bharatlas-mcp 1.6.0 → 1.7.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.
package/README.md CHANGED
@@ -65,7 +65,7 @@ Add to your MCP client config:
65
65
 
66
66
  ## How it works
67
67
 
68
- Thin wrapper over the [bharatlas REST API](https://bharatlas.com/docs). Each tool call becomes one or more API requests to Cloudflare Workers that read parquet files and PMTiles directly from R2 at runtime. No pre-computation, no API key, no auth.
68
+ Thin wrapper over the [bharatlas REST API](https://bharatlas.com/docs). Each tool call becomes one or more API requests to Cloudflare Workers that read parquet files and PMTiles directly from R2 at runtime. No pre-computation, no API key, no auth. We count MCP calls per layer, and keep nothing about the caller.
69
69
 
70
70
  The server sends instructions to the LLM at connection time that teach:
71
71
  - **Schema-first pattern**: check column names and sample values before querying (column names vary: `state` vs `State_LGD` vs `stname`)
@@ -0,0 +1,22 @@
1
+ // Collect share links: https://collect.bharatlas.com/c/<id>[/admin]#<token>.
2
+ // The token's prefix is its scope; the id goes into collect API paths, so it
3
+ // must be a plain id (idSegment).
4
+ import { idSegment } from "./read-tools.js";
5
+
6
+ const SCOPE_BY_PREFIX = { adm: "admin", edt: "edit", viw: "view" };
7
+ const SCOPE_RANK = { view: 0, edit: 1, admin: 2 };
8
+ export const scopeOfToken = (t) => SCOPE_BY_PREFIX[String(t || "").slice(0, 3)] || null;
9
+ export const atLeastScope = (have, need) => (SCOPE_RANK[have] ?? -1) >= SCOPE_RANK[need];
10
+
11
+ export function parseShareLink(link) {
12
+ let u;
13
+ try { u = new URL(String(link).trim()); } catch { throw new Error("not a valid URL — paste the whole collect share link"); }
14
+ const token = (u.hash || "").replace(/^#/, "");
15
+ const scope = scopeOfToken(token);
16
+ if (!scope) throw new Error("no token found in the link #fragment (expected #adm_… / #edt_… / #viw_…)");
17
+ const parts = u.pathname.split("/").filter(Boolean); // ["c", "<id>", "admin"?]
18
+ const ci = parts.indexOf("c");
19
+ const id = ci >= 0 ? parts[ci + 1] : null;
20
+ if (!id) throw new Error("could not find the map id in the link path (expected /c/<id>…)");
21
+ return { id: idSegment(id, "map id"), token, scope, link: u.toString() };
22
+ }
package/index.js CHANGED
@@ -9,11 +9,12 @@ import {
9
9
  import { readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
10
10
  import { homedir } from "node:os";
11
11
  import { join } from "node:path";
12
- import { INSTRUCTIONS_CORE, READ_TOOLS, readToolRequest, shapeReadResult, toSearchParams } from "./read-tools.js";
12
+ import { INSTRUCTIONS_CORE, READ_TOOLS, readToolRequest, shapeReadResult, toSearchParams, idSegment } from "./read-tools.js";
13
13
  import { withClientIds, importSummary } from "./import-records.js";
14
+ import { parseShareLink, atLeastScope } from "./collect-links.js";
14
15
 
15
16
  /** One version for the server and its user agent; bump with every release (version.test.js). */
16
- const VERSION = "1.6.0";
17
+ const VERSION = "1.7.0";
17
18
 
18
19
  const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
19
20
 
@@ -30,12 +31,12 @@ const SERVER_INSTRUCTIONS = `bharatlas MCP server. India's open geo data: curate
30
31
  ${INSTRUCTIONS_CORE}
31
32
 
32
33
  Collect (author your own map): this server also drives collect.bharatlas.com, the crowd map-capture tool in the bharatlas suite.
33
- - 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).
34
+ - 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).
34
35
  - register_map: paste any collect share link to manage that map here. The link's scope decides what you can do:
35
36
  - view link -> get_map, get_records: read / query / export that map's published points (analyse or back up what has been collected).
36
37
  - collect link -> the above; field capture itself is done in the browser on a phone via the collect link.
37
38
  - admin link -> everything: edit_map (settings), moderate_record (approve/reject), import_points (bulk data you already hold, with a source + rights), and publish.
38
- - publish submits a collect map's approved points to the bharatlas catalog FOR REVIEW — nothing is auto-approved. A bharatlas maintainer approves the submission before it goes live; the response's status is "pending" until then. Once approved it is queryable through the read tools above (list_submissions, query_layer, locate).
39
+ - publish submits a collect map's approved points to the bharatlas catalog FOR REVIEW; nothing is auto-approved. A bharatlas maintainer approves the submission before it goes live; the response's status is "pending" until then. Once approved it is queryable through the read tools above (list_submissions, query_layer, locate).
39
40
  - 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.`;
40
41
 
41
42
  // The eight read tools live in read-tools.js (shared with bharatlas.com/mcp);
@@ -69,7 +70,7 @@ const TOOLS = [
69
70
  {
70
71
  name: "get_records",
71
72
  description:
72
- "A collect map's records as a GeoJSON FeatureCollection — for reading, analysis, or backup/export. " +
73
+ "A collect map's records as a GeoJSON FeatureCollection, for reading, analysis, or backup/export. " +
73
74
  "view and collect scope return published points; admin can also read pending/rejected via status. " +
74
75
  "Each record's properties._photos lists its photo links (public once the point is approved); _ai holds notes a model wrote from the photo (others see only notes the owner accepted).",
75
76
  inputSchema: {
@@ -132,14 +133,14 @@ const TOOLS = [
132
133
  name: "publish",
133
134
  description:
134
135
  "Submit a collect map's approved points to the bharatlas catalog for review (needs the admin link). " +
135
- "Nothing goes live automatically — a maintainer approves the submission first; the response status is 'pending' until then. " +
136
+ "Nothing goes live automatically: a maintainer approves the submission first; the response status is 'pending' until then. " +
136
137
  "Once approved it is queryable via list_submissions / query_layer / locate above.",
137
138
  inputSchema: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
138
139
  },
139
140
  {
140
141
  name: "create_map",
141
142
  description:
142
- "Optional: create a collect map programmatically. Most maps are made online at collect.bharatlas.com (no key needed) — " +
143
+ "Optional: create a collect map programmatically. Most maps are made online at collect.bharatlas.com (no key needed); " +
143
144
  "prefer that and register_map the link. This path needs COLLECT_API_KEY (the request-only anti-abuse gate) and " +
144
145
  "auto-registers the new admin link.",
145
146
  inputSchema: {
@@ -154,7 +155,7 @@ const TOOLS = [
154
155
  license: { type: "string", description: "open licence id; default CC-BY-4.0" },
155
156
  category: { type: "string" },
156
157
  data_year: { type: "integer" },
157
- moderation: { type: "boolean", description: "default true — points wait for approval" },
158
+ moderation: { type: "boolean", description: "default true: points wait for approval" },
158
159
  basemap: { enum: ["positron", "satellite", "topo"] },
159
160
  },
160
161
  required: ["name", "purpose", "geometry", "fields"],
@@ -189,10 +190,6 @@ async function callApi(path, params = {}) {
189
190
  }
190
191
 
191
192
  // ---- collect: local credential store + scoped auth --------------------------
192
- const SCOPE_BY_PREFIX = { adm: "admin", edt: "edit", viw: "view" };
193
- const SCOPE_RANK = { view: 0, edit: 1, admin: 2 };
194
- const scopeOfToken = (t) => SCOPE_BY_PREFIX[String(t || "").slice(0, 3)] || null;
195
- const atLeastScope = (have, need) => (SCOPE_RANK[have] ?? -1) >= SCOPE_RANK[need];
196
193
 
197
194
  function loadStore() {
198
195
  try { return existsSync(COLLECT_STORE) ? JSON.parse(readFileSync(COLLECT_STORE, "utf8")) : { maps: {} }; }
@@ -207,7 +204,10 @@ function saveStore(s) {
207
204
  }
208
205
  function rememberMap(id, entry) { const s = loadStore(); s.maps[id] = { ...s.maps[id], ...entry }; saveStore(s); }
209
206
  function mapEntry(id) {
210
- const m = loadStore().maps[id];
207
+ // An id goes into collect API paths: letters, digits, _ and - only (idSegment),
208
+ // and only one this store holds (never an inherited key such as "__proto__").
209
+ const maps = loadStore().maps;
210
+ const m = Object.hasOwn(maps, idSegment(id, "id")) ? maps[id] : undefined;
211
211
  if (!m) throw new Error(`map ${id} is not registered. Create it online at collect.bharatlas.com, then register_map with its share link.`);
212
212
  return m;
213
213
  }
@@ -218,19 +218,6 @@ function tokenFor(id, need) {
218
218
  }
219
219
  return m.token;
220
220
  }
221
- function parseShareLink(link) {
222
- let u;
223
- try { u = new URL(String(link).trim()); } catch { throw new Error("not a valid URL — paste the whole collect share link"); }
224
- const token = (u.hash || "").replace(/^#/, "");
225
- const scope = scopeOfToken(token);
226
- if (!scope) throw new Error("no token found in the link #fragment (expected #adm_… / #edt_… / #viw_…)");
227
- const parts = u.pathname.split("/").filter(Boolean); // ["c", "<id>", "admin"?]
228
- const ci = parts.indexOf("c");
229
- const id = ci >= 0 ? parts[ci + 1] : null;
230
- if (!id) throw new Error("could not find the map id in the link path (expected /c/<id>…)");
231
- return { id, token, scope, link: u.toString() };
232
- }
233
-
234
221
  // ---- collect: HTTP (GET/POST/PATCH with auth headers): request() above ------
235
222
  function collectApi(method, path, { token, apiKey, body } = {}) {
236
223
  const headers = {};
@@ -281,7 +268,7 @@ async function handleTool(name, args) {
281
268
  }
282
269
 
283
270
  case "moderate_record":
284
- return collectApi("POST", `/records/${args.record_id}/moderate`, {
271
+ return collectApi("POST", `/records/${idSegment(args.record_id, "record_id")}/moderate`, {
285
272
  token: tokenFor(args.id, "admin"),
286
273
  body: { status: args.status, reason: args.reason },
287
274
  });
@@ -297,7 +284,8 @@ async function handleTool(name, args) {
297
284
 
298
285
  case "edit_map": {
299
286
  const { id, ...patch } = args;
300
- return collectApi("PATCH", `/collections/${id}`, { token: tokenFor(id, "admin"), body: patch });
287
+ const token = tokenFor(id, "admin"); // checks the id first
288
+ return collectApi("PATCH", `/collections/${id}`, { token, body: patch });
301
289
  }
302
290
 
303
291
  case "publish":
@@ -305,7 +293,7 @@ async function handleTool(name, args) {
305
293
 
306
294
  case "create_map": {
307
295
  if (!COLLECT_API_KEY) {
308
- 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.");
296
+ 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.");
309
297
  }
310
298
  const schema_doc = { version: 1, geometry: args.geometry, fields: args.fields };
311
299
  if (args.category) schema_doc.category = args.category;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bharatlas-mcp",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
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
5
  "keywords": ["mcp", "india", "geo", "geospatial", "gis", "boundaries", "parquet", "pmtiles", "llm", "claude", "bharatlas", "collect"],
6
6
  "repository": { "type": "git", "url": "git+https://github.com/urbanmorph/geodata.git", "directory": "mcp" },
@@ -9,7 +9,7 @@
9
9
  "type": "module",
10
10
  "main": "index.js",
11
11
  "scripts": {
12
- "test": "node --test import-records.test.js read-tools.test.js version.test.js",
12
+ "test": "node --test collect-links.test.js import-records.test.js read-tools.test.js version.test.js",
13
13
  "test:live": "node test.js"
14
14
  },
15
15
  "bin": {
package/read-tools.js CHANGED
@@ -11,14 +11,16 @@ export const INSTRUCTIONS_CORE = `Workflow patterns:
11
11
  - **Filtering**: query_layer where is an exact, case-insensitive match (no partial or substring match). Pass column=value pairs; check the schema for the right column name and value format. Columns the schema marks as type "nested" (structs, lists, maps, e.g. Overture names/addresses) can be selected but not used in where or group_by (the API returns 400 listing the flat columns).
12
12
  - **Counting**: use group_by to count features by any column. Example: group_by "category" on the gs_wildlife layer returns national parks vs sanctuaries.
13
13
  - **Totals**: add sum (numeric columns) to group_by to total values per group, e.g. group_by "district" + sum ["area_ha"] rolls block-level areas up to districts. Percentages are not additive: sum the underlying amounts and recompute shares.
14
- - **Location queries**: locate returns all admin boundaries + zones at a lat/lng, and (for the ~30 covered cities) auto-includes the municipal ward layer that contains the point — so "what ward is this?" just works with lat/lng alone. Use it to answer "what state/district/ward is this point in?"
14
+ - **Location queries**: locate returns all admin boundaries + zones at a lat/lng, and (for the 30+ cities with ward layers) auto-includes the municipal ward layer that contains the point, so "what ward is this?" works with lat/lng alone. Use it to answer "what state/district/ward is this point in?"
15
15
  - **Spatial joins** (multi-step): to answer "which X are in Y?" when layers don't share a common column:
16
16
  1. Use locate to find the admin context (state, district) of the target area
17
17
  2. Use query_layer with a where filter to narrow the other layer by that admin context
18
18
  3. For precise spatial containment, test individual points via locate against the target layer
19
+ - **Near a point**: nearby returns a layer's features nearest first within radius_km (default 25, max 200), with the true count inside the radius. Use it for "X near Y" once you have Y's coordinate.
19
20
  - **Community layers**: list_submissions returns user-contributed datasets. These work with query_layer and get_layer_schema exactly like curated layers.
20
21
  - **Downloads**: get_layer_detail returns direct URLs for the formats a layer has (parquet and pmtiles always; geojson, kml and shapefile for most).
21
- - **Large layers**: overture_places_india has 4.4M places. Always narrow it: where on basic_category (e.g. "hospital", "restaurant") or name, group_by, or nearby for places around a point. Whole-table filters and group_by take several seconds; nearby is the fast path for "near me".
22
+ - **Citing**: get_layer_detail also returns "versions", the layer's dated releases, newest first. When you cite or publish a result, name the version you used by its code (e.g. bharatlas-lgd_states-2026.12) and sha256, or its w3id address. An empty list means no release yet: cite the layer's /view page and the date you read it.
23
+ - **Large layers**: overture_places_india has 4.8M places. Always narrow it: where on basic_category (e.g. "hospital", "restaurant") or name, group_by, or nearby for places around a point. Whole-table filters and group_by take several seconds; nearby is the fast path for "near me".
22
24
  - **Honor the terms**: every layer and community submission carries its own source and open licence. When you use, quote, or publish results from a layer, credit its source and respect that licence; get_layer_detail returns the attribution and licence, and each /view page's Dataset JSON-LD carries a creditText to reproduce. A layer whose answer has "non_commercial": true is for non-commercial use only: say so whenever you use or recommend it, quote its "licence_notice", and never suggest it for a product, a client or paid work.
23
25
 
24
26
  Source preference (multiple layers often cover the same level):
@@ -42,11 +44,12 @@ Cross-layer queries (combining data from different layers):
42
44
  - "wells/borewells/tubewells/irrigation pumps" → mi6_wells_districts (census counts per district, 2017-18)
43
45
  - "forests/green cover/ecology" → soi_forests, gs_wildlife, bm_eco_zones, biogeographic_zones
44
46
  - "agriculture/farming/cropping zones" → agro_ecological_zones, agro_climatic_zones, corestack_lulc_blocks (land use and cropping intensity by block, modelled)
45
- - "places/POIs/shops/restaurants/ATMs/schools/hospitals by name" → overture_places_india (filter on name or basic_category; 4.4M rows, always add a where or group_by, or use nearby)
47
+ - "places/POIs/shops/restaurants/ATMs/schools/hospitals by name" → overture_places_india (filter on name or basic_category; 4.8M rows, always add a where or group_by, or use nearby)
46
48
  - "hazards/risks" → seismic_zones, india_flood_inventory
47
49
  - "health/medical" → nic_health
48
50
  - "boundaries/admin" → lgd_states, lgd_districts, lgd_subdistricts, lgd_blocks, lgd_villages
49
- - "roads/transport" → gs_highways, airports
51
+ - "roads/transport" → gs_highways, pmgsy_roads (rural roads), airports
52
+ - "railway stations/metro/bus stops/transit" → ir_stations, urban_rail_stations, urban_rail_lines, bus_stops
50
53
  When unsure, use list_layers with a broad q search and list_categories to discover what's available. Combine ALL relevant layers, not just the first match.
51
54
  - **Sky and air over a place**: once you have a coordinate (from locate, nearby or a layer row), the mugilu MCP (mugilu.live/mcp, tool conditions_at) gives the live air quality, heat, fog and warnings there. bharatlas answers where; mugilu answers what the sky is doing.
52
55
 
@@ -71,7 +74,7 @@ export const READ_TOOLS = [
71
74
  properties: {
72
75
  category: {
73
76
  type: "string",
74
- description: "Filter by category: boundaries, city-wards, people, environment, water, agriculture, transport, infrastructure, health-edu",
77
+ description: "Filter by category: boundaries, city-wards, people, environment, water, agriculture, transport, infrastructure, health-edu, economy",
75
78
  },
76
79
  level: {
77
80
  type: "string",
@@ -158,7 +161,7 @@ export const READ_TOOLS = [
158
161
  "Given a latitude/longitude, find which administrative boundaries, zones, and regions " +
159
162
  "contain that point. Returns state, district, subdistrict, block, parliament/assembly " +
160
163
  "constituency, pincode, seismic zone, high court jurisdiction, the municipal ward (for " +
161
- "the ~30 cities with ward data), and more. " +
164
+ "the 30+ cities with ward layers), and more. " +
162
165
  "The 'where am I?' tool. Also accepts specific layer IDs to check.",
163
166
  inputSchema: {
164
167
  type: "object",
@@ -174,7 +177,7 @@ export const READ_TOOLS = [
174
177
  layers: {
175
178
  type: "array",
176
179
  items: { type: "string" },
177
- description: "Specific layer IDs to check. Omit to use the default: 12 essential admin/zone layers PLUS the city ward layer(s) covering the point (for the ~30 cities with ward data). Passing this replaces the default entirely (no ward auto-include).",
180
+ description: "Specific layer IDs to check. Omit to use the default: 13 essential admin/zone layers PLUS the city ward layer(s) covering the point (for the 30+ cities with ward layers). Passing this replaces the default entirely (no ward auto-include).",
178
181
  },
179
182
  },
180
183
  required: ["lat", "lng"],
@@ -214,7 +217,7 @@ export const READ_TOOLS = [
214
217
  name: "get_layer_detail",
215
218
  description:
216
219
  "Get full metadata for a single layer: download URLs (parquet, pmtiles, geojson, kml, shapefile), " +
217
- "attribution, license, feature count, and level metadata.",
220
+ "attribution, license, feature count, level metadata, and versions (the dated releases to cite).",
218
221
  inputSchema: {
219
222
  type: "object",
220
223
  properties: {
@@ -250,11 +253,20 @@ export const READ_TOOLS = [
250
253
 
251
254
  const READ_NAMES = new Set(READ_TOOLS.map((t) => t.name));
252
255
 
253
- // Mirrors RESERVED in web/functions/lib/query-params.ts: these names are query
254
- // options, so a where column with one of them must go inside where=.
255
- const QUERY_RESERVED = new Set(["select", "group_by", "sum", "limit", "where", "order_by", "include_centroid"]);
256
+ // Mirrors QUERY_OPTIONS in web/functions/lib/query-params.ts (a web test holds
257
+ // the two equal): these names are query options, so a where column with one of
258
+ // them must go inside where=.
259
+ export const QUERY_RESERVED = new Set(["select", "group_by", "sum", "limit", "where", "order_by", "include_centroid", "filter", "format", "estimate"]);
256
260
 
257
261
  const LAYER_ID = /^[a-zA-Z0-9_-]+$/;
262
+ /** A value going into a URL path (e.g. a collect record id): letters, digits, _ and -
263
+ * only, so a crafted id can't walk to another endpoint (review 2026-11-18). */
264
+ export function idSegment(value, name) {
265
+ const v = String(value ?? "");
266
+ if (!/^[A-Za-z0-9_-]{1,64}$/.test(v)) throw new Error(`${name} must be an id (letters, digits, _ and -)`);
267
+ return v;
268
+ }
269
+
258
270
  function layerPath(id, suffix = "") {
259
271
  if (!LAYER_ID.test(String(id ?? ""))) {
260
272
  throw new Error("layer_id must be a layer ID such as lgd_states (letters, digits, _ and -)");
package/server.json CHANGED
@@ -25,12 +25,12 @@
25
25
  ]
26
26
  }
27
27
  ],
28
- "version": "1.6.0",
28
+ "version": "1.7.0",
29
29
  "packages": [
30
30
  {
31
31
  "registryType": "npm",
32
32
  "identifier": "bharatlas-mcp",
33
- "version": "1.6.0",
33
+ "version": "1.7.0",
34
34
  "transport": {
35
35
  "type": "stdio"
36
36
  }