Skip to main content
Glama

get_hadith

Retrieve specific Hadith sayings and actions of Prophet Muhammad (peace be upon him) from major collections including Bukhari, Muslim, and others by providing collection name and hadith number.

Instructions

Get a specific Hadith from a collection. Hadiths are sayings and actions of Prophet Muhammad (peace be upon him).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
collectionYesHadith collection name. Options: bukhari, muslim, abudawud, tirmidhi, nasai, ibnmajah
hadith_numberYesHadith number within the collection

Implementation Reference

  • Core implementation of the get_hadith tool: validates inputs, checks cache, fetches from API (English then Arabic fallback), parses response, and returns structured HadithResponse.
    export async function getHadith(
      collection: string,
      hadithNumber: number
    ): Promise<HadithResponse> {
      // Validate collection
      const collectionInfo = HADITH_COLLECTIONS.find(c => c.slug === collection);
      if (!collectionInfo) {
        throw new QuranMCPError(
          `Unknown hadith collection: ${collection}. Available collections: ${HADITH_COLLECTIONS.map(c => c.slug).join(', ')}`,
          'INVALID_COLLECTION'
        );
      }
    
      // Validate hadith number
      if (hadithNumber < 1 || hadithNumber > collectionInfo.totalHadiths) {
        throw new QuranMCPError(
          `Invalid hadith number: ${hadithNumber}. ${collectionInfo.name} has ${collectionInfo.totalHadiths} hadiths.`,
          'INVALID_HADITH_NUMBER'
        );
      }
    
      // Create cache key
      const cacheKey = `hadith:${collection}:${hadithNumber}`;
    
      // Try to get from cache or fetch
      return hadithCacheService.getOrSet(cacheKey, async () => {
        // Try English first, fallback to Arabic
        const endpoints = [
          `${API_ENDPOINTS.HADITH}/eng-${collection}/${hadithNumber}.json`,
          `${API_ENDPOINTS.HADITH}/ara-${collection}/${hadithNumber}.json`,
        ];
    
        let lastError: Error | null = null;
    
        for (const url of endpoints) {
          try {
            const data = await fetchJSON<any>(url);
    
            // Handle the actual API structure: { metadata: {...}, hadiths: [{text: "..."}] }
            let text = '';
            let book = undefined;
            let chapter = undefined;
            let grade = undefined;
            let narrator = undefined;
    
            if (data.hadiths && Array.isArray(data.hadiths) && data.hadiths.length > 0) {
              // Find the hadith with matching number
              const hadith = data.hadiths.find((h: any) => h.hadithnumber === hadithNumber) || data.hadiths[0];
              text = hadith.text || '';
              book = hadith.reference?.book;
              chapter = data.metadata?.section?.[book];
              grade = hadith.grades?.[0];
            } else {
              // Fallback to old structure
              text = data.text || data.hadith || '';
              book = data.book;
              chapter = data.chapter || data.chapterName;
              grade = data.grade;
              narrator = data.narrator;
            }
    
            return {
              hadithNumber,
              collection: collectionInfo.name,
              book,
              chapter,
              text,
              grade,
              narrator,
            };
          } catch (error) {
            lastError = error as Error;
            continue;
          }
        }
    
        throw new QuranMCPError(
          `Failed to fetch hadith: ${lastError?.message}`,
          'HADITH_FETCH_ERROR'
        );
      });
    }
  • MCP tool registration defining the name, description, and input schema for the get_hadith tool.
      name: 'get_hadith',
      description: 'Get a specific Hadith from a collection. Hadiths are sayings and actions of Prophet Muhammad (peace be upon him).',
      inputSchema: {
        type: 'object',
        properties: {
          collection: {
            type: 'string',
            description: 'Hadith collection name. Options: bukhari, muslim, abudawud, tirmidhi, nasai, ibnmajah',
            enum: ['bukhari', 'muslim', 'abudawud', 'tirmidhi', 'nasai', 'ibnmajah'],
          },
          hadith_number: {
            type: 'number',
            description: 'Hadith number within the collection',
            minimum: 1,
          },
        },
        required: ['collection', 'hadith_number'],
      },
    },
  • TypeScript interface for input parameters of the get_hadith tool.
    export interface GetHadithParams {
      collection: string;
      hadithNumber: number;
    }
  • TypeScript interface defining the output structure returned by get_hadith handler.
    export interface HadithResponse {
      hadithNumber: number;
      collection: string;
      book?: string;
      chapter?: string;
      text: string;
      grade?: string;
      narrator?: string;
    }
  • Dispatch logic in shared tool executor that invokes the getHadith handler for the 'get_hadith' tool name.
    case 'get_hadith': {
      const { collection, hadith_number } = args;
      result = await getHadith(collection, hadith_number);
      break;
    }
Behavior2/5

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

No annotations are provided, so the description carries full burden. It states the tool retrieves a Hadith but does not disclose behavioral traits such as error handling (e.g., if hadith_number is invalid), performance (e.g., response time), or output format (e.g., text, metadata). The description is minimal and lacks critical operational context.

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 concise with two sentences: one stating the purpose and one providing background on Hadiths. It is front-loaded with the core function, and the second sentence adds useful context without redundancy. However, it could be slightly more efficient by integrating the background more tightly.

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 no annotations and no output schema, the description is incomplete. It explains what the tool does but lacks details on behavior, output (e.g., what data is returned), error cases, or prerequisites. For a tool with 2 parameters and no structured output info, this leaves significant gaps for an AI 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?

Schema description coverage is 100%, with clear descriptions for both parameters (collection with enum options, hadith_number with minimum). The description adds no additional parameter semantics beyond what the schema provides, such as examples or usage notes. Baseline 3 is appropriate as the schema adequately documents parameters.

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's purpose: 'Get a specific Hadith from a collection' with a brief explanation of what Hadiths are. It uses a specific verb ('Get') and resource ('Hadith'), but does not explicitly differentiate from siblings like 'get_random_hadith' or 'search_hadith' beyond implying specificity by 'specific'.

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 mentions 'specific Hadith' but does not clarify scenarios (e.g., when you know the exact collection and number) or contrast with siblings like 'search_hadith' for unknown numbers or 'get_random_hadith' for random access. Usage is implied but not explicit.

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