Skip to main content
Glama
djalal

quran-mcp-server

by djalal

random_verse

Retrieve a random Quran verse with optional translations, audio, tafsirs, and word details in your preferred language for study or reflection.

Instructions

Get a random verse

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
audioNoId of recitation
fieldsNoComma separated list of ayah fields
languageNoLanguage to fetch word translation
tafsirsNoComma separated ids of tafsirs
translation_fieldsNoComma separated list of translation fields
translationsNoComma separated ids of translations
word_fieldsNoComma separated list of word fields
wordsNoInclude words of each ayah

Implementation Reference

  • Handler function that executes the random_verse tool: validates args with Zod schema, calls versesService.randomVerse, logs response/error, returns formatted content or error.
    /**
     * Handler for the random_verse tool
     */
    export async function handleRandomVerse(args: any) {
      try {
        // Validate arguments
        const validatedArgs = randomVerseSchema.parse(args);
        
        // Call the service
        const result = await versesService.randomVerse(validatedArgs);
        
        // Log the response in verbose mode
        verboseLog('response', {
          tool: 'random_verse',
          result
        });
        
        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        // Enhanced error logging with more details
        verboseLog('error', {
          tool: 'random_verse',
          error: error instanceof Error 
            ? { 
                name: error.name,
                message: error.message,
                stack: error.stack,
                // Include additional properties if they exist
                ...(error as any)
              } 
            : String(error)
        });
        
        if (error instanceof z.ZodError) {
          return {
            content: [{ 
              type: "text", 
              text: `Validation error: ${error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`
            }],
            isError: true,
          };
        }
        
        // Provide more detailed error message
        const errorMessage = error instanceof Error 
          ? `Error: ${error.name}: ${error.message}` 
          : `Unknown error: ${String(error)}`;
        
        return {
          content: [{ 
            type: "text", 
            text: errorMessage
          }],
          isError: true,
        };
      }
    }
  • Zod input schema for random_verse tool parameters (inherits commonVerseParams like language, words, etc.).
    /**
     * Schema for random_verse
     */
    export const randomVerseSchema = z.object({
      ...commonVerseParams,
    });
  • src/server.ts:172-177 (registration)
    Tool registration in listToolsResponse: defines name, description, inputSchema from versesSchemas.randomVerse, and examples.
    {
      name: ApiTools.random_verse,
      description: "Get a random verse",
      inputSchema: zodToJsonSchema(versesSchemas.randomVerse),
      examples: toolExamples['random_verse'],
    },
  • src/server.ts:277-278 (registration)
    Switch case in CallToolRequest handler that dispatches random_verse calls to handleRandomVerse.
    case ApiTools.random_verse:
      return await handleRandomVerse(request.params.arguments);
  • Supporting service method that performs the actual API request to Quran.com /verses/random endpoint with parameters, handles validation and errors.
    /**
     * Get random verse
     * Get a random verse. You can get random verse from a specific `chapter`,`page`, `juz`, `hizb`, `rub-el-hizb`, `ruku`, `manzil`, or from whole Quran.
     * 
     * @param {Object} params - The parameters for this operation
     * @returns {Promise<RandomVerseResponse>} The operation result
     * @throws {ApiError} If the operation fails
     */
    async randomVerse(params: z.infer<typeof randomVerseSchema>): Promise<RandomVerseResponse> {
      try {
        // Validate parameters
        const validatedParams = randomVerseSchema.parse(params);
        
        const url = `${API_BASE_URL}/verses/random`;
        
        // Make request to Quran.com API
        const data = await makeApiRequest(url, {
          language: validatedParams.language,
          words: validatedParams.words,
          translations: validatedParams.translations,
          audio: validatedParams.audio,
          tafsirs: validatedParams.tafsirs,
          word_fields: validatedParams.word_fields,
          translation_fields: validatedParams.translation_fields,
          fields: validatedParams.fields
        });
        
        return {
          success: true,
          message: "random_verse executed successfully",
          data
        };
      } catch (error) {
        verboseLog('error', {
          method: 'randomVerse',
          error: error instanceof Error ? error.message : String(error)
        });
        
        if (error instanceof z.ZodError) {
          throw new ApiError(`Validation error: ${error.errors.map(e => `${e.path.join('.')}: ${e.message}`).join(', ')}`, 400);
        }
        
        // Re-throw other errors
        throw error;
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'Get a random verse' implies a read-only operation, but it fails to specify aspects like whether the randomness is weighted, if there are rate limits, authentication requirements, or what the output format includes. This leaves significant gaps in understanding the tool's behavior.

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 extremely concise with just three words, front-loading the core purpose without any wasted text. It efficiently communicates the essential action, making it easy to parse and understand quickly.

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?

Given the complexity of 8 parameters and no annotations or output schema, the description is incomplete. It does not explain how parameters like 'tafsirs' or 'translations' influence the result, what the return values look like, or any behavioral traits. For a tool with rich optional parameters, more context is needed to guide effective use.

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?

The input schema has 100% description coverage, so the schema already documents all 8 parameters (e.g., 'audio', 'fields', 'language'). The description adds no additional meaning or context about these parameters, such as how they affect the random selection or output. With high schema coverage, the baseline score of 3 is appropriate.

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 'Get a random verse' clearly states the verb ('Get') and resource ('a random verse'), making the purpose immediately understandable. However, it does not differentiate from sibling tools like 'verses-by_chapter_number' or 'search', which might also retrieve verses but with different scopes or methods.

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. It lacks context such as whether this is for quick access, educational purposes, or specific use cases compared to other verse-retrieval tools in the sibling list, leaving the agent to infer 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

Related 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/djalal/quran-mcp-server'

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