bharatlas-mcp 1.3.0 → 1.5.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 +3 -1
- package/import-records.js +36 -0
- package/import-records.test.js +43 -0
- package/index.js +33 -316
- package/package.json +5 -1
- package/read-tools.js +339 -0
- package/server.json +34 -3
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
|
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// import_points: give each record its client_id (the row's own id, scoped to
|
|
2
|
+
// the map) so re-running an import adds nothing and a corrected re-run updates
|
|
3
|
+
// rows in place. The server enforces it; this only picks the id out of the input.
|
|
4
|
+
|
|
5
|
+
const idText = (v) => {
|
|
6
|
+
if (typeof v === "number") return Number.isFinite(v) ? String(v) : undefined;
|
|
7
|
+
return typeof v === "string" && v.trim() !== "" ? v : undefined;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Where each record's client_id comes from, first match wins:
|
|
12
|
+
* 1. `client_id` already on the record;
|
|
13
|
+
* 2. with `clientIdField` (a non-empty string): that property;
|
|
14
|
+
* without it: the GeoJSON feature `id`, then an `id` property.
|
|
15
|
+
* An empty `clientIdField` turns the default off. Records with no usable id are
|
|
16
|
+
* sent without one (the server adds them again on a re-run).
|
|
17
|
+
*/
|
|
18
|
+
export function withClientIds(records, clientIdField) {
|
|
19
|
+
return records.map((r) => {
|
|
20
|
+
if (!r || typeof r !== "object" || r.client_id !== undefined) return r;
|
|
21
|
+
const props = r.properties && typeof r.properties === "object" ? r.properties : {};
|
|
22
|
+
const id = clientIdField === undefined || clientIdField === null
|
|
23
|
+
? idText(r.id) ?? idText(props.id)
|
|
24
|
+
: clientIdField === "" ? undefined : idText(props[clientIdField]);
|
|
25
|
+
return id === undefined ? r : { ...r, client_id: id };
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** One line for the tool result: what the import did. */
|
|
30
|
+
export function importSummary(res, withoutId) {
|
|
31
|
+
const refused = res.errors?.length ?? 0;
|
|
32
|
+
return [
|
|
33
|
+
`${res.added ?? res.imported ?? 0} added, ${res.updated ?? 0} updated, ${res.unchanged ?? 0} unchanged of ${res.total} rows${refused ? `; ${refused} refused (see errors)` : ""}.`,
|
|
34
|
+
withoutId ? `${withoutId} row${withoutId === 1 ? "" : "s"} had no client_id, so re-running adds ${withoutId === 1 ? "it" : "them"} again.` : "",
|
|
35
|
+
].filter(Boolean).join(" ");
|
|
36
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Unit tests for import_points' record shaping (no network). Run: node --test
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import assert from "node:assert/strict";
|
|
4
|
+
import { withClientIds, importSummary } from "./import-records.js";
|
|
5
|
+
|
|
6
|
+
const g = { type: "Point", coordinates: [77.59, 12.97] };
|
|
7
|
+
|
|
8
|
+
test("client_id_field names the property that carries each row's id", () => {
|
|
9
|
+
const out = withClientIds([{ geometry: g, properties: { code: 101, name: "A" } }], "code");
|
|
10
|
+
assert.equal(out[0].client_id, "101");
|
|
11
|
+
assert.deepEqual(out[0].properties, { code: 101, name: "A" });
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test("by default the feature id is the client id, then an `id` property", () => {
|
|
15
|
+
const out = withClientIds([
|
|
16
|
+
{ type: "Feature", id: "f-1", geometry: g, properties: { id: "p-1" } },
|
|
17
|
+
{ geometry: g, properties: { id: 7 } },
|
|
18
|
+
{ geometry: g, properties: { name: "no id" } },
|
|
19
|
+
]);
|
|
20
|
+
assert.deepEqual(out.map((r) => r.client_id), ["f-1", "7", undefined]);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("a client_id already on the record wins; an empty client_id_field turns the default off", () => {
|
|
24
|
+
assert.equal(withClientIds([{ client_id: "mine", id: "f", geometry: g, properties: {} }], "id")[0].client_id, "mine");
|
|
25
|
+
assert.equal(withClientIds([{ id: "f", geometry: g, properties: { id: "p" } }], "")[0].client_id, undefined);
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test("blank and non-scalar ids are left out (the server would refuse them)", () => {
|
|
29
|
+
const out = withClientIds([
|
|
30
|
+
{ geometry: g, properties: { code: " " } },
|
|
31
|
+
{ geometry: g, properties: { code: { a: 1 } } },
|
|
32
|
+
{ geometry: g, properties: { code: Number.NaN } },
|
|
33
|
+
], "code");
|
|
34
|
+
assert.deepEqual(out.map((r) => r.client_id), [undefined, undefined, undefined]);
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
test("the summary names added, updated and unchanged", () => {
|
|
38
|
+
assert.equal(
|
|
39
|
+
importSummary({ added: 1, updated: 2, unchanged: 3, total: 7, errors: [{ index: 0, error: "x" }] }, 1),
|
|
40
|
+
"1 added, 2 updated, 3 unchanged of 7 rows; 1 refused (see errors). 1 row had no client_id, so re-running adds it again.",
|
|
41
|
+
);
|
|
42
|
+
assert.equal(importSummary({ added: 3, updated: 0, unchanged: 0, total: 3, errors: [] }, 0), "3 added, 0 updated, 0 unchanged of 3 rows.");
|
|
43
|
+
});
|
package/index.js
CHANGED
|
@@ -10,6 +10,8 @@ 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";
|
|
14
|
+
import { withClientIds, importSummary } from "./import-records.js";
|
|
13
15
|
|
|
14
16
|
const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
|
|
15
17
|
|
|
@@ -23,57 +25,7 @@ const COLLECT_STORE = process.env.COLLECT_MCP_STORE || join(homedir(), ".bharatl
|
|
|
23
25
|
|
|
24
26
|
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
27
|
|
|
26
|
-
|
|
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
|
|
28
|
+
${INSTRUCTIONS_CORE}
|
|
77
29
|
|
|
78
30
|
Collect (author your own map): this server also drives collect.bharatlas.com, the crowd map-capture tool in the bharatlas suite.
|
|
79
31
|
- 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 +36,10 @@ Collect (author your own map): this server also drives collect.bharatlas.com, th
|
|
|
84
36
|
- 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
37
|
- 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
38
|
|
|
39
|
+
// The eight read tools live in read-tools.js (shared with bharatlas.com/mcp);
|
|
40
|
+
// the collect tools need the local credential store, so they are npm-only.
|
|
87
41
|
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
|
-
|
|
42
|
+
...READ_TOOLS,
|
|
276
43
|
// --- collect (authoring): act only on maps whose share link you registered ---
|
|
277
44
|
{
|
|
278
45
|
name: "register_map",
|
|
@@ -301,7 +68,8 @@ const TOOLS = [
|
|
|
301
68
|
name: "get_records",
|
|
302
69
|
description:
|
|
303
70
|
"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."
|
|
71
|
+
"view and collect scope return published points; admin can also read pending/rejected via status. " +
|
|
72
|
+
"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
73
|
inputSchema: {
|
|
306
74
|
type: "object",
|
|
307
75
|
properties: { id: { type: "string" }, status: { type: "string", description: "admin only: pending | published | rejected" } },
|
|
@@ -326,14 +94,20 @@ const TOOLS = [
|
|
|
326
94
|
name: "import_points",
|
|
327
95
|
description:
|
|
328
96
|
"Bulk-import points you already hold into a collect map (needs the admin link). NOT for synthetic data. " +
|
|
329
|
-
"Requires a named source + rights confirmation; each row lands with that source as its provenance."
|
|
97
|
+
"Requires a named source + rights confirmation; each row lands with that source as its provenance. " +
|
|
98
|
+
"Re-running is safe for rows with a client id (the row's own stable id, unique within the map, up to 128 characters): " +
|
|
99
|
+
"a row already imported with that id is updated in place if its data changed and otherwise left alone, so the same import twice adds nothing. " +
|
|
100
|
+
"The client id is the record's `client_id`, else the property named by client_id_field, else (by default) the GeoJSON feature `id`, then an `id` property. " +
|
|
101
|
+
"Rows without one are added again on every run. The result says how many were added, updated and unchanged (per batch of 100 in `batches`). " +
|
|
102
|
+
"Up to 5000 records per call.",
|
|
330
103
|
inputSchema: {
|
|
331
104
|
type: "object",
|
|
332
105
|
properties: {
|
|
333
106
|
id: { type: "string" },
|
|
334
|
-
records: { type: "array", items: { type: "object" }, description: "GeoJSON-like {geometry, properties}" },
|
|
107
|
+
records: { type: "array", items: { type: "object" }, description: "GeoJSON-like {geometry, properties}, optionally with client_id" },
|
|
335
108
|
source: { type: "string" },
|
|
336
109
|
rights_confirmed: { type: "boolean", description: "you have the right to publish this under the map's licence" },
|
|
110
|
+
client_id_field: { type: "string", description: "property holding each row's stable id (e.g. \"code\"); default: feature id, then an `id` property; \"\" for none" },
|
|
337
111
|
},
|
|
338
112
|
required: ["id", "records", "source", "rights_confirmed"],
|
|
339
113
|
},
|
|
@@ -373,7 +147,8 @@ const TOOLS = [
|
|
|
373
147
|
purpose: { type: "string", description: "shown to contributors" },
|
|
374
148
|
description: { type: "string" },
|
|
375
149
|
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)" },
|
|
150
|
+
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" },
|
|
151
|
+
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
152
|
license: { type: "string", description: "open licence id; default CC-BY-4.0" },
|
|
378
153
|
category: { type: "string" },
|
|
379
154
|
data_year: { type: "integer" },
|
|
@@ -402,16 +177,9 @@ function httpGet(url) {
|
|
|
402
177
|
});
|
|
403
178
|
}
|
|
404
179
|
|
|
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
180
|
async function callApi(path, params = {}) {
|
|
410
|
-
const
|
|
411
|
-
|
|
412
|
-
if (v !== undefined && v !== null) url.searchParams.set(k, String(v));
|
|
413
|
-
}
|
|
414
|
-
return httpGet(url.toString());
|
|
181
|
+
const qs = toSearchParams(params).toString();
|
|
182
|
+
return httpGet(`${API}${path}${qs ? `?${qs}` : ""}`);
|
|
415
183
|
}
|
|
416
184
|
|
|
417
185
|
// ---- collect: local credential store + scoped auth --------------------------
|
|
@@ -481,66 +249,11 @@ function collectApi(method, path, { token, apiKey, body } = {}) {
|
|
|
481
249
|
|
|
482
250
|
async function handleTool(name, args) {
|
|
483
251
|
switch (name) {
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
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 });
|
|
252
|
+
// --- read tools (read-tools.js) ---
|
|
253
|
+
case "list_layers": case "get_layer_schema": case "query_layer": case "nearby":
|
|
254
|
+
case "locate": case "list_categories": case "get_layer_detail": case "list_submissions": {
|
|
255
|
+
const req = readToolRequest(name, args);
|
|
256
|
+
return shapeReadResult(name, await callApi(req.path, req.params));
|
|
544
257
|
}
|
|
545
258
|
|
|
546
259
|
// --- collect (authoring) ---
|
|
@@ -581,11 +294,14 @@ async function handleTool(name, args) {
|
|
|
581
294
|
body: { status: args.status, reason: args.reason },
|
|
582
295
|
});
|
|
583
296
|
|
|
584
|
-
case "import_points":
|
|
585
|
-
|
|
297
|
+
case "import_points": {
|
|
298
|
+
const records = withClientIds(Array.isArray(args.records) ? args.records : [], args.client_id_field);
|
|
299
|
+
const res = await collectApi("POST", `/collections/${args.id}/import`, {
|
|
586
300
|
token: tokenFor(args.id, "admin"),
|
|
587
|
-
body: { records
|
|
301
|
+
body: { records, source: args.source, rights_confirmed: !!args.rights_confirmed },
|
|
588
302
|
});
|
|
303
|
+
return { summary: importSummary(res, records.filter((r) => r?.client_id === undefined).length), ...res };
|
|
304
|
+
}
|
|
589
305
|
|
|
590
306
|
case "edit_map": {
|
|
591
307
|
const { id, ...patch } = args;
|
|
@@ -602,6 +318,7 @@ async function handleTool(name, args) {
|
|
|
602
318
|
const schema_doc = { version: 1, geometry: args.geometry, fields: args.fields };
|
|
603
319
|
if (args.category) schema_doc.category = args.category;
|
|
604
320
|
if (args.basemap) schema_doc.basemap = args.basemap;
|
|
321
|
+
if (args.mode && args.mode !== "form") schema_doc.mode = args.mode;
|
|
605
322
|
const body = {
|
|
606
323
|
name: args.name, purpose: args.purpose, description: args.description,
|
|
607
324
|
license: args.license || "CC-BY-4.0", data_year: args.data_year,
|
|
@@ -624,7 +341,7 @@ async function handleTool(name, args) {
|
|
|
624
341
|
}
|
|
625
342
|
|
|
626
343
|
const server = new Server(
|
|
627
|
-
{ name: "bharatlas-mcp", version: "1.
|
|
344
|
+
{ name: "bharatlas-mcp", version: "1.4.0" },
|
|
628
345
|
{ capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS },
|
|
629
346
|
);
|
|
630
347
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bharatlas-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.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" },
|
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
"mcpName": "io.github.sathya-sankaran/bharatlas-mcp",
|
|
9
9
|
"type": "module",
|
|
10
10
|
"main": "index.js",
|
|
11
|
+
"scripts": {
|
|
12
|
+
"test": "node --test import-records.test.js",
|
|
13
|
+
"test:live": "node test.js"
|
|
14
|
+
},
|
|
11
15
|
"bin": {
|
|
12
16
|
"bharatlas-mcp": "index.js"
|
|
13
17
|
},
|
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
|
-
"
|
|
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.5.0",
|
|
6
29
|
"packages": [
|
|
7
30
|
{
|
|
8
31
|
"registryType": "npm",
|
|
9
32
|
"identifier": "bharatlas-mcp",
|
|
10
|
-
"version": "1.
|
|
11
|
-
"transport": {
|
|
33
|
+
"version": "1.5.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
|
}
|