bharatlas-mcp 1.0.3 → 1.1.0

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.
Files changed (3) hide show
  1. package/index.js +273 -3
  2. package/package.json +4 -4
  3. package/server.json +3 -3
package/index.js CHANGED
@@ -7,10 +7,21 @@ import {
7
7
  ListToolsRequestSchema,
8
8
  } from "@modelcontextprotocol/sdk/types.js";
9
9
  import https from "node:https";
10
+ import { readFileSync, writeFileSync, existsSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join } from "node:path";
10
13
 
11
14
  const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
12
15
 
13
- const SERVER_INSTRUCTIONS = `bharatlas MCP server. India's open geo data: curated layers (state to village boundaries, city wards, forests, hospitals, highways, rivers, canals, groundwater, agro-climatic zones, floods, seismic zones) plus community submissions.
16
+ // collect (write side): authoring over the collect REST API. The read tools
17
+ // need no auth; the collect tools act only on maps whose share link the user
18
+ // has registered (register_map) — the link's token scope IS the permission, so
19
+ // this server can never touch a map the user does not hold a link to.
20
+ const COLLECT_API = process.env.COLLECT_API || "https://collect.bharatlas.com/api/collect/v1";
21
+ const COLLECT_API_KEY = process.env.COLLECT_API_KEY || ""; // optional: only for headless create_map
22
+ const COLLECT_STORE = process.env.COLLECT_MCP_STORE || join(homedir(), ".bharatlas-mcp.json");
23
+
24
+ const SERVER_INSTRUCTIONS = `bharatlas MCP server. India's open geo data: curated layers (state to village boundaries, city wards, forests, hospitals, highways, rivers, canals, groundwater, agro-climatic zones, floods, seismic zones) plus community submissions. It also drives collect.bharatlas.com for authoring your own maps (see "Collect" below).
14
25
 
15
26
  Workflow patterns:
16
27
 
@@ -56,7 +67,16 @@ Column naming conventions (vary by source):
56
67
  - State: State_LGD (number), STNAME, stname, state, state_name
57
68
  - District: Dist_LGD (number), DTNAME, dtname, district, dtcode11
58
69
  - Block: Block_LGD, BNAME, block_name, blkcode11
59
- - Names are often UPPERCASE in LGD layers, mixed case in other sources`;
70
+ - Names are often UPPERCASE in LGD layers, mixed case in other sources
71
+
72
+ Collect (author your own map): this server also drives collect.bharatlas.com, the crowd map-capture tool in the bharatlas suite.
73
+ - Create maps ONLINE at collect.bharatlas.com — the browser handles the anti-abuse check, so no account and no API key are needed. Point the user there to make one. They get three share links, each with a token in the URL #fragment: admin (full control), collect (add points), view (read published points).
74
+ - register_map: paste any collect share link to manage that map here. The link's scope decides what you can do:
75
+ - view link -> get_map, get_records: read / query / export that map's published points (analyse or back up what has been collected).
76
+ - collect link -> the above; field capture itself is done in the browser on a phone via the collect link.
77
+ - admin link -> everything: edit_map (settings), moderate_record (approve/reject), import_points (bulk data you already hold, with a source + rights), and publish.
78
+ - publish bakes approved points into a bharatlas catalog submission. It is then queryable through the read tools above (list_submissions, query_layer, locate) — the full loop, gather -> moderate -> publish -> query, in one server.
79
+ - No accounts: the link is the credential. A tool that needs more than your link allows will say which link you need. create_map is optional and needs COLLECT_API_KEY (request-only); prefer creating online.`;
60
80
 
61
81
  const TOOLS = [
62
82
  {
@@ -239,6 +259,116 @@ const TOOLS = [
239
259
  },
240
260
  },
241
261
  },
262
+
263
+ // --- collect (authoring): act only on maps whose share link you registered ---
264
+ {
265
+ name: "register_map",
266
+ description:
267
+ "Register a collect map so this server can act on it. Paste the whole share link " +
268
+ "(e.g. https://collect.bharatlas.com/c/<id>/admin#<token>). The token in the #fragment sets your scope: " +
269
+ "admin = full control, collect = add points, view = read published. New maps are created online at " +
270
+ "collect.bharatlas.com first (no account or key needed); this registers one you already made.",
271
+ inputSchema: {
272
+ type: "object",
273
+ properties: { link: { type: "string", description: "a collect.bharatlas.com share link with the token in the #fragment" } },
274
+ required: ["link"],
275
+ },
276
+ },
277
+ {
278
+ name: "list_my_maps",
279
+ description: "List the collect maps you have registered here (local store), each with its scope.",
280
+ inputSchema: { type: "object", properties: {} },
281
+ },
282
+ {
283
+ name: "get_map",
284
+ description: "A collect map's metadata + record counts, plus a link to open it in collect. Any registered scope.",
285
+ inputSchema: { type: "object", properties: { id: { type: "string", description: "the map (collection) id" } }, required: ["id"] },
286
+ },
287
+ {
288
+ name: "get_records",
289
+ description:
290
+ "A collect map's records as a GeoJSON FeatureCollection — for reading, analysis, or backup/export. " +
291
+ "view and collect scope return published points; admin can also read pending/rejected via status.",
292
+ inputSchema: {
293
+ type: "object",
294
+ properties: { id: { type: "string" }, status: { type: "string", description: "admin only: pending | published | rejected" } },
295
+ required: ["id"],
296
+ },
297
+ },
298
+ {
299
+ name: "moderate_record",
300
+ description: "Approve or reject one pending point (needs the admin link). Pass the map id it belongs to.",
301
+ inputSchema: {
302
+ type: "object",
303
+ properties: {
304
+ id: { type: "string", description: "the map (collection) id" },
305
+ record_id: { type: "string" },
306
+ status: { enum: ["published", "rejected", "pending"] },
307
+ reason: { type: "string" },
308
+ },
309
+ required: ["id", "record_id", "status"],
310
+ },
311
+ },
312
+ {
313
+ name: "import_points",
314
+ description:
315
+ "Bulk-import points you already hold into a collect map (needs the admin link). NOT for synthetic data. " +
316
+ "Requires a named source + rights confirmation; each row lands with that source as its provenance.",
317
+ inputSchema: {
318
+ type: "object",
319
+ properties: {
320
+ id: { type: "string" },
321
+ records: { type: "array", items: { type: "object" }, description: "GeoJSON-like {geometry, properties}" },
322
+ source: { type: "string" },
323
+ rights_confirmed: { type: "boolean", description: "you have the right to publish this under the map's licence" },
324
+ },
325
+ required: ["id", "records", "source", "rights_confirmed"],
326
+ },
327
+ },
328
+ {
329
+ name: "edit_map",
330
+ description:
331
+ "Edit a collect map's settings: name/description/purpose/category/data_year/basemap (needs the admin link). " +
332
+ "Licence can only change while the map has no records.",
333
+ inputSchema: {
334
+ type: "object",
335
+ properties: {
336
+ id: { type: "string" }, name: { type: "string" }, description: { type: "string" }, purpose: { type: "string" },
337
+ category: { type: "string" }, data_year: { type: ["integer", "null"] }, basemap: { type: "string" }, license: { type: "string" },
338
+ },
339
+ required: ["id"],
340
+ },
341
+ },
342
+ {
343
+ name: "publish",
344
+ description:
345
+ "Bake a collect map's approved points into a bharatlas catalog submission (needs the admin link). " +
346
+ "Once published it is queryable via list_submissions / query_layer / locate above.",
347
+ inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
348
+ },
349
+ {
350
+ name: "create_map",
351
+ description:
352
+ "Optional: create a collect map programmatically. Most maps are made online at collect.bharatlas.com (no key needed) — " +
353
+ "prefer that and register_map the link. This path needs COLLECT_API_KEY (the request-only anti-abuse gate) and " +
354
+ "auto-registers the new admin link.",
355
+ inputSchema: {
356
+ type: "object",
357
+ properties: {
358
+ name: { type: "string", description: "3-120 chars" },
359
+ purpose: { type: "string", description: "shown to contributors" },
360
+ description: { type: "string" },
361
+ geometry: { type: "array", items: { enum: ["point", "line", "polygon"] }, description: "what contributors may add" },
362
+ fields: { type: "array", items: { type: "object" }, description: "the form for each record (see collect.bharatlas.com/schema/v1.json)" },
363
+ license: { type: "string", description: "open licence id; default CC-BY-4.0" },
364
+ category: { type: "string" },
365
+ data_year: { type: "integer" },
366
+ moderation: { type: "boolean", description: "default true — points wait for approval" },
367
+ basemap: { enum: ["positron", "satellite", "topo"] },
368
+ },
369
+ required: ["name", "purpose", "geometry", "fields"],
370
+ },
371
+ },
242
372
  ];
243
373
 
244
374
  function httpGet(url) {
@@ -266,6 +396,71 @@ async function callApi(path, params = {}) {
266
396
  return httpGet(url.toString());
267
397
  }
268
398
 
399
+ // ---- collect: local credential store + scoped auth --------------------------
400
+ const SCOPE_BY_PREFIX = { adm: "admin", edt: "edit", viw: "view" };
401
+ const SCOPE_RANK = { view: 0, edit: 1, admin: 2 };
402
+ const scopeOfToken = (t) => SCOPE_BY_PREFIX[String(t || "").slice(0, 3)] || null;
403
+ const atLeastScope = (have, need) => (SCOPE_RANK[have] ?? -1) >= SCOPE_RANK[need];
404
+
405
+ function loadStore() {
406
+ try { return existsSync(COLLECT_STORE) ? JSON.parse(readFileSync(COLLECT_STORE, "utf8")) : { maps: {} }; }
407
+ catch { return { maps: {} }; }
408
+ }
409
+ function saveStore(s) { try { writeFileSync(COLLECT_STORE, JSON.stringify(s, null, 2)); } catch { /* best effort */ } }
410
+ function rememberMap(id, entry) { const s = loadStore(); s.maps[id] = { ...s.maps[id], ...entry }; saveStore(s); }
411
+ function mapEntry(id) {
412
+ const m = loadStore().maps[id];
413
+ if (!m) throw new Error(`map ${id} is not registered. Create it online at collect.bharatlas.com, then register_map with its share link.`);
414
+ return m;
415
+ }
416
+ function tokenFor(id, need) {
417
+ const m = mapEntry(id);
418
+ if (need && !atLeastScope(m.scope, need)) {
419
+ throw new Error(`this needs the ${need} link for map ${id}; you registered the ${m.scope} link. Register the ${need} link to do this.`);
420
+ }
421
+ return m.token;
422
+ }
423
+ function parseShareLink(link) {
424
+ let u;
425
+ try { u = new URL(String(link).trim()); } catch { throw new Error("not a valid URL — paste the whole collect share link"); }
426
+ const token = (u.hash || "").replace(/^#/, "");
427
+ const scope = scopeOfToken(token);
428
+ if (!scope) throw new Error("no token found in the link #fragment (expected #adm_… / #edt_… / #viw_…)");
429
+ const parts = u.pathname.split("/").filter(Boolean); // ["c", "<id>", "admin"?]
430
+ const ci = parts.indexOf("c");
431
+ const id = ci >= 0 ? parts[ci + 1] : null;
432
+ if (!id) throw new Error("could not find the map id in the link path (expected /c/<id>…)");
433
+ return { id, token, scope, link: u.toString() };
434
+ }
435
+
436
+ // ---- collect: HTTP (GET/POST/PATCH with auth headers) -----------------------
437
+ function httpReq(method, urlStr, { headers = {}, body } = {}) {
438
+ return new Promise((resolve, reject) => {
439
+ const data = body !== undefined ? JSON.stringify(body) : undefined;
440
+ const opts = { method, headers: { ...headers } };
441
+ if (data) opts.headers["content-type"] = "application/json";
442
+ const req = https.request(new URL(urlStr), opts, (res) => {
443
+ let buf = "";
444
+ res.on("data", (c) => (buf += c));
445
+ res.on("end", () => {
446
+ let parsed;
447
+ try { parsed = buf ? JSON.parse(buf) : {}; } catch { parsed = { raw: buf }; }
448
+ if (res.statusCode >= 400) reject(new Error(parsed.error || `HTTP ${res.statusCode}: ${buf.slice(0, 200)}`));
449
+ else resolve(parsed);
450
+ });
451
+ });
452
+ req.on("error", reject);
453
+ if (data) req.write(data);
454
+ req.end();
455
+ });
456
+ }
457
+ function collectApi(method, path, { token, apiKey, body } = {}) {
458
+ const headers = {};
459
+ if (token) headers.authorization = `Bearer ${token}`;
460
+ if (apiKey) headers["x-api-key"] = apiKey;
461
+ return httpReq(method, COLLECT_API + path, { headers, body });
462
+ }
463
+
269
464
  async function handleTool(name, args) {
270
465
  switch (name) {
271
466
  case "list_layers": {
@@ -321,13 +516,88 @@ async function handleTool(name, args) {
321
516
  return callApi("/submissions", { q, category, sort, limit, offset });
322
517
  }
323
518
 
519
+ // --- collect (authoring) ---
520
+ case "register_map": {
521
+ const { id, token, scope, link } = parseShareLink(args.link);
522
+ let name;
523
+ try {
524
+ const meta = await collectApi("GET", `/collections/${id}`, { token });
525
+ name = meta.name || meta.data?.name;
526
+ } catch { /* metadata is best-effort; still register */ }
527
+ rememberMap(id, { token, scope, link, name, at: new Date().toISOString() });
528
+ const can = scope === "admin"
529
+ ? "moderate, edit, import and publish"
530
+ : scope === "edit"
531
+ ? "read and export (add points in the browser via the collect link)"
532
+ : "read and export published points";
533
+ return { id, scope, name, note: `Registered the ${scope} link for "${name || id}". You can now ${can}.` };
534
+ }
535
+
536
+ case "list_my_maps":
537
+ return Object.entries(loadStore().maps).map(([id, m]) => ({ id, name: m.name, scope: m.scope, at: m.at }));
538
+
539
+ case "get_map": {
540
+ const m = mapEntry(args.id);
541
+ const meta = await collectApi("GET", `/collections/${args.id}`, { token: m.token });
542
+ return { ...meta, open_in_collect: m.link };
543
+ }
544
+
545
+ case "get_records": {
546
+ const m = mapEntry(args.id);
547
+ const qs = args.status ? `?status=${encodeURIComponent(args.status)}` : "";
548
+ return collectApi("GET", `/collections/${args.id}/records${qs}`, { token: m.token });
549
+ }
550
+
551
+ case "moderate_record":
552
+ return collectApi("POST", `/records/${args.record_id}/moderate`, {
553
+ token: tokenFor(args.id, "admin"),
554
+ body: { status: args.status, reason: args.reason },
555
+ });
556
+
557
+ case "import_points":
558
+ return collectApi("POST", `/collections/${args.id}/import`, {
559
+ token: tokenFor(args.id, "admin"),
560
+ body: { records: args.records, source: args.source, rights_confirmed: !!args.rights_confirmed },
561
+ });
562
+
563
+ case "edit_map": {
564
+ const { id, ...patch } = args;
565
+ return collectApi("PATCH", `/collections/${id}`, { token: tokenFor(id, "admin"), body: patch });
566
+ }
567
+
568
+ case "publish":
569
+ return collectApi("POST", `/collections/${args.id}/publish`, { token: tokenFor(args.id, "admin") });
570
+
571
+ case "create_map": {
572
+ if (!COLLECT_API_KEY) {
573
+ throw new Error("create_map needs COLLECT_API_KEY (request-only). Most maps are created online at collect.bharatlas.com — do that, then register_map with the share link.");
574
+ }
575
+ const schema_doc = { version: 1, geometry: args.geometry, fields: args.fields };
576
+ if (args.category) schema_doc.category = args.category;
577
+ if (args.basemap) schema_doc.basemap = args.basemap;
578
+ const body = {
579
+ name: args.name, purpose: args.purpose, description: args.description,
580
+ license: args.license || "CC-BY-4.0", data_year: args.data_year,
581
+ moderation: args.moderation === false ? 0 : 1, schema_doc,
582
+ };
583
+ const r = await collectApi("POST", "/collections", { apiKey: COLLECT_API_KEY, body });
584
+ const adminLink = r.links?.admin;
585
+ if (adminLink) {
586
+ try {
587
+ const p = parseShareLink(adminLink);
588
+ rememberMap(p.id, { token: p.token, scope: p.scope, link: p.link, name: args.name, at: new Date().toISOString() });
589
+ } catch { /* ignore */ }
590
+ }
591
+ return { id: r.id, links: r.links, note: "Share links.collect with contributors. Admin link registered locally." };
592
+ }
593
+
324
594
  default:
325
595
  throw new Error(`Unknown tool: ${name}`);
326
596
  }
327
597
  }
328
598
 
329
599
  const server = new Server(
330
- { name: "bharatlas-mcp", version: "1.0.0" },
600
+ { name: "bharatlas-mcp", version: "1.1.0" },
331
601
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS },
332
602
  );
333
603
 
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "bharatlas-mcp",
3
- "version": "1.0.3",
4
- "description": "MCP server for India's open geo data. Query layers, locate points, find nearby features, filter and group data.",
5
- "keywords": ["mcp", "india", "geo", "geospatial", "gis", "boundaries", "parquet", "pmtiles", "llm", "claude", "bharatlas"],
6
- "repository": { "type": "git", "url": "https://github.com/urbanmorph/geodata", "directory": "mcp" },
3
+ "version": "1.1.0",
4
+ "description": "MCP server for India's open geo data. Query layers, locate points, find nearby features, filter and group data. Also authors collect maps: register a share link, moderate contributions, and publish to the catalog.",
5
+ "keywords": ["mcp", "india", "geo", "geospatial", "gis", "boundaries", "parquet", "pmtiles", "llm", "claude", "bharatlas", "collect"],
6
+ "repository": { "type": "git", "url": "git+https://github.com/urbanmorph/geodata.git", "directory": "mcp" },
7
7
  "homepage": "https://bharatlas.com/mcp",
8
8
  "mcpName": "io.github.urbanmorph/bharatlas-mcp",
9
9
  "type": "module",
package/server.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.urbanmorph/bharatlas-mcp",
4
- "description": "Query India's open geo data. Locate, filter, nearby search across layers.",
5
- "version": "1.0.3",
4
+ "description": "Query India's open geo data (locate, filter, nearby), and author collect maps: register a share link, moderate contributions, and publish to the catalog.",
5
+ "version": "1.1.0",
6
6
  "packages": [
7
7
  {
8
8
  "registryType": "npm",
9
9
  "identifier": "bharatlas-mcp",
10
- "version": "1.0.3",
10
+ "version": "1.1.0",
11
11
  "transport": { "type": "stdio" }
12
12
  }
13
13
  ]