bharatlas-mcp 1.4.0 → 1.6.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/import-records.js +36 -0
- package/index.js +49 -47
- package/package.json +5 -1
- package/read-tools.js +2 -1
- package/server.json +2 -2
|
@@ -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
|
+
}
|
package/index.js
CHANGED
|
@@ -6,11 +6,14 @@ import {
|
|
|
6
6
|
CallToolRequestSchema,
|
|
7
7
|
ListToolsRequestSchema,
|
|
8
8
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
9
|
-
import
|
|
10
|
-
import { readFileSync, writeFileSync, existsSync } from "node:fs";
|
|
9
|
+
import { readFileSync, writeFileSync, existsSync, chmodSync } from "node:fs";
|
|
11
10
|
import { homedir } from "node:os";
|
|
12
11
|
import { join } from "node:path";
|
|
13
12
|
import { INSTRUCTIONS_CORE, READ_TOOLS, readToolRequest, shapeReadResult, toSearchParams } from "./read-tools.js";
|
|
13
|
+
import { withClientIds, importSummary } from "./import-records.js";
|
|
14
|
+
|
|
15
|
+
/** One version for the server and its user agent; bump with every release (version.test.js). */
|
|
16
|
+
const VERSION = "1.6.0";
|
|
14
17
|
|
|
15
18
|
const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
|
|
16
19
|
|
|
@@ -93,14 +96,20 @@ const TOOLS = [
|
|
|
93
96
|
name: "import_points",
|
|
94
97
|
description:
|
|
95
98
|
"Bulk-import points you already hold into a collect map (needs the admin link). NOT for synthetic data. " +
|
|
96
|
-
"Requires a named source + rights confirmation; each row lands with that source as its provenance."
|
|
99
|
+
"Requires a named source + rights confirmation; each row lands with that source as its provenance. " +
|
|
100
|
+
"Re-running is safe for rows with a client id (the row's own stable id, unique within the map, up to 128 characters): " +
|
|
101
|
+
"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. " +
|
|
102
|
+
"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. " +
|
|
103
|
+
"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`). " +
|
|
104
|
+
"Up to 5000 records per call.",
|
|
97
105
|
inputSchema: {
|
|
98
106
|
type: "object",
|
|
99
107
|
properties: {
|
|
100
108
|
id: { type: "string" },
|
|
101
|
-
records: { type: "array", items: { type: "object" }, description: "GeoJSON-like {geometry, properties}" },
|
|
109
|
+
records: { type: "array", items: { type: "object" }, description: "GeoJSON-like {geometry, properties}, optionally with client_id" },
|
|
102
110
|
source: { type: "string" },
|
|
103
111
|
rights_confirmed: { type: "boolean", description: "you have the right to publish this under the map's licence" },
|
|
112
|
+
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" },
|
|
104
113
|
},
|
|
105
114
|
required: ["id", "records", "source", "rights_confirmed"],
|
|
106
115
|
},
|
|
@@ -153,26 +162,30 @@ const TOOLS = [
|
|
|
153
162
|
},
|
|
154
163
|
];
|
|
155
164
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
165
|
+
// One HTTP helper for the read API and collect. fetch follows redirects and
|
|
166
|
+
// times out; a reply that is not JSON becomes a rejected promise (the old
|
|
167
|
+
// https.get helper threw inside the 'end' callback and crashed the server).
|
|
168
|
+
// The API counts MCP use per layer by this header (web/functions/lib/usage.ts); the
|
|
169
|
+
// smoke test sends "bharatlas-mcp-test" so its calls are not counted.
|
|
170
|
+
const USER_AGENT = process.env.BHARATLAS_MCP_UA || `bharatlas-mcp/${VERSION}`;
|
|
171
|
+
|
|
172
|
+
async function request(method, url, { headers = {}, body } = {}) {
|
|
173
|
+
const init = { method, headers: { "user-agent": USER_AGENT, ...headers }, signal: AbortSignal.timeout(30_000) };
|
|
174
|
+
if (body !== undefined) {
|
|
175
|
+
init.body = JSON.stringify(body);
|
|
176
|
+
init.headers["content-type"] = "application/json";
|
|
177
|
+
}
|
|
178
|
+
const res = await fetch(url, init);
|
|
179
|
+
const text = await res.text();
|
|
180
|
+
let parsed;
|
|
181
|
+
try { parsed = text ? JSON.parse(text) : {}; } catch { parsed = { raw: text }; }
|
|
182
|
+
if (!res.ok) throw new Error(parsed.error || `HTTP ${res.status}: ${text.slice(0, 200)}`);
|
|
183
|
+
return parsed;
|
|
171
184
|
}
|
|
172
185
|
|
|
173
186
|
async function callApi(path, params = {}) {
|
|
174
187
|
const qs = toSearchParams(params).toString();
|
|
175
|
-
return
|
|
188
|
+
return request("GET", `${API}${path}${qs ? `?${qs}` : ""}`);
|
|
176
189
|
}
|
|
177
190
|
|
|
178
191
|
// ---- collect: local credential store + scoped auth --------------------------
|
|
@@ -185,7 +198,13 @@ function loadStore() {
|
|
|
185
198
|
try { return existsSync(COLLECT_STORE) ? JSON.parse(readFileSync(COLLECT_STORE, "utf8")) : { maps: {} }; }
|
|
186
199
|
catch { return { maps: {} }; }
|
|
187
200
|
}
|
|
188
|
-
|
|
201
|
+
// The store holds share-link tokens (admin ones included): owner-only.
|
|
202
|
+
function saveStore(s) {
|
|
203
|
+
try {
|
|
204
|
+
writeFileSync(COLLECT_STORE, JSON.stringify(s, null, 2), { mode: 0o600 });
|
|
205
|
+
chmodSync(COLLECT_STORE, 0o600); // also tighten a file created before this
|
|
206
|
+
} catch { /* best effort */ }
|
|
207
|
+
}
|
|
189
208
|
function rememberMap(id, entry) { const s = loadStore(); s.maps[id] = { ...s.maps[id], ...entry }; saveStore(s); }
|
|
190
209
|
function mapEntry(id) {
|
|
191
210
|
const m = loadStore().maps[id];
|
|
@@ -212,32 +231,12 @@ function parseShareLink(link) {
|
|
|
212
231
|
return { id, token, scope, link: u.toString() };
|
|
213
232
|
}
|
|
214
233
|
|
|
215
|
-
// ---- collect: HTTP (GET/POST/PATCH with auth headers)
|
|
216
|
-
function httpReq(method, urlStr, { headers = {}, body } = {}) {
|
|
217
|
-
return new Promise((resolve, reject) => {
|
|
218
|
-
const data = body !== undefined ? JSON.stringify(body) : undefined;
|
|
219
|
-
const opts = { method, headers: { ...headers } };
|
|
220
|
-
if (data) opts.headers["content-type"] = "application/json";
|
|
221
|
-
const req = https.request(new URL(urlStr), opts, (res) => {
|
|
222
|
-
let buf = "";
|
|
223
|
-
res.on("data", (c) => (buf += c));
|
|
224
|
-
res.on("end", () => {
|
|
225
|
-
let parsed;
|
|
226
|
-
try { parsed = buf ? JSON.parse(buf) : {}; } catch { parsed = { raw: buf }; }
|
|
227
|
-
if (res.statusCode >= 400) reject(new Error(parsed.error || `HTTP ${res.statusCode}: ${buf.slice(0, 200)}`));
|
|
228
|
-
else resolve(parsed);
|
|
229
|
-
});
|
|
230
|
-
});
|
|
231
|
-
req.on("error", reject);
|
|
232
|
-
if (data) req.write(data);
|
|
233
|
-
req.end();
|
|
234
|
-
});
|
|
235
|
-
}
|
|
234
|
+
// ---- collect: HTTP (GET/POST/PATCH with auth headers): request() above ------
|
|
236
235
|
function collectApi(method, path, { token, apiKey, body } = {}) {
|
|
237
236
|
const headers = {};
|
|
238
237
|
if (token) headers.authorization = `Bearer ${token}`;
|
|
239
238
|
if (apiKey) headers["x-api-key"] = apiKey;
|
|
240
|
-
return
|
|
239
|
+
return request(method, COLLECT_API + path, { headers, body });
|
|
241
240
|
}
|
|
242
241
|
|
|
243
242
|
async function handleTool(name, args) {
|
|
@@ -287,11 +286,14 @@ async function handleTool(name, args) {
|
|
|
287
286
|
body: { status: args.status, reason: args.reason },
|
|
288
287
|
});
|
|
289
288
|
|
|
290
|
-
case "import_points":
|
|
291
|
-
|
|
289
|
+
case "import_points": {
|
|
290
|
+
const records = withClientIds(Array.isArray(args.records) ? args.records : [], args.client_id_field);
|
|
291
|
+
const res = await collectApi("POST", `/collections/${args.id}/import`, {
|
|
292
292
|
token: tokenFor(args.id, "admin"),
|
|
293
|
-
body: { records
|
|
293
|
+
body: { records, source: args.source, rights_confirmed: !!args.rights_confirmed },
|
|
294
294
|
});
|
|
295
|
+
return { summary: importSummary(res, records.filter((r) => r?.client_id === undefined).length), ...res };
|
|
296
|
+
}
|
|
295
297
|
|
|
296
298
|
case "edit_map": {
|
|
297
299
|
const { id, ...patch } = args;
|
|
@@ -331,7 +333,7 @@ async function handleTool(name, args) {
|
|
|
331
333
|
}
|
|
332
334
|
|
|
333
335
|
const server = new Server(
|
|
334
|
-
{ name: "bharatlas-mcp", version:
|
|
336
|
+
{ name: "bharatlas-mcp", version: VERSION },
|
|
335
337
|
{ capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS },
|
|
336
338
|
);
|
|
337
339
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bharatlas-mcp",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.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 read-tools.test.js version.test.js",
|
|
13
|
+
"test:live": "node test.js"
|
|
14
|
+
},
|
|
11
15
|
"bin": {
|
|
12
16
|
"bharatlas-mcp": "index.js"
|
|
13
17
|
},
|
package/read-tools.js
CHANGED
|
@@ -19,7 +19,7 @@ export const INSTRUCTIONS_CORE = `Workflow patterns:
|
|
|
19
19
|
- **Community layers**: list_submissions returns user-contributed datasets. These work with query_layer and get_layer_schema exactly like curated layers.
|
|
20
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
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.
|
|
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. A layer whose answer has "non_commercial": true is for non-commercial use only: say so whenever you use or recommend it, quote its "licence_notice", and never suggest it for a product, a client or paid work.
|
|
23
23
|
|
|
24
24
|
Source preference (multiple layers often cover the same level):
|
|
25
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.
|
|
@@ -332,6 +332,7 @@ export function shapeReadResult(name, result) {
|
|
|
332
332
|
data: result.data.map((l) => ({
|
|
333
333
|
id: l.id, level: l.level, source: l.source, category: l.category,
|
|
334
334
|
rows: l.rows, licence: l.licence, notes: l.notes,
|
|
335
|
+
...(l.non_commercial ? { non_commercial: true, licence_notice: l.licence_notice } : {}),
|
|
335
336
|
})),
|
|
336
337
|
};
|
|
337
338
|
}
|
package/server.json
CHANGED