rbi-doc-mcp 0.0.0-stage → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,97 @@
1
- # Temporary Holding Version
1
+ # `rbi-doc-mcp`: Reserve Bank of India (RBI) Regulatory Archive MCP Server & Local CLI (1991-2026)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![Public Web Portal](https://img.shields.io/badge/Web_Portal-https%3A%2F%2Frbi--archive.pages.dev-blue.svg)](https://rbi-archive.pages.dev)
4
+ [![Official MCP Endpoint](https://img.shields.io/badge/MCP_Endpoint-https%3A%2F%2Frbi--archive.pages.dev%2Fmcp-green.svg)](https://rbi-archive.pages.dev/mcp)
5
+ [![Archive Corpus](https://img.shields.io/badge/RBI_Regulatory_Corpus-88%2C236_Documents_(1991--2026)-amber.svg)](https://github.com/imsovikde/rbi-regulatory-archive-1991-2026)
6
+
7
+ `rbi-doc-mcp` is the official Model Context Protocol (MCP) command-line bridge and offline-capable local BM25F regulatory query engine for the **Reserve Bank of India (RBI) Regulatory Archive (1991-2026)**, covering all **88,236** publicly available RBI Master Directions, Master Circulars, Circulars, Notifications, Draft Guidelines, and Press Releases converted to SHA-256-verified GitHub-Flavored Markdown.
8
+
9
+ - **Public Web Portal & Interactive Terminal**: [https://rbi-archive.pages.dev](https://rbi-archive.pages.dev)
10
+ - **Official Streamable HTTP MCP Endpoint**: `https://rbi-archive.pages.dev/mcp`
11
+ - **User Account & Usage Dashboard**: [https://rbi-archive.pages.dev/account](https://rbi-archive.pages.dev/account)
12
+ - **Public Regulatory Archive & Full Guide**: [github.com/imsovikde/rbi-regulatory-archive-1991-2026](https://github.com/imsovikde/rbi-regulatory-archive-1991-2026) ([Complete MCP Guide](https://github.com/imsovikde/rbi-regulatory-archive-1991-2026/blob/main/mcp-guide.md))
13
+
14
+ ---
15
+
16
+ ## Quick Start
17
+
18
+ ### 1. Zero-Cost Local Stdio MCP Server (`--local`)
19
+
20
+ Run a local Model Context Protocol server over `stdio` that queries the sharded BM25F static index (`https://rbi-archive.pages.dev/idx/v2`) with persistent local disk caching (`~/.cache/rbi-doc-mcp/idx-v2`) and fetches full regulatory Markdown directly from the public GitHub Raw and Hugging Face mirrors:
21
+
22
+ ```bash
23
+ npx rbi-doc-mcp --local
24
+ ```
25
+
26
+ ### 2. Direct Terminal Search, Resolution & Validity Verification
27
+
28
+ You can also query the 88,236-document archive directly from your terminal:
29
+
30
+ ```bash
31
+ # Search RBI Master Directions and Circulars using BM25F ranking
32
+ npx rbi-doc-mcp --search "Know Your Customer Master Direction"
33
+
34
+ # Resolve an official RBI circular reference number or canonical document ID
35
+ npx rbi-doc-mcp --resolve "RBI/2017-18/15"
36
+
37
+ # Verify whether a circular was legally in force (ACTIVE, SUPERSEDED, or REPEALED) on a specific date
38
+ npx rbi-doc-mcp --validity "rbi_081878" 2026-01-01
39
+ ```
40
+
41
+ ### 3. Remote Streamable HTTP MCP Connection
42
+
43
+ For cloud-hosted multi-step JavaScript Code Mode (`rbi_doc_execute_code`), clause-level RAG (`rag_query_rbi_provisions`), and OAuth 2.1 session management, connect your MCP client directly to `https://rbi-archive.pages.dev/mcp`:
44
+
45
+ ```bash
46
+ claude mcp add --transport http rbi-archive https://rbi-archive.pages.dev/mcp
47
+ ```
48
+
49
+ ---
50
+
51
+ ## Client Configuration (`claude_desktop_config.json`, Cursor, VS Code, Windsurf)
52
+
53
+ ### Local Stdio Mode (`npx rbi-doc-mcp --local`)
54
+
55
+ ```json
56
+ {
57
+ "mcpServers": {
58
+ "rbi-archive-local": {
59
+ "command": "npx",
60
+ "args": ["-y", "rbi-doc-mcp", "--local"]
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ ### Remote Streamable HTTP Mode (`https://rbi-archive.pages.dev/mcp`)
67
+
68
+ ```json
69
+ {
70
+ "mcpServers": {
71
+ "rbi-archive": {
72
+ "url": "https://rbi-archive.pages.dev/mcp"
73
+ }
74
+ }
75
+ }
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Available MCP Tools
81
+
82
+ | Tool Name | Purpose |
83
+ | :--- | :--- |
84
+ | `search_rbi_regulations` | Hybrid BM25F search across all 88,236 RBI regulatory documents (1991-2026) with category and year filtering |
85
+ | `resolve_rbi_doc` / `resolve_rbi_document` | Resolve official RBI circular references (`RBI/2024-25/...`, `DOR.No...`, `DBOD.No...`), numeric IDs, or file paths into canonical metadata and SHA-256 digests |
86
+ | `fetch_rbi_markdown` / `fetch_rbi_document` | Retrieve verified GitHub-Flavored Markdown text for any RBI circular or Master Direction |
87
+ | `verify_circular_validity` | Point-in-time legal validity check (`ACTIVE`, `SUPERSEDED`, `REPEALED`) on any `YYYY-MM-DD` date |
88
+ | `trace_statutory_consequences` | Trace causal supersession and amendment chains across the statutory DAG |
89
+ | `format_court_citation` / `get_rbi_citation` | Format judicial citations with official reference numbers, dates, and SHA-256 verification hashes |
90
+ | `rag_query_rbi_provisions` | Clause-level retrieval over Content-Defined Chunked (CDC) statutory provisions (Remote HTTP endpoint) |
91
+ | `rbi_doc_execute_code` | Single-turn sandboxed JavaScript execution (`sdk.*`) for multi-hop regulatory joins (Remote HTTP endpoint) |
92
+
93
+ ---
94
+
95
+ ## License
96
+
97
+ Apache-2.0. Regulatory documents are public publications of the Reserve Bank of India.
@@ -0,0 +1,139 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ const readline = require("readline");
5
+ const { LocalRbiEngine } = require("../lib/local_mode");
6
+ const pkg = require("../package.json");
7
+
8
+ const args = process.argv.slice(2);
9
+
10
+ if (args.includes("--version") || args.includes("-v")) {
11
+ process.stdout.write(`${pkg.name} v${pkg.version}\n`);
12
+ process.exit(0);
13
+ }
14
+
15
+ if (args.includes("--help") || args.includes("-h")) {
16
+ process.stdout.write(
17
+ [
18
+ `${pkg.name} v${pkg.version} - Reserve Bank of India (RBI) Regulatory Archive MCP CLI (1991-2026, 88,236 documents)`,
19
+ "",
20
+ "Usage:",
21
+ " npx rbi-doc-mcp --local Start offline/static stdio MCP server (0 Worker requests)",
22
+ " npx rbi-doc-mcp Start remote stdio bridge to https://rbi-archive.pages.dev/mcp",
23
+ " npx rbi-doc-mcp --search \"<query>\" Run a direct CLI BM25F regulatory search and print JSON",
24
+ " npx rbi-doc-mcp --resolve \"<id_or_ref>\" Resolve an RBI circular reference or doc_id and print JSON",
25
+ " npx rbi-doc-mcp --validity \"<doc_id>\" Check point-in-time circular validity and print JSON",
26
+ " npx rbi-doc-mcp --version Print package version",
27
+ " npx rbi-doc-mcp --help Show this usage guide",
28
+ "",
29
+ "Public Web Portal: https://rbi-archive.pages.dev",
30
+ "Official MCP Server: https://rbi-archive.pages.dev/mcp",
31
+ "Public Documentation: https://github.com/imsovikde/rbi-regulatory-archive-1991-2026/blob/main/mcp-guide.md",
32
+ "",
33
+ ].join("\n")
34
+ );
35
+ process.exit(0);
36
+ }
37
+
38
+ const IS_LOCAL =
39
+ args.includes("--local") ||
40
+ String(process.env.RBI_DOC_MCP_MODE || "").toLowerCase() === "local";
41
+
42
+ const REMOTE_ENDPOINT = process.env.RBI_DOC_MCP_URL || "https://rbi-archive.pages.dev/mcp";
43
+ const API_KEY = process.env.RBI_DOC_MCP_API_KEY || "";
44
+ const CF_ACCESS_CLIENT_ID = process.env.CF_ACCESS_CLIENT_ID || "";
45
+ const CF_ACCESS_CLIENT_SECRET = process.env.CF_ACCESS_CLIENT_SECRET || "";
46
+
47
+ const searchIdx = args.indexOf("--search");
48
+ const resolveIdx = args.indexOf("--resolve");
49
+ const validityIdx = args.indexOf("--validity");
50
+
51
+ if (searchIdx !== -1 || resolveIdx !== -1 || validityIdx !== -1) {
52
+ (async () => {
53
+ const engine = new LocalRbiEngine();
54
+ let result;
55
+ if (searchIdx !== -1) {
56
+ const q = args[searchIdx + 1] || "";
57
+ result = await engine.searchRegulations({ query: q, limit: 5 });
58
+ } else if (resolveIdx !== -1) {
59
+ const id = args[resolveIdx + 1] || "";
60
+ result = await engine.resolveDocument(id);
61
+ } else if (validityIdx !== -1) {
62
+ const id = args[validityIdx + 1] || "";
63
+ const asOf = args[validityIdx + 2] && !args[validityIdx + 2].startsWith("--") ? args[validityIdx + 2] : undefined;
64
+ result = await engine.verifyValidity(id, asOf);
65
+ }
66
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
67
+ process.exit(0);
68
+ })().catch((err) => {
69
+ process.stderr.write(`Error: ${err.message}\n`);
70
+ process.exit(1);
71
+ });
72
+ return;
73
+ }
74
+
75
+ const localEngine = IS_LOCAL ? new LocalRbiEngine() : null;
76
+
77
+ const rl = readline.createInterface({
78
+ input: process.stdin,
79
+ output: process.stdout,
80
+ terminal: false,
81
+ });
82
+
83
+ async function forwardRpc(payload) {
84
+ if (IS_LOCAL && localEngine) {
85
+ return localEngine.handleJsonRpc(payload);
86
+ }
87
+
88
+ const headers = {
89
+ "Content-Type": "application/json",
90
+ };
91
+ if (API_KEY) {
92
+ headers["Authorization"] = `Bearer ${API_KEY}`;
93
+ }
94
+ if (CF_ACCESS_CLIENT_ID && CF_ACCESS_CLIENT_SECRET) {
95
+ headers["CF-Access-Client-Id"] = CF_ACCESS_CLIENT_ID;
96
+ headers["CF-Access-Client-Secret"] = CF_ACCESS_CLIENT_SECRET;
97
+ }
98
+
99
+ try {
100
+ const res = await fetch(REMOTE_ENDPOINT, {
101
+ method: "POST",
102
+ headers,
103
+ body: JSON.stringify(payload),
104
+ });
105
+ return await res.json();
106
+ } catch (err) {
107
+ return {
108
+ jsonrpc: "2.0",
109
+ id: payload.id || null,
110
+ error: {
111
+ code: -32603,
112
+ message: `Failed to connect to RBI DOC MCP endpoint: ${err.message}`,
113
+ },
114
+ };
115
+ }
116
+ }
117
+
118
+ rl.on("line", async (line) => {
119
+ const trimmed = line.trim();
120
+ if (!trimmed) return;
121
+
122
+ try {
123
+ const parsed = JSON.parse(trimmed);
124
+ const response = await forwardRpc(parsed);
125
+ if (response !== null && response !== undefined) {
126
+ process.stdout.write(JSON.stringify(response) + "\n");
127
+ }
128
+ } catch (err) {
129
+ const errResponse = {
130
+ jsonrpc: "2.0",
131
+ id: null,
132
+ error: {
133
+ code: -32700,
134
+ message: `Invalid JSON payload: ${err.message}`,
135
+ },
136
+ };
137
+ process.stdout.write(JSON.stringify(errResponse) + "\n");
138
+ }
139
+ });
@@ -0,0 +1,502 @@
1
+ "use strict";
2
+
3
+ const fs = require("fs");
4
+ const os = require("os");
5
+ const path = require("path");
6
+
7
+ const DEFAULT_STATIC_BASE = "https://rbi-archive.pages.dev/idx/v2";
8
+ const DEFAULT_GITHUB_RAW_BASE =
9
+ "https://raw.githubusercontent.com/imsovikde/rbi-regulatory-archive-1991-2026/main";
10
+ const DEFAULT_HF_RAW_BASE =
11
+ "https://huggingface.co/datasets/imsovikde/rbi-regulatory-archive-1991-2026/resolve/main";
12
+
13
+ const STOPWORDS = new Set([
14
+ "a", "an", "and", "are", "as", "at", "be", "been", "being", "by", "for", "from",
15
+ "has", "have", "had", "in", "into", "is", "it", "its", "of", "on", "or", "that",
16
+ "the", "their", "this", "to", "under", "was", "were", "will", "with", "which",
17
+ "shall", "may", "not", "all", "any", "such", "other", "also", "no", "page",
18
+ "reserve", "bank", "india", "rbi",
19
+ ]);
20
+
21
+ function fnv1a32(input) {
22
+ const bytes = Buffer.from(String(input || ""), "utf8");
23
+ let h = 0x811c9dc5;
24
+ for (let i = 0; i < bytes.length; i++) {
25
+ h ^= bytes[i];
26
+ h = Math.imul(h, 0x01000193);
27
+ }
28
+ return h >>> 0;
29
+ }
30
+
31
+ function normalizeReferenceKey(raw, preserveUnderscore = true) {
32
+ let s = String(raw || "").normalize("NFC").trim().toUpperCase();
33
+ s = s.replace(/^RBINO\.?\s*/, "RBI/");
34
+ s = s.replace(/(\d{4})-(?:\d{2})(\d{2})\b/g, "$1-$2");
35
+ s = s.replace(/\s+/g, "");
36
+ s = preserveUnderscore
37
+ ? s.replace(/[^A-Z0-9/._-]/g, "")
38
+ : s.replace(/[^A-Z0-9/.-]/g, "");
39
+ return s.replace(/^[./-]+|[./-]+$/g, "");
40
+ }
41
+
42
+ function tokenize(query) {
43
+ const raw = String(query || "")
44
+ .normalize("NFC")
45
+ .toLowerCase()
46
+ .split(/[^a-z0-9]+/)
47
+ .filter(Boolean);
48
+ const out = [];
49
+ for (const t of raw) {
50
+ if (t.length < 2 || STOPWORDS.has(t)) continue;
51
+ if (!out.includes(t)) out.push(t);
52
+ }
53
+ return out.slice(0, 12);
54
+ }
55
+
56
+ const LOCAL_TOOLS = [
57
+ {
58
+ name: "search_rbi_regulations",
59
+ description: "Tier-2 zero-Worker-cost BM25F search over static sharded RBI index (/idx/v2/*).",
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: {
63
+ query: { type: "string" },
64
+ limit: { type: "number" },
65
+ category: { type: "string" },
66
+ year: { type: "number" },
67
+ },
68
+ required: ["query"],
69
+ },
70
+ },
71
+ {
72
+ name: "resolve_rbi_doc",
73
+ description: "Resolve an RBI circular number, rbi_XXXXXX ID, or path from static alias shards.",
74
+ inputSchema: {
75
+ type: "object",
76
+ properties: { identifier: { type: "string" } },
77
+ required: ["identifier"],
78
+ },
79
+ },
80
+ {
81
+ name: "resolve_rbi_document",
82
+ description: "Resolve an RBI circular number, rbi_XXXXXX ID, or path from static alias shards.",
83
+ inputSchema: {
84
+ type: "object",
85
+ properties: { identifier: { type: "string" } },
86
+ required: ["identifier"],
87
+ },
88
+ },
89
+ {
90
+ name: "verify_circular_validity",
91
+ description: "Evaluate point-in-time legal validity using static validity_graph.json.",
92
+ inputSchema: {
93
+ type: "object",
94
+ properties: { doc_id: { type: "string" }, as_of_date: { type: "string" } },
95
+ required: ["doc_id"],
96
+ },
97
+ },
98
+ {
99
+ name: "format_court_citation",
100
+ description: "Format a clean court-ready citation for an RBI circular.",
101
+ inputSchema: {
102
+ type: "object",
103
+ properties: { identifier: { type: "string" }, doc_id: { type: "string" } },
104
+ },
105
+ },
106
+ {
107
+ name: "get_rbi_citation",
108
+ description: "Format a clean court-ready citation for an RBI circular.",
109
+ inputSchema: {
110
+ type: "object",
111
+ properties: { doc_id: { type: "string" } },
112
+ required: ["doc_id"],
113
+ },
114
+ },
115
+ {
116
+ name: "fetch_rbi_markdown",
117
+ description: "Fetch full RBI regulation Markdown directly from GitHub Raw (with Hugging Face fallback) at 0 Worker cost.",
118
+ inputSchema: {
119
+ type: "object",
120
+ properties: { doc_id: { type: "string" }, max_chars: { type: "number" } },
121
+ required: ["doc_id"],
122
+ },
123
+ },
124
+ {
125
+ name: "fetch_rbi_document",
126
+ description: "Fetch full RBI regulation Markdown directly from GitHub Raw (with Hugging Face fallback) at 0 Worker cost.",
127
+ inputSchema: {
128
+ type: "object",
129
+ properties: { doc_id: { type: "string" }, max_chars: { type: "number" } },
130
+ required: ["doc_id"],
131
+ },
132
+ },
133
+ {
134
+ name: "trace_statutory_consequences",
135
+ description: "Trace statutory supersession and repeal edges from the static validity DAG.",
136
+ inputSchema: {
137
+ type: "object",
138
+ properties: { doc_id: { type: "string" } },
139
+ required: ["doc_id"],
140
+ },
141
+ },
142
+ {
143
+ name: "get_corpus_overview",
144
+ description: "Return RBI regulatory corpus statistics from static manifest.",
145
+ inputSchema: { type: "object", properties: {} },
146
+ },
147
+ ];
148
+
149
+ class LocalRbiEngine {
150
+ constructor(opts = {}) {
151
+ this.staticBase = String(opts.staticBase || process.env.RBI_STATIC_INDEX_URL || DEFAULT_STATIC_BASE).replace(/\/+$/, "");
152
+ this.githubRawBase = String(opts.githubRawBase || DEFAULT_GITHUB_RAW_BASE).replace(/\/+$/, "");
153
+ this.hfRawBase = String(opts.hfRawBase || DEFAULT_HF_RAW_BASE).replace(/\/+$/, "");
154
+ this.staticDir = opts.staticDir || null;
155
+ this.cacheDir =
156
+ opts.cacheDir ||
157
+ path.join(process.env.XDG_CACHE_HOME || path.join(os.homedir(), ".cache"), "rbi-doc-mcp", "idx-v2");
158
+ this.fetchImpl = opts.fetchImpl || globalThis.fetch;
159
+ this.memCache = new Map();
160
+ this.coreBundle = null;
161
+ }
162
+
163
+ _safeRelPath(relPath) {
164
+ const cleaned = String(relPath || "").replace(/\\/g, "/").replace(/^\/+/, "");
165
+ if (!cleaned || cleaned.includes("..")) {
166
+ throw new Error(`Invalid shard path: ${relPath}`);
167
+ }
168
+ return cleaned;
169
+ }
170
+
171
+ async loadJsonShard(relPath) {
172
+ const safe = this._safeRelPath(relPath);
173
+ if (this.memCache.has(safe)) return this.memCache.get(safe);
174
+
175
+ // Optional direct local directory (dev/test mode)
176
+ if (this.staticDir) {
177
+ const localPath = path.join(this.staticDir, safe);
178
+ if (fs.existsSync(localPath)) {
179
+ const parsed = JSON.parse(fs.readFileSync(localPath, "utf8"));
180
+ this.memCache.set(safe, parsed);
181
+ return parsed;
182
+ }
183
+ return null;
184
+ }
185
+
186
+ // Persistent disk cache
187
+ const cachedFile = path.join(this.cacheDir, safe);
188
+ if (fs.existsSync(cachedFile)) {
189
+ try {
190
+ const parsed = JSON.parse(fs.readFileSync(cachedFile, "utf8"));
191
+ this.memCache.set(safe, parsed);
192
+ return parsed;
193
+ } catch {
194
+ // Re-fetch if corrupted
195
+ }
196
+ }
197
+
198
+ const res = await this.fetchImpl(`${this.staticBase}/${safe}`);
199
+ if (!res.ok) return null;
200
+ const text = await res.text();
201
+ const parsed = JSON.parse(text);
202
+ this.memCache.set(safe, parsed);
203
+ try {
204
+ fs.mkdirSync(path.dirname(cachedFile), { recursive: true });
205
+ fs.writeFileSync(cachedFile, text, "utf8");
206
+ } catch {
207
+ // Read-only filesystem fallback: keep in memory only
208
+ }
209
+ return parsed;
210
+ }
211
+
212
+ async ensureCore() {
213
+ if (this.coreBundle) return this.coreBundle;
214
+ const bundle = await this.loadJsonShard("core_bundle.json");
215
+ if (bundle && bundle.manifest) {
216
+ this.coreBundle = bundle;
217
+ return bundle;
218
+ }
219
+ const [manifest, validity_graph, synonyms] = await Promise.all([
220
+ this.loadJsonShard("manifest.json"),
221
+ this.loadJsonShard("validity_graph.json"),
222
+ this.loadJsonShard("synonyms.json"),
223
+ ]);
224
+ this.coreBundle = {
225
+ manifest: manifest || {},
226
+ validity_graph: validity_graph || {},
227
+ synonyms: synonyms || {},
228
+ };
229
+ return this.coreBundle;
230
+ }
231
+
232
+ async getDocByUid(uid) {
233
+ const shardId = String(uid & 255).padStart(3, "0");
234
+ const shard = await this.loadJsonShard(`meta/m_${shardId}.json`);
235
+ if (!shard) return null;
236
+ const e = shard[String(uid)];
237
+ if (!e) return null;
238
+ return {
239
+ doc_id: e.id,
240
+ uid: e.u,
241
+ rbi_doc_num: e.ref,
242
+ title: e.t,
243
+ iso_date: e.iso,
244
+ year: e.y,
245
+ category: e.cat,
246
+ status: e.st || "ACTIVE",
247
+ md_path: e.p,
248
+ pdf_url: e.pdf,
249
+ sha256: e.sha,
250
+ token_estimate: e.tok,
251
+ body_excerpt: e.ex,
252
+ };
253
+ }
254
+
255
+ async resolveDocument(identifier) {
256
+ const raw = String(identifier || "").trim();
257
+ if (!raw) return { document: null, error: "Empty identifier." };
258
+ const cleanPath = raw.replace(/\\/g, "/").replace(/^\/+/, "");
259
+ const keys = [];
260
+ const k1 = normalizeReferenceKey(cleanPath, true);
261
+ if (k1) keys.push(k1);
262
+ if (cleanPath.startsWith("data/")) {
263
+ const k2 = normalizeReferenceKey(cleanPath.slice(5), true);
264
+ if (k2 && !keys.includes(k2)) keys.push(k2);
265
+ }
266
+ if (/^rbi_[0-9]{1,8}$/i.test(raw) || !/^[0-9]+_[0-9]+$/.test(raw)) {
267
+ const k3 = normalizeReferenceKey(cleanPath, false);
268
+ if (k3 && !keys.includes(k3) && !/^\d+$/.test(k3)) keys.push(k3);
269
+ }
270
+
271
+ for (const key of keys) {
272
+ const shardId = String(fnv1a32(key) & 63).padStart(2, "0");
273
+ const shard = await this.loadJsonShard(`aliases/a_${shardId}.json`);
274
+ if (!shard || shard[key] === undefined) continue;
275
+ const hit = shard[key];
276
+ const uid = typeof hit === "number" ? hit : hit && typeof hit.u === "number" ? hit.u : null;
277
+ if (uid !== null) {
278
+ const doc = await this.getDocByUid(uid);
279
+ if (doc) return { document: doc };
280
+ }
281
+ }
282
+ return { document: null, error: `Document not found in static alias shards: ${raw}` };
283
+ }
284
+
285
+ async searchRegulations({ query, limit = 10, category, year }) {
286
+ const tokens = tokenize(query);
287
+ if (tokens.length === 0) {
288
+ return { results: [], total_matched: 0, mode: "local_static_v2" };
289
+ }
290
+ const cappedLimit = Math.max(1, Math.min(50, Number(limit) || 10));
291
+ const core = await this.ensureCore();
292
+ const expanded = new Map();
293
+ for (const tok of tokens) {
294
+ expanded.set(tok, 1.0);
295
+ const syns = (core.synonyms && core.synonyms[tok]) || [];
296
+ for (const s of syns.slice(0, 3)) {
297
+ if (!expanded.has(s)) expanded.set(s, 0.35);
298
+ }
299
+ }
300
+
301
+ const byShard = new Map();
302
+ for (const term of expanded.keys()) {
303
+ const shardId = String(fnv1a32(term) & 255).padStart(3, "0");
304
+ if (!byShard.has(shardId)) byShard.set(shardId, []);
305
+ byShard.get(shardId).push(term);
306
+ }
307
+
308
+ const scores = new Map();
309
+ await Promise.all(
310
+ Array.from(byShard.entries()).map(async ([shardId, terms]) => {
311
+ const shard = await this.loadJsonShard(`bm25/b_${shardId}.json`);
312
+ if (!shard) return;
313
+ for (const term of terms) {
314
+ const posting = shard[term];
315
+ if (!Array.isArray(posting)) continue;
316
+ const w = expanded.get(term) || 1.0;
317
+ for (let i = 0; i < posting.length; i += 2) {
318
+ const uid = posting[i];
319
+ const s = (posting[i + 1] / 120.0) * w;
320
+ scores.set(uid, (scores.get(uid) || 0) + s);
321
+ }
322
+ }
323
+ })
324
+ );
325
+
326
+ const ranked = Array.from(scores.entries())
327
+ .sort((a, b) => b[1] - a[1])
328
+ .slice(0, cappedLimit * 3);
329
+
330
+ const results = [];
331
+ for (const [uid, score] of ranked) {
332
+ const doc = await this.getDocByUid(uid);
333
+ if (!doc) continue;
334
+ if (category && doc.category.toLowerCase() !== String(category).toLowerCase()) continue;
335
+ if (year && Number(doc.year) !== Number(year)) continue;
336
+ results.push({ ...doc, bm25_score: Number(score.toFixed(4)) });
337
+ if (results.length >= cappedLimit) break;
338
+ }
339
+
340
+ return {
341
+ results,
342
+ total_matched: scores.size,
343
+ mode: "local_static_v2",
344
+ worker_invocations: 0,
345
+ };
346
+ }
347
+
348
+ async verifyValidity(docId, asOfDate) {
349
+ const resolved = await this.resolveDocument(docId);
350
+ if (!resolved.document) return { error: resolved.error || "Document not found." };
351
+ const doc = resolved.document;
352
+ const core = await this.ensureCore();
353
+ const targetDate = asOfDate || new Date().toISOString().slice(0, 10);
354
+ if (doc.iso_date && targetDate < doc.iso_date) {
355
+ return {
356
+ doc_id: doc.doc_id,
357
+ as_of_date: targetDate,
358
+ status: "NOT_YET_ISSUED",
359
+ issued_date: doc.iso_date,
360
+ mode: "local_static_v2",
361
+ };
362
+ }
363
+ const incoming = (core.validity_graph && core.validity_graph[String(doc.uid)]) || [];
364
+ let status = doc.status === "NOT_APPLICABLE" ? "NOT_APPLICABLE" : "ACTIVE";
365
+ const activeEdges = [];
366
+ for (const edge of incoming) {
367
+ const [srcUid, edgeType, effDate] = edge;
368
+ if (effDate && effDate > targetDate) continue;
369
+ activeEdges.push({ source_uid: srcUid, edge_type: edgeType, effective_date: effDate });
370
+ if (status !== "NOT_APPLICABLE") {
371
+ if (edgeType === "REPEALS") status = "REPEALED";
372
+ else if (edgeType === "SUPERSEDES" && status !== "REPEALED") status = "SUPERSEDED";
373
+ }
374
+ }
375
+ return {
376
+ doc_id: doc.doc_id,
377
+ rbi_doc_num: doc.rbi_doc_num,
378
+ title: doc.title,
379
+ as_of_date: targetDate,
380
+ status,
381
+ incoming_edges: activeEdges,
382
+ mode: "local_static_v2",
383
+ };
384
+ }
385
+
386
+ async fetchFullMarkdown(docId, maxChars = 64000) {
387
+ const resolved = await this.resolveDocument(docId);
388
+ if (!resolved.document) return { error: resolved.error || "Document not found." };
389
+ const doc = resolved.document;
390
+ const relMd = String(doc.md_path || "").replace(/^\/+/, "");
391
+ if (!relMd) return { error: "Document metadata has no md_path." };
392
+
393
+ const candidates = [
394
+ { source: "github_raw", url: `${this.githubRawBase}/${relMd}` },
395
+ { source: "huggingface_raw", url: `${this.hfRawBase}/${relMd}` },
396
+ ];
397
+ for (const c of candidates) {
398
+ try {
399
+ const res = await this.fetchImpl(c.url);
400
+ if (res.ok) {
401
+ const text = await res.text();
402
+ return {
403
+ doc_id: doc.doc_id,
404
+ rbi_doc_num: doc.rbi_doc_num,
405
+ title: doc.title,
406
+ source: c.source,
407
+ worker_invocations: 0,
408
+ truncated: text.length > maxChars,
409
+ content: text.slice(0, maxChars),
410
+ };
411
+ }
412
+ } catch {
413
+ // Try next mirror
414
+ }
415
+ }
416
+ return {
417
+ doc_id: doc.doc_id,
418
+ title: doc.title,
419
+ source: "excerpt_fallback",
420
+ content: doc.body_excerpt || "",
421
+ warning: "Upstream raw mirrors unreachable; returning indexed excerpt.",
422
+ };
423
+ }
424
+
425
+ async handleJsonRpc(req) {
426
+ const { id, method, params } = req || {};
427
+ if (id === undefined || id === null) {
428
+ if (method === "notifications/initialized" || method === "initialized") return null;
429
+ }
430
+
431
+ switch (method) {
432
+ case "initialize":
433
+ return {
434
+ jsonrpc: "2.0",
435
+ id: id ?? 1,
436
+ result: {
437
+ protocolVersion: (params && params.protocolVersion) || "2025-06-18",
438
+ capabilities: { tools: { listChanged: false } },
439
+ serverInfo: { name: "rbi-doc-mcp-local", version: "2.2.0" },
440
+ },
441
+ };
442
+ case "ping":
443
+ return { jsonrpc: "2.0", id: id ?? 1, result: {} };
444
+ case "tools/list":
445
+ return { jsonrpc: "2.0", id: id ?? 1, result: { tools: LOCAL_TOOLS } };
446
+ case "tools/call": {
447
+ const name = String((params && params.name) || "");
448
+ const args = (params && params.arguments) || {};
449
+ let out;
450
+ if (name === "search_rbi_regulations") out = await this.searchRegulations(args);
451
+ else if (name === "resolve_rbi_document" || name === "resolve_rbi_doc") {
452
+ out = await this.resolveDocument(args.identifier || args.doc_id);
453
+ } else if (name === "verify_circular_validity") {
454
+ out = await this.verifyValidity(args.doc_id || args.identifier, args.as_of_date);
455
+ } else if (name === "trace_statutory_consequences") {
456
+ out = await this.verifyValidity(args.doc_id || args.identifier);
457
+ } else if (name === "get_rbi_citation" || name === "format_court_citation") {
458
+ const r = await this.resolveDocument(args.doc_id || args.identifier);
459
+ out = r.document
460
+ ? {
461
+ citation: `Reserve Bank of India, ${r.document.title}, Ref. ${r.document.rbi_doc_num || r.document.doc_id} (${r.document.iso_date}) [SHA-256: ${r.document.sha256 || "verified"}]`,
462
+ judicial_citation: `Reserve Bank of India, ${r.document.title}, Ref. ${r.document.rbi_doc_num || r.document.doc_id} (${r.document.iso_date})`,
463
+ doc_id: r.document.doc_id,
464
+ pdf_url: r.document.pdf_url,
465
+ sha256: r.document.sha256,
466
+ mode: "local_static_v2",
467
+ }
468
+ : { error: r.error || "Document not found." };
469
+ } else if (name === "fetch_rbi_document" || name === "fetch_rbi_markdown") {
470
+ out = await this.fetchFullMarkdown(args.doc_id || args.identifier, args.max_chars || 64000);
471
+ } else if (name === "get_corpus_overview") {
472
+ const core = await this.ensureCore();
473
+ out = { manifest: core.manifest, mode: "local_static_v2", worker_invocations: 0 };
474
+ } else {
475
+ out = { error: `Unknown local tool: ${name}` };
476
+ }
477
+ return {
478
+ jsonrpc: "2.0",
479
+ id: id ?? 1,
480
+ result: {
481
+ content: [{ type: "text", text: JSON.stringify(out, null, 2) }],
482
+ isError: Boolean(out && out.error),
483
+ },
484
+ };
485
+ }
486
+ default:
487
+ return {
488
+ jsonrpc: "2.0",
489
+ id: id ?? null,
490
+ error: { code: -32601, message: `Method not found: ${String(method)}` },
491
+ };
492
+ }
493
+ }
494
+ }
495
+
496
+ module.exports = {
497
+ LocalRbiEngine,
498
+ LOCAL_TOOLS,
499
+ fnv1a32,
500
+ normalizeReferenceKey,
501
+ tokenize,
502
+ };
package/package.json CHANGED
@@ -1,6 +1,56 @@
1
1
  {
2
2
  "name": "rbi-doc-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.2.1",
4
+ "description": "Official Model Context Protocol (MCP) CLI & Zero-Cost Local BM25F Regulatory Search Engine for the Reserve Bank of India (RBI) Regulatory Archive (1991-2026, 88,236 Master Directions, Circulars, Notifications, FEMA & Banking Regulations).",
5
+ "homepage": "https://rbi-archive.pages.dev",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/imsovikde/rbi-regulatory-archive-1991-2026.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/imsovikde/rbi-regulatory-archive-1991-2026/issues"
12
+ },
13
+ "bin": {
14
+ "rbi-doc-mcp": "./bin/rbi-doc-mcp.js"
15
+ },
16
+ "main": "./lib/local_mode.js",
17
+ "files": [
18
+ "bin/rbi-doc-mcp.js",
19
+ "lib/local_mode.js",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18.0.0"
24
+ },
25
+ "scripts": {
26
+ "start": "node ./bin/rbi-doc-mcp.js"
27
+ },
28
+ "keywords": [
29
+ "rbi",
30
+ "reserve-bank-of-india",
31
+ "mcp",
32
+ "model-context-protocol",
33
+ "mcp-server",
34
+ "claude",
35
+ "claude-code",
36
+ "cursor",
37
+ "windsurf",
38
+ "copilot",
39
+ "indian-banking",
40
+ "banking-regulation-act",
41
+ "fema",
42
+ "pmla",
43
+ "kyc",
44
+ "nbfc",
45
+ "fintech-india",
46
+ "master-directions",
47
+ "rbi-circulars",
48
+ "legal-tech",
49
+ "regtech",
50
+ "rag",
51
+ "bm25f",
52
+ "ai-agents"
53
+ ],
54
+ "author": "Souvik Dey <imsovikde@gmail.com>",
55
+ "license": "Apache-2.0"
56
+ }