Skip to main content
Glama

search_quran

Search Quran verses by keywords or phrases to find relevant passages about specific topics like patience, prayer, or mercy using natural language queries.

Instructions

Search the Quran by keywords or phrases. This powerful tool allows you to find verses containing specific words or concepts without knowing the exact surah and ayah numbers. Perfect for finding verses about specific topics like "patience", "prayer", "mercy", etc. The AI agent can use natural language queries to search through the entire Quran.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query - keywords or phrases to search for in the Quran. Can be single words like "patience" or phrases like "those who believe". Minimum 2 characters.
translationNoTranslation to search in (default: en.sahih). Options: en.asad, en.sahih, en.pickthall, en.yusufali, en.hilalien.sahih
max_resultsNoMaximum number of results to return (default: 20, max: 50)

Implementation Reference

  • The core handler function that executes the search_quran tool. Performs intelligent fuzzy matching across all 114 Quran surahs in parallel, with relevance scoring, Arabic normalization, caching, and helpful suggestions.
    export async function searchQuran(
      query: string,
      translationSlug: string = 'en.sahih',
      maxResults: number = 20
    ): Promise<SearchResult[]> {
      if (!query || query.trim().length < 2) {
        throw new QuranMCPError(
          'Search query must be at least 2 characters long',
          'INVALID_SEARCH_QUERY'
        );
      }
    
      // Validate translation
      const translation = TRANSLATIONS.find(t => t.slug === translationSlug);
      if (!translation) {
        throw new QuranMCPError(
          `Unknown translation: ${translationSlug}. Available: ${TRANSLATIONS.map(t => t.slug).join(', ')}`,
          'INVALID_TRANSLATION'
        );
      }
    
      const cacheKey = `search:quran:${translationSlug}:${query}:${maxResults}`;
    
      return searchCacheService.getOrSet(cacheKey, async () => {
        const results: SearchResult[] = [];
        const keywords = query.toLowerCase().split(/\s+/).filter(k => k.length > 1);
        const isArabicQuery = isArabic(query);
    
        // OPTIMIZED: Fetch ALL surahs in parallel for maximum speed
        const fetchSlug = isArabicQuery ? 'ar.alafasy' : translationSlug;
    
        // Fetch all 114 surahs in parallel (Cloudflare Workers can handle this)
        const allPromises = SURAH_INFO.map(async (surahInfo) => {
          try {
            const url = `https://api.alquran.cloud/v1/surah/${surahInfo.number}/${fetchSlug}`;
            const response = await fetchJSON<any>(url);
    
            if (response.code === 200 && response.data && response.data.ayahs) {
              const surahResults: SearchResult[] = [];
              for (const ayah of response.data.ayahs) {
                const { score, matchType } = calculateRelevance(ayah.text, keywords);
    
                if (score > 0) {
                  surahResults.push({
                    surah: surahInfo.number,
                    ayah: ayah.numberInSurah,
                    surahName: surahInfo.name,
                    text: ayah.text,
                    translation: isArabicQuery ? 'Arabic' : translation.name,
                    relevanceScore: score,
                    matchType,
                  });
                }
              }
              return surahResults;
            }
          } catch (error) {
            // Continue searching other surahs even if one fails
            console.error(`Error searching surah ${surahInfo.number}:`, error);
          }
          return [];
        });
    
        // Wait for ALL requests to complete in parallel
        const allResults = await Promise.all(allPromises);
    
        // Flatten results
        for (const surahResults of allResults) {
          results.push(...surahResults);
        }
    
        // Sort by relevance and match type
        const sorted = results.sort((a, b) => {
          // Prioritize exact matches
          if (a.matchType === 'exact' && b.matchType !== 'exact') return -1;
          if (b.matchType === 'exact' && a.matchType !== 'exact') return 1;
          // Then by score
          return b.relevanceScore - a.relevanceScore;
        });
    
        const finalResults = sorted.slice(0, maxResults);
    
        // Add helpful message if no results or only fuzzy matches
        if (finalResults.length === 0) {
          console.log(`No results found for "${query}". Try different keywords or check spelling.`);
        } else if (finalResults.every(r => r.matchType !== 'exact')) {
          console.log(`No exact matches for "${query}". Showing ${finalResults.length} similar results.`);
        }
    
        return finalResults;
      });
    }
  • The MCP tool definition including name, description, and input schema (JSON Schema) for validating search_quran parameters.
    {
      name: 'search_quran',
      description: 'Search the Quran by keywords or phrases. This powerful tool allows you to find verses containing specific words or concepts without knowing the exact surah and ayah numbers. Perfect for finding verses about specific topics like "patience", "prayer", "mercy", etc. The AI agent can use natural language queries to search through the entire Quran.',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'Search query - keywords or phrases to search for in the Quran. Can be single words like "patience" or phrases like "those who believe". Minimum 2 characters.',
          },
          translation: {
            type: 'string',
            description: 'Translation to search in (default: en.sahih). Options: en.asad, en.sahih, en.pickthall, en.yusufali, en.hilali',
            default: 'en.sahih',
          },
          max_results: {
            type: 'number',
            description: 'Maximum number of results to return (default: 20, max: 50)',
            default: 20,
            maximum: 50,
          },
        },
        required: ['query'],
      },
    },
  • The switch case in the central tool executor that handles dispatching calls to the search_quran handler based on tool name.
    case 'search_quran': {
      const { query, translation = 'en.sahih', max_results = 20 } = args;
      result = await searchQuran(query, translation, max_results);
      break;
    }
  • Import statement that brings the searchQuran handler into the tool executor scope.
      searchHadith,
      searchHadithByTopic,
      searchQuran,
      searchQuranByTopic
    } from '../tools/search.js';
  • TypeScript interface defining expected parameters for Quran search (related to schema).
    export interface SearchQuranParams {
      query: string;
      language?: 'arabic' | 'english';
      translation?: string;
    }
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. It mentions 'powerful tool' and 'search through the entire Quran' but doesn't disclose important behavioral traits like rate limits, authentication requirements, search algorithm characteristics, or what happens with ambiguous queries. It does mention 'natural language queries' which adds some context beyond basic functionality.

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 appropriately sized with three sentences that each add value: purpose statement, use case examples, and natural language capability. It's front-loaded with the core functionality. Could be slightly more concise by combining some concepts, but overall efficient.

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?

For a search tool with 3 parameters, 100% schema coverage, but no annotations and no output schema, the description is adequate but has gaps. It explains the 'why' and 'when' well but doesn't address behavioral aspects like performance characteristics, result format, or error conditions that would help an agent use it effectively.

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%, so the schema already documents all parameters thoroughly. The description mentions 'keywords or phrases' which aligns with the query parameter, and 'specific topics' which relates to query usage, but adds minimal semantic value beyond what the schema provides. Baseline 3 is appropriate when schema does the heavy lifting.

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: 'Search the Quran by keywords or phrases' with specific examples like 'patience', 'prayer', 'mercy'. It distinguishes from siblings like get_quran_verse (which requires exact references) and search_quran_by_topic (which likely uses topic categorization rather than keyword search).

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

Usage Guidelines4/5

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

The description provides clear context: 'without knowing the exact surah and ayah numbers' and 'Perfect for finding verses about specific topics'. It implies when to use this tool (for keyword/concept searches) but doesn't explicitly state when NOT to use it or name specific alternatives among the many sibling tools.

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/Prince77-7/quranMCP'

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