#!/usr/bin/env node import { Server } from "@modelcontextprotocol/sdk/server/index.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import * as fs from "node:fs"; import * as path from "node:path"; const VERSION = "0.2.0"; const HF_BASE_URL = process.env.QURAN_MD_BASE_URL || "https://huggingface.co/datasets/bravesigma/quran-md-data/resolve/main"; const LOCAL_DATA_DIR = process.env.QURAN_MD_LOCAL_DIR || ""; async function fetchDataFile(relPath: string): Promise { if (LOCAL_DATA_DIR) { const localPath = path.join(LOCAL_DATA_DIR, relPath); if (fs.existsSync(localPath)) { return fs.readFileSync(localPath, "utf-8"); } } const url = `${HF_BASE_URL}/${relPath}`; const res = await fetch(url); if (!res.ok) { throw new Error(`Failed to fetch ${relPath} from ${url} (${res.status})`); } return await res.text(); } function pad3(n: number): string { return String(n).padStart(3, "0"); } async function getVerseJson(surah: number, ayah: number): Promise { const relPath = `raw/${pad3(surah)}-${pad3(ayah)}.json`; const text = await fetchDataFile(relPath); return JSON.parse(text); } async function getJsonl(name: string): Promise { const text = await fetchDataFile(`data/${name}`); return text .split("\n") .filter((l) => l.trim()) .map((l) => JSON.parse(l)); } // words data is sharded into plain-text parts under the HF 10MiB git limit; // data/words_manifest.json lists the parts in order with sha256. async function getWords(): Promise { const manifestText = await fetchDataFile("data/words_manifest.json"); const manifest = JSON.parse(manifestText); const out: any[] = []; for (const part of manifest.parts) { const text = await fetchDataFile(`data/${part.file}`); for (const line of text.split("\n")) { if (line.trim()) out.push(JSON.parse(line)); } } return out; } // Every tool response carries provenance and consensus_level (Phase 7 rule). const PROVENANCE = { source_repo: "bravesigma/quran-md-data (HF datasets)", data_version: "schema v2.0.0", grounding_rule: "All quotes are verbatim substrings of stored source files with sha256 provenance; positions carry consensus_level; xref edges are review-queue items until human-approved.", consensus_level_note: "consensus_level values: agreed | majority | disputed | single_source (null = not yet established)", }; function wrap(payload: any) { return { ...payload, _provenance: PROVENANCE }; } async function startMcpServer() { const server = new Server( { name: "quran-md", version: VERSION }, { capabilities: { tools: {} } } ); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "get_manifest", description: "Returns the root quran.md anti-bias grounding instructions and methodology.", inputSchema: { type: "object", properties: {} }, }, { name: "get_verse", description: "Fetch canonical Quranic verse analysis (Arabic roots, Sunni & Shia tafsirs/hadiths, Isnad/Matn audit).", inputSchema: { type: "object", properties: { surah: { type: "number", description: "Surah number (1-114)" }, ayah: { type: "number", description: "Ayah number" }, }, required: ["surah", "ayah"], }, }, { name: "compare_traditions", description: "Compare Sunni and Shia canonical perspectives (tafsir, hadith, positions[]) alongside the Isnad/Matn audit for a verse. Response includes provenance and consensus_level.", inputSchema: { type: "object", properties: { surah: { type: "number", description: "Surah number (1-114)" }, ayah: { type: "number", description: "Ayah number" }, }, required: ["surah", "ayah"], }, }, { name: "get_roots", description: "Word-level morphology (form, lemma, root, POS) for a verse from the Quranic Arabic Corpus, plus IDF-weighted lexical cross-reference edges. Every root/lemma claim is corpus-verified.", inputSchema: { type: "object", properties: { surah: { type: "number", description: "Surah number (1-114)" }, ayah: { type: "number", description: "Ayah number" }, }, required: ["surah", "ayah"], }, }, { name: "get_xrefs", description: "Cross-reference edges for a verse (lexical shared root/lemma with IDF weighting; exegetical tafsir-citation edges; classifier relations). Items marked review_status='queue' are NOT human-approved — treat relations as candidate, never as established fact.", inputSchema: { type: "object", properties: { surah: { type: "number", description: "Surah number (1-114)" }, ayah: { type: "number", description: "Ayah number" }, limit: { type: "number", description: "Max edges returned (default 25)" }, }, required: ["surah", "ayah"], }, }, { name: "get_commentary", description: "Tafsir commentary units for a verse (optionally filtered by tradition: sunni|imami). quote_ar fields are verbatim substrings of stored source files with sha256; summary fields (if any) carry generated_by and are paraphrases.", inputSchema: { type: "object", properties: { ayah: { type: "string", description: "Verse key, e.g. '6:74'" }, tradition: { type: "string", enum: ["sunni", "imami"], description: "Optional filter" }, }, required: ["ayah"], }, }, { name: "audit_hadith", description: "Isnad/Matn audit for hadith records linked to a verse: per-criteria-set checks (sunni_classical, imami_classical — never merged into one score), typed matn claims, ghayb rule applied, 'ard 'ala al-Quran as shared test. Unresolved is a valid result.", inputSchema: { type: "object", properties: { surah: { type: "number" }, ayah: { type: "number" }, }, required: ["surah", "ayah"], }, }, ], })); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { if (name === "get_manifest") { const md = await fetchDataFile("quran.md"); return { content: [{ type: "text", text: md }] }; } if (name === "get_verse") { const surah = Number(args?.surah); const ayah = Number(args?.ayah); const data = await getVerseJson(surah, ayah); return { content: [{ type: "text", text: JSON.stringify(wrap(data), null, 2) }], }; } if (name === "compare_traditions") { const surah = Number(args?.surah); const ayah = Number(args?.ayah); const data = await getVerseJson(surah, ayah); const comparison = { verse: data.verse_key, arabic_text: data.arabic_text, roots: data.roots, words_corpus_verified: (data.words || []).length, sunni: { ...data.sunni_perspectives, consensus_level: data.sunni_perspectives?.consensus_level ?? null, }, shia: { ...data.shia_perspectives, consensus_level: data.shia_perspectives?.consensus_level ?? null, }, positions: data.positions || [], isnad_matn_audit: data.isnad_matn_audit, data_flags: data.data_flags || [], }; return { content: [ { type: "text", text: JSON.stringify(wrap(comparison), null, 2) }, ], }; } if (name === "get_roots") { const surah = Number(args?.surah); const ayah = Number(args?.ayah); const vk = `${surah}:${ayah}`; const words = await getWords(); const mine = words.filter((w) => w.ref.startsWith(`${vk}:`) ); const allEdges = await getJsonl("xref_edges.jsonl"); const lexical = allEdges.filter( (e) => e.from === vk && e.source === "lexical" ); return { content: [ { type: "text", text: JSON.stringify( wrap({ verse: vk, word_count: mine.length, words: mine, roots_index: [...new Set(mine.map((w: any) => w.root).filter(Boolean))], lexical_edges: lexical.slice(0, 25), corpus_verified: true, }), null, 2 ), }, ], }; } if (name === "get_xrefs") { const surah = Number(args?.surah); const ayah = Number(args?.ayah); const limit = Number(args?.limit) || 25; const vk = `${surah}:${ayah}`; const allEdges = await getJsonl("xref_edges.jsonl"); const mine = allEdges.filter( (e) => e.from === vk || e.to === vk ); return { content: [ { type: "text", text: JSON.stringify( wrap({ verse: vk, total_edges: mine.length, edges: mine.slice(0, limit), warning: "Edges carry review_status; 'queue' = not human-approved. Classified relations are LLM-assigned from closed set, pending review.", }), null, 2 ), }, ], }; } if (name === "get_commentary") { const ayahKey = String(args?.ayah || ""); const tradition = args?.tradition; const units = await getJsonl("commentary_units.jsonl"); let mine = units.filter((u) => u.span?.start === ayahKey || u.span?.end === ayahKey); if (tradition) { mine = mine.filter((u) => u.tradition === tradition); } const trimmed = mine.map((u) => ({ id: u.id, work: u.work, author: u.author, tradition: u.tradition, span: u.span, span_roles: u.span_roles, section_type: u.section_type, quote_ar: u.quote_ar.slice(0, 1200), quote_verbatim: true, source_sha256: u.quote_location?.source_sha256, attribution_flags: u.attribution_flags, ayah_citations: u.ayah_citations, license: u.provenance?.license, })); return { content: [ { type: "text", text: JSON.stringify( wrap({ ayah: ayahKey, tradition_filter: tradition || null, units: trimmed, imami_note: mine.length > 0 ? undefined : "No Imami commentary units ingested yet: Al-Mizan is license-blocked (see sources/manifest.json), Majma' al-Bayan / Tafsir al-Qummi pending clean-source transcription. Imami positions for this verse are therefore sourced only from the legacy enrichment (flagged unverified_recall).", }), null, 2 ), }, ], }; } if (name === "audit_hadith") { const surah = Number(args?.surah); const ayah = Number(args?.ayah); const vk = `${surah}:${ayah}`; const hadiths = await getJsonl("hadith.jsonl"); const audits = await getJsonl("audits.jsonl"); const narrators = await getJsonl("narrators.jsonl"); const mine = hadiths.filter((h) => (h.linked_ayat || []).some((l: any) => l.ref === vk) ); const mineAudits = audits.filter((a) => mine.some((h) => h.id === a.target) ); return { content: [ { type: "text", text: JSON.stringify( wrap({ verse: vk, hadiths: mine, audits: mineAudits, narrators, discipline: "No numeric trust score. Each criteria set reports result+why independently; ghayb/eschatological claims are audited for transmission and internal coherence only; 'ard 'ala al-Quran is the stated shared test.", }), null, 2 ), }, ], }; } throw new Error(`Unknown tool: ${name}`); } catch (err: any) { return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true, }; } }); const transport = new StdioServerTransport(); await server.connect(transport); } async function main() { const args = process.argv.slice(2); const cmd = args[0]; if (cmd === "mcp") { await startMcpServer(); return; } if (cmd === "init") { const md = await fetchDataFile("quran.md"); fs.writeFileSync("quran.md", md, "utf-8"); console.log("Created quran.md in current directory."); return; } if (cmd === "sources") { const m = await fetchDataFile("sources/manifest.json"); const parsed = JSON.parse(m); console.log( JSON.stringify( { license_policy: parsed.policy, sources: parsed.sources.map((s: any) => ({ id: s.id, license: s.license?.value, hf_redistribution: s.redistribution?.huggingface, state: s.proposed_state, })), }, null, 2 ) ); return; } if (cmd && cmd.includes(":")) { const [s, a] = cmd.split(":").map(Number); const data = await getVerseJson(s, a); console.log(JSON.stringify(wrap(data), null, 2)); return; } console.log(`quran-md v${VERSION} Usage: npx quran-md mcp Start MCP server (for Claude, Cursor, Windsurf, etc.) npx quran-md init Download root quran.md manifest into current folder npx quran-md sources Print the license manifest (per-source state) npx quran-md Fetch canonical JSON for a verse (e.g. 6:74)`); } main().catch((err) => { console.error(err); process.exit(1); });