bharatlas-mcp 1.5.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/index.js CHANGED
@@ -6,13 +6,15 @@ import {
6
6
  CallToolRequestSchema,
7
7
  ListToolsRequestSchema,
8
8
  } from "@modelcontextprotocol/sdk/types.js";
9
- import https from "node:https";
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";
14
13
  import { withClientIds, importSummary } from "./import-records.js";
15
14
 
15
+ /** One version for the server and its user agent; bump with every release (version.test.js). */
16
+ const VERSION = "1.6.0";
17
+
16
18
  const API = process.env.BHARATLAS_API || "https://bharatlas.com/api/v1";
17
19
 
18
20
  // collect (write side): authoring over the collect REST API. The read tools
@@ -160,26 +162,30 @@ const TOOLS = [
160
162
  },
161
163
  ];
162
164
 
163
- function httpGet(url) {
164
- return new Promise((resolve, reject) => {
165
- https.get(url, (res) => {
166
- if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
167
- return httpGet(res.headers.location).then(resolve, reject);
168
- }
169
- let body = "";
170
- res.on("data", (chunk) => (body += chunk));
171
- res.on("end", () => {
172
- if (res.statusCode >= 400) reject(new Error(`API ${res.statusCode}: ${body.slice(0, 200)}`));
173
- else resolve(JSON.parse(body));
174
- });
175
- res.on("error", reject);
176
- }).on("error", reject);
177
- });
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;
178
184
  }
179
185
 
180
186
  async function callApi(path, params = {}) {
181
187
  const qs = toSearchParams(params).toString();
182
- return httpGet(`${API}${path}${qs ? `?${qs}` : ""}`);
188
+ return request("GET", `${API}${path}${qs ? `?${qs}` : ""}`);
183
189
  }
184
190
 
185
191
  // ---- collect: local credential store + scoped auth --------------------------
@@ -192,7 +198,13 @@ function loadStore() {
192
198
  try { return existsSync(COLLECT_STORE) ? JSON.parse(readFileSync(COLLECT_STORE, "utf8")) : { maps: {} }; }
193
199
  catch { return { maps: {} }; }
194
200
  }
195
- function saveStore(s) { try { writeFileSync(COLLECT_STORE, JSON.stringify(s, null, 2)); } catch { /* best effort */ } }
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
+ }
196
208
  function rememberMap(id, entry) { const s = loadStore(); s.maps[id] = { ...s.maps[id], ...entry }; saveStore(s); }
197
209
  function mapEntry(id) {
198
210
  const m = loadStore().maps[id];
@@ -219,32 +231,12 @@ function parseShareLink(link) {
219
231
  return { id, token, scope, link: u.toString() };
220
232
  }
221
233
 
222
- // ---- collect: HTTP (GET/POST/PATCH with auth headers) -----------------------
223
- function httpReq(method, urlStr, { headers = {}, body } = {}) {
224
- return new Promise((resolve, reject) => {
225
- const data = body !== undefined ? JSON.stringify(body) : undefined;
226
- const opts = { method, headers: { ...headers } };
227
- if (data) opts.headers["content-type"] = "application/json";
228
- const req = https.request(new URL(urlStr), opts, (res) => {
229
- let buf = "";
230
- res.on("data", (c) => (buf += c));
231
- res.on("end", () => {
232
- let parsed;
233
- try { parsed = buf ? JSON.parse(buf) : {}; } catch { parsed = { raw: buf }; }
234
- if (res.statusCode >= 400) reject(new Error(parsed.error || `HTTP ${res.statusCode}: ${buf.slice(0, 200)}`));
235
- else resolve(parsed);
236
- });
237
- });
238
- req.on("error", reject);
239
- if (data) req.write(data);
240
- req.end();
241
- });
242
- }
234
+ // ---- collect: HTTP (GET/POST/PATCH with auth headers): request() above ------
243
235
  function collectApi(method, path, { token, apiKey, body } = {}) {
244
236
  const headers = {};
245
237
  if (token) headers.authorization = `Bearer ${token}`;
246
238
  if (apiKey) headers["x-api-key"] = apiKey;
247
- return httpReq(method, COLLECT_API + path, { headers, body });
239
+ return request(method, COLLECT_API + path, { headers, body });
248
240
  }
249
241
 
250
242
  async function handleTool(name, args) {
@@ -341,7 +333,7 @@ async function handleTool(name, args) {
341
333
  }
342
334
 
343
335
  const server = new Server(
344
- { name: "bharatlas-mcp", version: "1.4.0" },
336
+ { name: "bharatlas-mcp", version: VERSION },
345
337
  { capabilities: { tools: {} }, instructions: SERVER_INSTRUCTIONS },
346
338
  );
347
339
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bharatlas-mcp",
3
- "version": "1.5.0",
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" },
@@ -9,7 +9,7 @@
9
9
  "type": "module",
10
10
  "main": "index.js",
11
11
  "scripts": {
12
- "test": "node --test import-records.test.js",
12
+ "test": "node --test import-records.test.js read-tools.test.js version.test.js",
13
13
  "test:live": "node test.js"
14
14
  },
15
15
  "bin": {
package/read-tools.js CHANGED
@@ -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
@@ -25,12 +25,12 @@
25
25
  ]
26
26
  }
27
27
  ],
28
- "version": "1.5.0",
28
+ "version": "1.6.0",
29
29
  "packages": [
30
30
  {
31
31
  "registryType": "npm",
32
32
  "identifier": "bharatlas-mcp",
33
- "version": "1.5.0",
33
+ "version": "1.6.0",
34
34
  "transport": {
35
35
  "type": "stdio"
36
36
  }
@@ -1,43 +0,0 @@
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
- });