bharatlas-mcp 1.3.0 → 1.4.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
@@ -7,6 +7,8 @@ Ask questions about India's geo data in natural language. This MCP server connec
7
7
 
8
8
  ## Install
9
9
 
10
+ No install needed for the eight read tools: they also run hosted at `https://bharatlas.com/mcp` (Streamable HTTP, read-only), e.g. `claude mcp add --transport http bharatlas https://bharatlas.com/mcp`. Install this package for all 17 tools, including collect authoring.
11
+
10
12
  Add to your MCP client config:
11
13
 
12
14
  ```json
@@ -14,7 +16,7 @@ Add to your MCP client config:
14
16
  "mcpServers": {
15
17
  "bharatlas": {
16
18
  "command": "npx",
17
- "args": ["-y", "bharatlas-mcp"]
19
+ "args": ["-y", "bharatlas-mcp@latest"]
18
20
  }
19
21
  }
20
22
  }
package/index.js CHANGED
@@ -10,6 +10,7 @@ import https from "node:https";
10
10
  import { readFileSync, writeFileSync, existsSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
12
  import { join } from "node:path";
13
+ import { INSTRUCTIONS_CORE, READ_TOOLS, readToolRequest, shapeReadResult, toSearchParams } from "./read-tools.js";
13
14
 
14
15
  const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
15
16
 
@@ -23,57 +24,7 @@ const COLLECT_STORE = process.env.COLLECT_MCP_STORE || join(homedir(), ".bharatl
23
24
 
24
25
  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).
25
26
 
26
- Workflow patterns:
27
-
28
- - **Discovery**: start with list_layers or list_categories to find relevant layers. Use the q parameter for text search.
29
- - **Schema first**: always call get_layer_schema BEFORE query_layer. Column names vary per layer (e.g. "state" vs "State_LGD" vs "stname"). The schema shows exact names and sample values.
30
- - **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).
31
- - **Counting**: use group_by to count features by any column. Example: group_by "category" on the gs_wildlife layer returns national parks vs sanctuaries.
32
- - **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.
33
- - **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?"
34
- - **Spatial joins** (multi-step): to answer "which X are in Y?" when layers don't share a common column:
35
- 1. Use locate to find the admin context (state, district) of the target area
36
- 2. Use query_layer with a where filter to narrow the other layer by that admin context
37
- 3. For precise spatial containment, test individual points via locate against the target layer
38
- - **Community layers**: list_submissions returns user-contributed datasets. These work with query_layer and get_layer_schema exactly like curated layers.
39
- - **Downloads**: get_layer_detail returns direct URLs for the formats a layer has (parquet and pmtiles always; geojson, kml and shapefile for most).
40
- - **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".
41
- - **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.
42
-
43
- Source preference (multiple layers often cover the same level):
44
- - **Admin boundaries** (state, district, subdistrict, block, village): prefer LGD (lgd_*) as the authoritative source. SOI, Bhuvan, and geoBoundaries are cross-reference alternates with slightly different counts/boundaries. Mention alternates if the user asks about discrepancies.
45
- - **City wards**: each city has its own layer (wards_chennai, wards_pune, etc.). Some cities have multiple vintages (e.g. Bengaluru has GBA 2025 + BBMP 2022 historical).
46
- - **Environment/infrastructure/health**: usually one source per layer. Check the source field.
47
- - **Community submissions**: ALWAYS check list_submissions alongside list_layers when searching. Community layers may cover areas or topics that curated layers don't. They work with query_layer and get_layer_schema identically.
48
- - When multiple sources exist, tell the user which one you're using and why. If results seem wrong, try the alternate source.
49
-
50
- Cross-layer queries (combining data from different layers):
51
- - Questions often span multiple layers and categories. "Which wards are near an international airport?" needs the airports layer (transport) + a city ward layer (city-wards).
52
- - **Step 1**: identify all relevant layers using list_layers with different q/category filters.
53
- - **Step 2**: query one layer to get a geographic anchor (e.g. airport location → state/district).
54
- - **Step 3**: use that anchor to find the right layer in the other category (e.g. wards_bengaluru_gba for Karnataka airports).
55
- - **Step 4**: use locate or column filters to find overlapping features.
56
- - Never assume one layer is enough. Think about what layers need to be combined to answer the question fully.
57
- - Use locate as the bridge: find what's at a point across ALL relevant layers in one call by passing multiple layer IDs.
58
- - **Map user concepts to multiple layers.** Users say "water bodies" not "wris_rivers." Translate:
59
- - "water bodies/water" → wris_rivers, wris_reservoirs, bp_wetlands, bp_ramsar, wris_basin, wris_subbasin, wris_canals
60
- - "groundwater/aquifer/water table" → cgwb_aquifers, cgwb_gw_extraction, mi6_wells_districts
61
- - "wells/borewells/tubewells/irrigation pumps" → mi6_wells_districts (census counts per district, 2017-18)
62
- - "forests/green cover/ecology" → soi_forests, gs_wildlife, bm_eco_zones, biogeographic_zones
63
- - "agriculture/farming/cropping zones" → agro_ecological_zones, agro_climatic_zones, corestack_lulc_blocks (land use and cropping intensity by block, modelled)
64
- - "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)
65
- - "hazards/risks" → seismic_zones, india_flood_inventory
66
- - "health/medical" → nic_health
67
- - "boundaries/admin" → lgd_states, lgd_districts, lgd_subdistricts, lgd_blocks, lgd_villages
68
- - "roads/transport" → gs_highways, airports
69
- 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.
70
- - **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.
71
-
72
- Column naming conventions (vary by source):
73
- - State: State_LGD (number), STNAME, stname, state, state_name
74
- - District: Dist_LGD (number), DTNAME, dtname, district, dtcode11
75
- - Block: Block_LGD, BNAME, block_name, blkcode11
76
- - Names are often UPPERCASE in LGD layers, mixed case in other sources
27
+ ${INSTRUCTIONS_CORE}
77
28
 
78
29
  Collect (author your own map): this server also drives collect.bharatlas.com, the crowd map-capture tool in the bharatlas suite.
79
30
  - 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).
@@ -84,195 +35,10 @@ Collect (author your own map): this server also drives collect.bharatlas.com, th
84
35
  - 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).
85
36
  - 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.`;
86
37
 
38
+ // The eight read tools live in read-tools.js (shared with bharatlas.com/mcp);
39
+ // the collect tools need the local credential store, so they are npm-only.
87
40
  const TOOLS = [
88
- {
89
- name: "list_layers",
90
- description:
91
- "List available geo layers. Use to discover what data bharatlas has. " +
92
- "Returns layer IDs, names, row counts, categories, and download formats. " +
93
- "Filter by category (boundaries, city-wards, environment, water, agriculture, transport, etc.), " +
94
- "admin level (state, district, block, village, etc.), source, or text search.",
95
- inputSchema: {
96
- type: "object",
97
- properties: {
98
- category: {
99
- type: "string",
100
- description: "Filter by category: boundaries, city-wards, people, environment, water, agriculture, transport, infrastructure, health-edu",
101
- },
102
- level: {
103
- type: "string",
104
- description: "Filter by admin level: state, district, subdistrict, block, village, etc.",
105
- },
106
- source: {
107
- type: "string",
108
- description: "Filter by data source: LGD, SOI, Bhuvan, OpenCity, DataMeet, etc.",
109
- },
110
- q: {
111
- type: "string",
112
- description: "Text search across layer IDs, sources, and descriptions",
113
- },
114
- limit: { type: "number", description: "Max results (default 20)" },
115
- offset: { type: "number", description: "Skip N results for pagination" },
116
- },
117
- },
118
- },
119
- {
120
- name: "get_layer_schema",
121
- description:
122
- "Get column names, types, and sample values for a layer. " +
123
- "Use BEFORE querying to discover what columns exist and what values they contain. " +
124
- "Essential for knowing the right column names for filters.",
125
- inputSchema: {
126
- type: "object",
127
- properties: {
128
- layer_id: {
129
- type: "string",
130
- description: "Layer ID (e.g. lgd_states, airports, soi_forests, wards_chennai)",
131
- },
132
- },
133
- required: ["layer_id"],
134
- },
135
- },
136
- {
137
- name: "query_layer",
138
- description:
139
- "Query a layer's data with filters and grouping. Reads the parquet file at runtime. " +
140
- "Supports: select specific columns, filter by column values, group by a column to get counts, " +
141
- "and sum numeric columns per group (e.g. roll block areas up to district totals). " +
142
- "Use get_layer_schema first to discover column names. " +
143
- "Examples: 'airports in Karnataka' -> where: {state: 'KA'}, " +
144
- "'forest types' -> group_by: 'type', " +
145
- "'health facilities in Bihar' -> where: {state: 'BIHAR'}, select: ['name', 'type'].",
146
- inputSchema: {
147
- type: "object",
148
- properties: {
149
- layer_id: {
150
- type: "string",
151
- description: "Layer ID to query",
152
- },
153
- select: {
154
- type: "array",
155
- items: { type: "string" },
156
- description: "Column names to return. Omit for all non-geometry columns.",
157
- },
158
- where: {
159
- type: "object",
160
- additionalProperties: { type: "string" },
161
- description: "Filter conditions as {column: value} pairs. Exact, case-insensitive match on flat columns (not partial). Values may contain commas.",
162
- },
163
- group_by: {
164
- type: "string",
165
- description: "Column to group by. Returns {value: count} instead of rows.",
166
- },
167
- sum: {
168
- type: "array",
169
- items: { type: "string" },
170
- description: "Numeric columns to total per group (requires group_by). Adds {sums: {group: {col: total}}}. Use this to roll finer units up, e.g. block-level areas to district totals. Shares/percentages are not additive: sum the area columns and recompute shares.",
171
- },
172
- limit: { type: "number", description: "Max rows (default 100, max 1000)" },
173
- include_centroid: {
174
- type: "boolean",
175
- description: "Include _lat/_lng centroid coordinates (defaults to true). Set false to exclude.",
176
- },
177
- },
178
- required: ["layer_id"],
179
- },
180
- },
181
- {
182
- name: "locate",
183
- description:
184
- "Given a latitude/longitude, find which administrative boundaries, zones, and regions " +
185
- "contain that point. Returns state, district, subdistrict, block, parliament/assembly " +
186
- "constituency, pincode, seismic zone, high court jurisdiction, the municipal ward (for " +
187
- "the ~30 cities with ward data), and more. " +
188
- "The 'where am I?' tool. Also accepts specific layer IDs to check.",
189
- inputSchema: {
190
- type: "object",
191
- properties: {
192
- lat: {
193
- type: "number",
194
- description: "Latitude (6 to 38, India bounding box)",
195
- },
196
- lng: {
197
- type: "number",
198
- description: "Longitude (68 to 98, India bounding box)",
199
- },
200
- layers: {
201
- type: "array",
202
- items: { type: "string" },
203
- 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).",
204
- },
205
- },
206
- required: ["lat", "lng"],
207
- },
208
- },
209
- {
210
- name: "nearby",
211
- description:
212
- "Find features from a layer that are near a given point, nearest first, within radius_km. " +
213
- "Reads the layer's parquet bounding boxes and ranks features by distance to their centres; " +
214
- "works for points, polygons and lines. Returns the true count within the radius plus the nearest `limit`. " +
215
- "Example: 'reservoirs near Bengaluru' -> layer_id: 'wris_reservoirs', lat: 12.97, lng: 77.59, radius_km: 50.",
216
- inputSchema: {
217
- type: "object",
218
- properties: {
219
- layer_id: {
220
- type: "string",
221
- description: "Layer to search for nearby features",
222
- },
223
- lat: { type: "number", description: "Center point latitude" },
224
- lng: { type: "number", description: "Center point longitude" },
225
- radius_km: {
226
- type: "number",
227
- description: "Search radius in kilometres (default 25, max 200)",
228
- },
229
- limit: { type: "number", description: "Max results (default 20)" },
230
- },
231
- required: ["layer_id", "lat", "lng"],
232
- },
233
- },
234
- {
235
- name: "list_categories",
236
- description: "List all data categories with layer counts.",
237
- inputSchema: { type: "object", properties: {} },
238
- },
239
- {
240
- name: "get_layer_detail",
241
- description:
242
- "Get full metadata for a single layer: download URLs (parquet, pmtiles, geojson, kml, shapefile), " +
243
- "attribution, license, feature count, and level metadata.",
244
- inputSchema: {
245
- type: "object",
246
- properties: {
247
- layer_id: {
248
- type: "string",
249
- description: "Layer ID",
250
- },
251
- },
252
- required: ["layer_id"],
253
- },
254
- },
255
- {
256
- name: "list_submissions",
257
- description:
258
- "List community-submitted geo layers. These are user-contributed datasets " +
259
- "under open licenses. Filter by category or search by name.",
260
- inputSchema: {
261
- type: "object",
262
- properties: {
263
- q: { type: "string", description: "Search name and description" },
264
- category: { type: "string", description: "Filter by category" },
265
- sort: {
266
- type: "string",
267
- enum: ["recent", "useful"],
268
- description: "Sort order (default: recent)",
269
- },
270
- limit: { type: "number", description: "Max results (default 20)" },
271
- offset: { type: "number", description: "Pagination offset" },
272
- },
273
- },
274
- },
275
-
41
+ ...READ_TOOLS,
276
42
  // --- collect (authoring): act only on maps whose share link you registered ---
277
43
  {
278
44
  name: "register_map",
@@ -301,7 +67,8 @@ const TOOLS = [
301
67
  name: "get_records",
302
68
  description:
303
69
  "A collect map's records as a GeoJSON FeatureCollection — for reading, analysis, or backup/export. " +
304
- "view and collect scope return published points; admin can also read pending/rejected via status.",
70
+ "view and collect scope return published points; admin can also read pending/rejected via status. " +
71
+ "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).",
305
72
  inputSchema: {
306
73
  type: "object",
307
74
  properties: { id: { type: "string" }, status: { type: "string", description: "admin only: pending | published | rejected" } },
@@ -373,7 +140,8 @@ const TOOLS = [
373
140
  purpose: { type: "string", description: "shown to contributors" },
374
141
  description: { type: "string" },
375
142
  geometry: { type: "array", items: { enum: ["point", "line", "polygon"] }, description: "what contributors may add" },
376
- fields: { type: "array", items: { type: "object" }, description: "the form for each record (see collect.bharatlas.com/schema/v1.json)" },
143
+ fields: { type: "array", items: { type: "object" }, description: "the form for each record (see collect.bharatlas.com/schema/v1.json); a field of type \"photo\" (max_photos 1-3) asks for photos" },
144
+ mode: { enum: ["form", "form_ai", "photos_ai"], description: "how people collect: form (default); form_ai = form plus notes a model writes from the photo, for the owner to check; photos_ai = people only take photos and the model fills the form (places only). AI modes need a photo field." },
377
145
  license: { type: "string", description: "open licence id; default CC-BY-4.0" },
378
146
  category: { type: "string" },
379
147
  data_year: { type: "integer" },
@@ -402,16 +170,9 @@ function httpGet(url) {
402
170
  });
403
171
  }
404
172
 
405
- // Mirrors RESERVED in web/functions/lib/query-params.ts: these names are query
406
- // options, so a where column with one of them must go inside where=.
407
- const QUERY_RESERVED = new Set(["select", "group_by", "sum", "limit", "where", "order_by", "include_centroid"]);
408
-
409
173
  async function callApi(path, params = {}) {
410
- const url = new URL(API + path);
411
- for (const [k, v] of Object.entries(params)) {
412
- if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
413
- }
414
- return httpGet(url.toString());
174
+ const qs = toSearchParams(params).toString();
175
+ return httpGet(`${API}${path}${qs ? `?${qs}` : ""}`);
415
176
  }
416
177
 
417
178
  // ---- collect: local credential store + scoped auth --------------------------
@@ -481,66 +242,11 @@ function collectApi(method, path, { token, apiKey, body } = {}) {
481
242
 
482
243
  async function handleTool(name, args) {
483
244
  switch (name) {
484
- case "list_layers": {
485
- const { category, level, source, q, limit = 20, offset } = args;
486
- const result = await callApi("/layers", { category, level, source, q, limit, offset });
487
- // FIX #1: compact response - strip download URLs from list view
488
- if (result.data) {
489
- result.data = result.data.map((l) => ({
490
- id: l.id, level: l.level, source: l.source, category: l.category,
491
- rows: l.rows, licence: l.licence, notes: l.notes,
492
- }));
493
- }
494
- return result;
495
- }
496
-
497
- case "get_layer_schema": {
498
- return callApi(`/layers/${args.layer_id}/schema`);
499
- }
500
-
501
- case "query_layer": {
502
- const { layer_id, select, where, group_by, sum, limit, include_centroid } = args;
503
- const params = {};
504
- if (select?.length) params.select = select.join(",");
505
- if (group_by) params.group_by = group_by;
506
- if (sum?.length) params.sum = sum.join(",");
507
- if (limit) params.limit = limit;
508
- if (include_centroid !== undefined) params.include_centroid = String(include_centroid);
509
- // Each filter as its own ?col=val param so values may contain commas (the
510
- // API splits a where= string on commas). Columns named like a reserved
511
- // param must still travel inside where=.
512
- const reservedWhere = [];
513
- for (const [k, v] of Object.entries(where || {})) {
514
- if (QUERY_RESERVED.has(k)) reservedWhere.push(`${k}=${v}`);
515
- else params[k] = v;
516
- }
517
- if (reservedWhere.length) params.where = reservedWhere.join(",");
518
- return callApi(`/layers/${layer_id}/query`, params);
519
- }
520
-
521
- case "nearby": {
522
- const { layer_id, lat, lng, radius_km = 25, limit = 20 } = args;
523
- return callApi("/nearby", { lat, lng, layer: layer_id, radius_km: Math.min(radius_km, 200), limit });
524
- }
525
-
526
- case "locate": {
527
- const { lat, lng, layers } = args;
528
- const params = { lat, lng };
529
- if (layers?.length) params.layers = layers.join(",");
530
- return callApi("/locate", params);
531
- }
532
-
533
- case "list_categories": {
534
- return callApi("/categories");
535
- }
536
-
537
- case "get_layer_detail": {
538
- return callApi(`/layers/${args.layer_id}`);
539
- }
540
-
541
- case "list_submissions": {
542
- const { q, category, sort, limit = 20, offset } = args;
543
- return callApi("/submissions", { q, category, sort, limit, offset });
245
+ // --- read tools (read-tools.js) ---
246
+ case "list_layers": case "get_layer_schema": case "query_layer": case "nearby":
247
+ case "locate": case "list_categories": case "get_layer_detail": case "list_submissions": {
248
+ const req = readToolRequest(name, args);
249
+ return shapeReadResult(name, await callApi(req.path, req.params));
544
250
  }
545
251
 
546
252
  // --- collect (authoring) ---
@@ -602,6 +308,7 @@ async function handleTool(name, args) {
602
308
  const schema_doc = { version: 1, geometry: args.geometry, fields: args.fields };
603
309
  if (args.category) schema_doc.category = args.category;
604
310
  if (args.basemap) schema_doc.basemap = args.basemap;
311
+ if (args.mode && args.mode !== "form") schema_doc.mode = args.mode;
605
312
  const body = {
606
313
  name: args.name, purpose: args.purpose, description: args.description,
607
314
  license: args.license || "CC-BY-4.0", data_year: args.data_year,
@@ -624,7 +331,7 @@ async function handleTool(name, args) {
624
331
  }
625
332
 
626
333
  const server = new Server(
627
- { name: "bharatlas-mcp", version: "1.3.0" },
334
+ { name: "bharatlas-mcp", version: "1.4.0" },
628
335
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS },
629
336
  );
630
337
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bharatlas-mcp",
3
- "version": "1.3.0",
3
+ "version": "1.4.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" },
package/read-tools.js ADDED
@@ -0,0 +1,339 @@
1
+ // The bharatlas read tools, shared by the npm stdio server (index.js) and the
2
+ // hosted server at https://bharatlas.com/mcp (web/functions/lib/mcp.ts), so the
3
+ // two never drift. Plain ESM with no Node or Workers APIs: each tool call maps to
4
+ // a GET on the bharatlas API (/api/v1) and its result is shaped the same way.
5
+
6
+ /** How an agent should use the read tools; each server adds its own intro. */
7
+ export const INSTRUCTIONS_CORE = `Workflow patterns:
8
+
9
+ - **Discovery**: start with list_layers or list_categories to find relevant layers. Use the q parameter for text search.
10
+ - **Schema first**: always call get_layer_schema BEFORE query_layer. Column names vary per layer (e.g. "state" vs "State_LGD" vs "stname"). The schema shows exact names and sample values.
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
+ - **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
+ - **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?"
15
+ - **Spatial joins** (multi-step): to answer "which X are in Y?" when layers don't share a common column:
16
+ 1. Use locate to find the admin context (state, district) of the target area
17
+ 2. Use query_layer with a where filter to narrow the other layer by that admin context
18
+ 3. For precise spatial containment, test individual points via locate against the target layer
19
+ - **Community layers**: list_submissions returns user-contributed datasets. These work with query_layer and get_layer_schema exactly like curated layers.
20
+ - **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
+ - **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.
23
+
24
+ Source preference (multiple layers often cover the same level):
25
+ - **Admin boundaries** (state, district, subdistrict, block, village): prefer LGD (lgd_*) as the authoritative source. SOI, Bhuvan, and geoBoundaries are cross-reference alternates with slightly different counts/boundaries. Mention alternates if the user asks about discrepancies.
26
+ - **City wards**: each city has its own layer (wards_chennai, wards_pune, etc.). Some cities have multiple vintages (e.g. Bengaluru has GBA 2025 + BBMP 2022 historical).
27
+ - **Environment/infrastructure/health**: usually one source per layer. Check the source field.
28
+ - **Community submissions**: ALWAYS check list_submissions alongside list_layers when searching. Community layers may cover areas or topics that curated layers don't. They work with query_layer and get_layer_schema identically.
29
+ - When multiple sources exist, tell the user which one you're using and why. If results seem wrong, try the alternate source.
30
+
31
+ Cross-layer queries (combining data from different layers):
32
+ - Questions often span multiple layers and categories. "Which wards are near an international airport?" needs the airports layer (transport) + a city ward layer (city-wards).
33
+ - **Step 1**: identify all relevant layers using list_layers with different q/category filters.
34
+ - **Step 2**: query one layer to get a geographic anchor (e.g. airport location → state/district).
35
+ - **Step 3**: use that anchor to find the right layer in the other category (e.g. wards_bengaluru_gba for Karnataka airports).
36
+ - **Step 4**: use locate or column filters to find overlapping features.
37
+ - Never assume one layer is enough. Think about what layers need to be combined to answer the question fully.
38
+ - Use locate as the bridge: find what's at a point across ALL relevant layers in one call by passing multiple layer IDs.
39
+ - **Map user concepts to multiple layers.** Users say "water bodies" not "wris_rivers." Translate:
40
+ - "water bodies/water" → wris_rivers, wris_reservoirs, bp_wetlands, bp_ramsar, wris_basin, wris_subbasin, wris_canals
41
+ - "groundwater/aquifer/water table" → cgwb_aquifers, cgwb_gw_extraction, mi6_wells_districts
42
+ - "wells/borewells/tubewells/irrigation pumps" → mi6_wells_districts (census counts per district, 2017-18)
43
+ - "forests/green cover/ecology" → soi_forests, gs_wildlife, bm_eco_zones, biogeographic_zones
44
+ - "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)
46
+ - "hazards/risks" → seismic_zones, india_flood_inventory
47
+ - "health/medical" → nic_health
48
+ - "boundaries/admin" → lgd_states, lgd_districts, lgd_subdistricts, lgd_blocks, lgd_villages
49
+ - "roads/transport" → gs_highways, airports
50
+ 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
+ - **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
+
53
+ Column naming conventions (vary by source):
54
+ - State: State_LGD (number), STNAME, stname, state, state_name
55
+ - District: Dist_LGD (number), DTNAME, dtname, district, dtcode11
56
+ - Block: Block_LGD, BNAME, block_name, blkcode11
57
+ - Names are often UPPERCASE in LGD layers, mixed case in other sources`;
58
+
59
+ const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
60
+
61
+ export const READ_TOOLS = [
62
+ {
63
+ name: "list_layers",
64
+ description:
65
+ "List available geo layers. Use to discover what data bharatlas has. " +
66
+ "Returns layer IDs, names, row counts, categories, and download formats. " +
67
+ "Filter by category (boundaries, city-wards, environment, water, agriculture, transport, etc.), " +
68
+ "admin level (state, district, block, village, etc.), source, or text search.",
69
+ inputSchema: {
70
+ type: "object",
71
+ properties: {
72
+ category: {
73
+ type: "string",
74
+ description: "Filter by category: boundaries, city-wards, people, environment, water, agriculture, transport, infrastructure, health-edu",
75
+ },
76
+ level: {
77
+ type: "string",
78
+ description: "Filter by admin level: state, district, subdistrict, block, village, etc.",
79
+ },
80
+ source: {
81
+ type: "string",
82
+ description: "Filter by data source: LGD, SOI, Bhuvan, OpenCity, DataMeet, etc.",
83
+ },
84
+ q: {
85
+ type: "string",
86
+ description: "Text search across layer IDs, sources, and descriptions",
87
+ },
88
+ limit: { type: "number", description: "Max results (default 20)" },
89
+ offset: { type: "number", description: "Skip N results for pagination" },
90
+ },
91
+ },
92
+ },
93
+ {
94
+ name: "get_layer_schema",
95
+ description:
96
+ "Get column names, types, and sample values for a layer. " +
97
+ "Use BEFORE querying to discover what columns exist and what values they contain. " +
98
+ "Essential for knowing the right column names for filters.",
99
+ inputSchema: {
100
+ type: "object",
101
+ properties: {
102
+ layer_id: {
103
+ type: "string",
104
+ description: "Layer ID (e.g. lgd_states, airports, soi_forests, wards_chennai)",
105
+ },
106
+ },
107
+ required: ["layer_id"],
108
+ },
109
+ },
110
+ {
111
+ name: "query_layer",
112
+ description:
113
+ "Query a layer's data with filters and grouping. Reads the parquet file at runtime. " +
114
+ "Supports: select specific columns, filter by column values, group by a column to get counts, " +
115
+ "and sum numeric columns per group (e.g. roll block areas up to district totals). " +
116
+ "Use get_layer_schema first to discover column names. " +
117
+ "Examples: 'airports in Karnataka' -> where: {state: 'KA'}, " +
118
+ "'forest types' -> group_by: 'type', " +
119
+ "'health facilities in Bihar' -> where: {state: 'BIHAR'}, select: ['name', 'type'].",
120
+ inputSchema: {
121
+ type: "object",
122
+ properties: {
123
+ layer_id: {
124
+ type: "string",
125
+ description: "Layer ID to query",
126
+ },
127
+ select: {
128
+ type: "array",
129
+ items: { type: "string" },
130
+ description: "Column names to return. Omit for all non-geometry columns.",
131
+ },
132
+ where: {
133
+ type: "object",
134
+ additionalProperties: { type: "string" },
135
+ description: "Filter conditions as {column: value} pairs. Exact, case-insensitive match on flat columns (not partial). Values may contain commas.",
136
+ },
137
+ group_by: {
138
+ type: "string",
139
+ description: "Column to group by. Returns {value: count} instead of rows.",
140
+ },
141
+ sum: {
142
+ type: "array",
143
+ items: { type: "string" },
144
+ description: "Numeric columns to total per group (requires group_by). Adds {sums: {group: {col: total}}}. Use this to roll finer units up, e.g. block-level areas to district totals. Shares/percentages are not additive: sum the area columns and recompute shares.",
145
+ },
146
+ limit: { type: "number", description: "Max rows (default 100, max 1000)" },
147
+ include_centroid: {
148
+ type: "boolean",
149
+ description: "Include _lat/_lng centroid coordinates (defaults to true). Set false to exclude.",
150
+ },
151
+ },
152
+ required: ["layer_id"],
153
+ },
154
+ },
155
+ {
156
+ name: "locate",
157
+ description:
158
+ "Given a latitude/longitude, find which administrative boundaries, zones, and regions " +
159
+ "contain that point. Returns state, district, subdistrict, block, parliament/assembly " +
160
+ "constituency, pincode, seismic zone, high court jurisdiction, the municipal ward (for " +
161
+ "the ~30 cities with ward data), and more. " +
162
+ "The 'where am I?' tool. Also accepts specific layer IDs to check.",
163
+ inputSchema: {
164
+ type: "object",
165
+ properties: {
166
+ lat: {
167
+ type: "number",
168
+ description: "Latitude (6 to 38, India bounding box)",
169
+ },
170
+ lng: {
171
+ type: "number",
172
+ description: "Longitude (68 to 98, India bounding box)",
173
+ },
174
+ layers: {
175
+ type: "array",
176
+ 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).",
178
+ },
179
+ },
180
+ required: ["lat", "lng"],
181
+ },
182
+ },
183
+ {
184
+ name: "nearby",
185
+ description:
186
+ "Find features from a layer that are near a given point, nearest first, within radius_km. " +
187
+ "Reads the layer's parquet bounding boxes and ranks features by distance to their centres; " +
188
+ "works for points, polygons and lines. Returns the true count within the radius plus the nearest `limit`. " +
189
+ "Example: 'reservoirs near Bengaluru' -> layer_id: 'wris_reservoirs', lat: 12.97, lng: 77.59, radius_km: 50.",
190
+ inputSchema: {
191
+ type: "object",
192
+ properties: {
193
+ layer_id: {
194
+ type: "string",
195
+ description: "Layer to search for nearby features",
196
+ },
197
+ lat: { type: "number", description: "Center point latitude" },
198
+ lng: { type: "number", description: "Center point longitude" },
199
+ radius_km: {
200
+ type: "number",
201
+ description: "Search radius in kilometres (default 25, max 200)",
202
+ },
203
+ limit: { type: "number", description: "Max results (default 20)" },
204
+ },
205
+ required: ["layer_id", "lat", "lng"],
206
+ },
207
+ },
208
+ {
209
+ name: "list_categories",
210
+ description: "List all data categories with layer counts.",
211
+ inputSchema: { type: "object", properties: {} },
212
+ },
213
+ {
214
+ name: "get_layer_detail",
215
+ description:
216
+ "Get full metadata for a single layer: download URLs (parquet, pmtiles, geojson, kml, shapefile), " +
217
+ "attribution, license, feature count, and level metadata.",
218
+ inputSchema: {
219
+ type: "object",
220
+ properties: {
221
+ layer_id: {
222
+ type: "string",
223
+ description: "Layer ID",
224
+ },
225
+ },
226
+ required: ["layer_id"],
227
+ },
228
+ },
229
+ {
230
+ name: "list_submissions",
231
+ description:
232
+ "List community-submitted geo layers. These are user-contributed datasets " +
233
+ "under open licenses. Filter by category or search by name.",
234
+ inputSchema: {
235
+ type: "object",
236
+ properties: {
237
+ q: { type: "string", description: "Search name and description" },
238
+ category: { type: "string", description: "Filter by category" },
239
+ sort: {
240
+ type: "string",
241
+ enum: ["recent", "useful"],
242
+ description: "Sort order (default: recent)",
243
+ },
244
+ limit: { type: "number", description: "Max results (default 20)" },
245
+ offset: { type: "number", description: "Pagination offset" },
246
+ },
247
+ },
248
+ },
249
+ ].map((t) => ({ ...t, annotations: READ_ONLY }));
250
+
251
+ const READ_NAMES = new Set(READ_TOOLS.map((t) => t.name));
252
+
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
+
257
+ const LAYER_ID = /^[a-zA-Z0-9_-]+$/;
258
+ function layerPath(id, suffix = "") {
259
+ if (!LAYER_ID.test(String(id ?? ""))) {
260
+ throw new Error("layer_id must be a layer ID such as lgd_states (letters, digits, _ and -)");
261
+ }
262
+ return `/layers/${id}${suffix}`;
263
+ }
264
+
265
+ /** The API GET a read tool makes: { path, params } under /api/v1, or null when
266
+ * `name` is not a read tool. Throws on a layer_id the API could never accept. */
267
+ export function readToolRequest(name, args = {}) {
268
+ if (!READ_NAMES.has(name)) return null;
269
+ switch (name) {
270
+ case "list_layers": {
271
+ const { category, level, source, q, limit = 20, offset } = args;
272
+ return { path: "/layers", params: { category, level, source, q, limit, offset } };
273
+ }
274
+ case "get_layer_schema":
275
+ return { path: layerPath(args.layer_id, "/schema"), params: {} };
276
+ case "query_layer": {
277
+ const { layer_id, select, where, group_by, sum, limit, include_centroid } = args;
278
+ const params = {};
279
+ if (select?.length) params.select = select.join(",");
280
+ if (group_by) params.group_by = group_by;
281
+ if (sum?.length) params.sum = sum.join(",");
282
+ if (limit) params.limit = limit;
283
+ if (include_centroid !== undefined) params.include_centroid = String(include_centroid);
284
+ // Each filter as its own ?col=val param so values may contain commas (the
285
+ // API splits a where= string on commas). Columns named like a reserved
286
+ // param must still travel inside where=.
287
+ const reservedWhere = [];
288
+ for (const [k, v] of Object.entries(where || {})) {
289
+ if (QUERY_RESERVED.has(k)) reservedWhere.push(`${k}=${v}`);
290
+ else params[k] = v;
291
+ }
292
+ if (reservedWhere.length) params.where = reservedWhere.join(",");
293
+ return { path: layerPath(layer_id, "/query"), params };
294
+ }
295
+ case "nearby": {
296
+ const { layer_id, lat, lng, radius_km = 25, limit = 20 } = args;
297
+ return { path: "/nearby", params: { lat, lng, layer: layer_id, radius_km: Math.min(radius_km, 200), limit } };
298
+ }
299
+ case "locate": {
300
+ const { lat, lng, layers } = args;
301
+ const params = { lat, lng };
302
+ if (layers?.length) params.layers = layers.join(",");
303
+ return { path: "/locate", params };
304
+ }
305
+ case "list_categories":
306
+ return { path: "/categories", params: {} };
307
+ case "get_layer_detail":
308
+ return { path: layerPath(args.layer_id), params: {} };
309
+ case "list_submissions": {
310
+ const { q, category, sort, limit = 20, offset } = args;
311
+ return { path: "/submissions", params: { q, category, sort, limit, offset } };
312
+ }
313
+ }
314
+ return null;
315
+ }
316
+
317
+ /** The query string for a request's params, skipping unset values. */
318
+ export function toSearchParams(params) {
319
+ const sp = new URLSearchParams();
320
+ for (const [k, v] of Object.entries(params)) {
321
+ if (v !== undefined && v !== null) sp.set(k, String(v));
322
+ }
323
+ return sp;
324
+ }
325
+
326
+ /** Shape an API answer for the model: list_layers drops the per-layer download
327
+ * URLs (get_layer_detail has them), which keeps the list compact. */
328
+ export function shapeReadResult(name, result) {
329
+ if (name === "list_layers" && Array.isArray(result?.data)) {
330
+ return {
331
+ ...result,
332
+ data: result.data.map((l) => ({
333
+ id: l.id, level: l.level, source: l.source, category: l.category,
334
+ rows: l.rows, licence: l.licence, notes: l.notes,
335
+ })),
336
+ };
337
+ }
338
+ return result;
339
+ }
package/server.json CHANGED
@@ -1,14 +1,45 @@
1
1
  {
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "io.github.sathya-sankaran/bharatlas-mcp",
4
+ "title": "bharatlas",
4
5
  "description": "Query India's open geo data, and author collect maps: register a link, moderate, publish.",
5
- "version": "1.3.0",
6
+ "websiteUrl": "https://bharatlas.com",
7
+ "repository": {
8
+ "url": "https://github.com/urbanmorph/geodata",
9
+ "source": "github",
10
+ "subfolder": "mcp"
11
+ },
12
+ "icons": [
13
+ {
14
+ "src": "https://bharatlas.com/favicon.svg",
15
+ "mimeType": "image/svg+xml",
16
+ "sizes": [
17
+ "any"
18
+ ]
19
+ },
20
+ {
21
+ "src": "https://bharatlas.com/apple-touch-icon.png",
22
+ "mimeType": "image/png",
23
+ "sizes": [
24
+ "180x180"
25
+ ]
26
+ }
27
+ ],
28
+ "version": "1.4.0",
6
29
  "packages": [
7
30
  {
8
31
  "registryType": "npm",
9
32
  "identifier": "bharatlas-mcp",
10
- "version": "1.3.0",
11
- "transport": { "type": "stdio" }
33
+ "version": "1.4.0",
34
+ "transport": {
35
+ "type": "stdio"
36
+ }
37
+ }
38
+ ],
39
+ "remotes": [
40
+ {
41
+ "type": "streamable-http",
42
+ "url": "https://bharatlas.com/mcp"
12
43
  }
13
44
  ]
14
45
  }