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;
      }
    }

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