@statsmcp/core 0.5.0 → 0.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/dist/index.d.ts +40 -3
- package/dist/index.js +408 -3
- package/dist/node.js +1 -1
- package/dist/{snapshot-BqwC4tjq.js → snapshot-CMstGbu-.js} +41 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -152,7 +152,7 @@ interface PxwebPreset {
|
|
|
152
152
|
* (the language is a parameter), use the API table ids as they are and ignore
|
|
153
153
|
* `database` and `tableIdFromHit`.
|
|
154
154
|
*/
|
|
155
|
-
api?: 'pxweb-v1' | 'pxweb-v2' | 'statbank-dk' | 'cbs-odata' | 'eurostat' | 'statcan-wds' | 'singstat' | 'cso-pxstat' | 'ine-es' | 'ine-pt' | 'insee' | 'ons' | 'statbel' | 'czso' | 'ibge' | 'osp' | 'sdmx';
|
|
155
|
+
api?: 'pxweb-v1' | 'pxweb-v2' | 'statbank-dk' | 'cbs-odata' | 'eurostat' | 'statcan-wds' | 'singstat' | 'cso-pxstat' | 'ine-es' | 'ine-pt' | 'insee' | 'ons' | 'statbel' | 'czso' | 'ibge' | 'bdl' | 'osp' | 'sdmx';
|
|
156
156
|
/** SDMX agency id, for example "ABS". Required when `api` is "sdmx". */
|
|
157
157
|
sdmxAgency?: string;
|
|
158
158
|
/**
|
|
@@ -195,8 +195,10 @@ interface PresetServerOptions {
|
|
|
195
195
|
userAgent?: string;
|
|
196
196
|
/** Crawled table lists, used when a source's live table list fails. */
|
|
197
197
|
tableSnapshots?: SnapshotReader;
|
|
198
|
+
/** API key for an office that takes one; BDL sends it as `X-ClientId`. */
|
|
199
|
+
clientId?: string;
|
|
198
200
|
}
|
|
199
|
-
export declare function createPresetClient(preset: PxwebPreset, options: Pick<PresetServerOptions, 'cache' | 'fetch' | 'tableSnapshots'> & {
|
|
201
|
+
export declare function createPresetClient(preset: PxwebPreset, options: Pick<PresetServerOptions, 'cache' | 'fetch' | 'tableSnapshots' | 'clientId'> & {
|
|
200
202
|
userAgent: string;
|
|
201
203
|
timeoutMs?: number;
|
|
202
204
|
}): PxwebClient;
|
|
@@ -394,6 +396,41 @@ interface IbgeClientOptions extends HttpOptions, TableListOptions {
|
|
|
394
396
|
* memory for an hour.
|
|
395
397
|
*/
|
|
396
398
|
export declare function createIbgeClient(options: IbgeClientOptions): Required<PxwebClient>;
|
|
399
|
+
interface BdlClientOptions extends HttpOptions, TableListOptions {
|
|
400
|
+
/** API root, for example "https://bdl.stat.gov.pl/api/v1". */
|
|
401
|
+
baseUrl: string;
|
|
402
|
+
/** Free BDL API key, sent as `X-ClientId`; it raises the request limits tenfold. */
|
|
403
|
+
clientId?: string;
|
|
404
|
+
/** Upper limit of cells in one data request. */
|
|
405
|
+
maxCells?: number;
|
|
406
|
+
/** Clock for search ranking; defaults to the system time. */
|
|
407
|
+
now?: () => Date;
|
|
408
|
+
}
|
|
409
|
+
/**
|
|
410
|
+
* Client for Statistics Poland (GUS), Local Data Bank (BDL) API, in Polish and English.
|
|
411
|
+
*
|
|
412
|
+
* - Table id: a BDL subgroup, the subject level that holds variables (for example "P2567").
|
|
413
|
+
* - Search: a local index over every subject. `subjects/search?name=%` matches all
|
|
414
|
+
* 2,700 subjects (28 pages of 100, the largest page size), which is far fewer calls
|
|
415
|
+
* than the K → G → P tree walk (about 300). Path is the subject's ancestors (domain,
|
|
416
|
+
* group); subjects under an "archival data" group are marked discontinued. The list
|
|
417
|
+
* has no years, so the docs have no `lastPeriod`.
|
|
418
|
+
* - Metadata: `subjects/{id}` (years, dimension names) and `variables?subject-id=…`
|
|
419
|
+
* (one call per 100 variables). A BDL variable is one series: its labels n1…n5 are
|
|
420
|
+
* the dimensions, named by the subject's `dimensions`. Each dimension becomes a
|
|
421
|
+
* variable `n1`…`n5` with ordinal value codes in API order (the same in both
|
|
422
|
+
* languages). `unit` offers Poland (eliminable, the default) and, when the series
|
|
423
|
+
* go down to level 2 or deeper, the 16 voivodeships. `year` is the subject's years.
|
|
424
|
+
* - Query: the selection picks the series whose labels match and the cell limit is
|
|
425
|
+
* checked on series × units × years. Data comes from `data/by-unit` (100 series per
|
|
426
|
+
* call for one unit) or `data/by-variable` (one series for Poland or all
|
|
427
|
+
* voivodeships per call), whichever needs fewer calls.
|
|
428
|
+
* - Limits: anonymous clients get 100 requests per 15 minutes; `clientId` raises it.
|
|
429
|
+
* HTTP 429 becomes a 503 error that says to try again later.
|
|
430
|
+
* - Caching: list pages, subjects and variables in the shared cache for a day, data
|
|
431
|
+
* for an hour; the parsed table in memory for an hour.
|
|
432
|
+
*/
|
|
433
|
+
export declare function createBdlClient(options: BdlClientOptions): Required<PxwebClient>;
|
|
397
434
|
interface OspClientOptions extends HttpOptions, TableListOptions {
|
|
398
435
|
/** SDMX-ML root, for example "https://osp-rs.stat.gov.lt/ords/ipospp/ospp/rest_xml". */
|
|
399
436
|
baseUrl: string;
|
|
@@ -595,4 +632,4 @@ interface PxwebV2ClientOptions extends HttpOptions, TableListOptions {
|
|
|
595
632
|
}
|
|
596
633
|
/** Client for the PxWeb API v2, with the same interface as the v1 client. */
|
|
597
634
|
export declare function createPxwebV2Client(options: PxwebV2ClientOptions): PxwebClient;
|
|
598
|
-
export { type ApiBaseUrl, type Cache, type CbsODataClientOptions, type CzsoClientOptions, type EurostatClientOptions, type FlatTable, type IbgeClientOptions, type IneEsClientOptions, type InePtClientOptions, type InseeClientOptions, type JsonStatDataset, type MemoryCacheOptions, type MultiServerEntry, type MultiServerOptions, type OnsClientOptions, type OspClientOptions, type PrebuiltSearchIndex, type PresetServerOptions, type PxstatClientOptions, type PxwebClient, type PxwebClientOptions, type PxwebPreset, type PxwebSelection, type PxwebV2ClientOptions, type QueryPlan, SNAPSHOT_VERSION, type SdmxClientOptions, type SearchAlias, type SearchHit, type SelectionInput, type SingstatClientOptions, type Snapshot, type SnapshotBucket, type SnapshotReader, type StatbankDkClientOptions, type StatbelClientOptions, type StatcanClientOptions, type TableDoc, type TableIndex, type TableIndexLoaderOptions, type TableIndexOptions, type TableIndexSearchOptions, type TableListOptions, type TableMetadata, type TableSearchHit, type TableSearchOptions, type TableVariable, type UrlSnapshotReaderOptions, bucketSnapshotReader, firstSnapshot, readSnapshot, snapshotKey, urlSnapshotReader, writeSnapshot };
|
|
635
|
+
export { type ApiBaseUrl, type BdlClientOptions, type Cache, type CbsODataClientOptions, type CzsoClientOptions, type EurostatClientOptions, type FlatTable, type IbgeClientOptions, type IneEsClientOptions, type InePtClientOptions, type InseeClientOptions, type JsonStatDataset, type MemoryCacheOptions, type MultiServerEntry, type MultiServerOptions, type OnsClientOptions, type OspClientOptions, type PrebuiltSearchIndex, type PresetServerOptions, type PxstatClientOptions, type PxwebClient, type PxwebClientOptions, type PxwebPreset, type PxwebSelection, type PxwebV2ClientOptions, type QueryPlan, SNAPSHOT_VERSION, type SdmxClientOptions, type SearchAlias, type SearchHit, type SelectionInput, type SingstatClientOptions, type Snapshot, type SnapshotBucket, type SnapshotReader, type StatbankDkClientOptions, type StatbelClientOptions, type StatcanClientOptions, type TableDoc, type TableIndex, type TableIndexLoaderOptions, type TableIndexOptions, type TableIndexSearchOptions, type TableListOptions, type TableMetadata, type TableSearchHit, type TableSearchOptions, type TableVariable, type UrlSnapshotReaderOptions, bucketSnapshotReader, firstSnapshot, readSnapshot, snapshotKey, urlSnapshotReader, writeSnapshot };
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { _ as startsWord, a as snapshotKey, c as tableDocSchema, d as buildSearchIndex, f as createTableIndex, g as normalize, h as searchTitles, i as readSnapshot, l as SEARCH_INDEX_VERSION, m as preferCrawled, n as bucketSnapshotReader, o as urlSnapshotReader, p as createTableIndexLoader, r as firstSnapshot, s as writeSnapshot, t as SNAPSHOT_VERSION, u as asPrebuiltIndex, v as rankSearchHits } from "./snapshot-
|
|
1
|
+
import { _ as startsWord, a as snapshotKey, c as tableDocSchema, d as buildSearchIndex, f as createTableIndex, g as normalize, h as searchTitles, i as readSnapshot, l as SEARCH_INDEX_VERSION, m as preferCrawled, n as bucketSnapshotReader, o as urlSnapshotReader, p as createTableIndexLoader, r as firstSnapshot, s as writeSnapshot, t as SNAPSHOT_VERSION, u as asPrebuiltIndex, v as rankSearchHits } from "./snapshot-CMstGbu-.js";
|
|
2
2
|
import { McpServer } from "@modelcontextprotocol/server";
|
|
3
3
|
import { z } from "zod";
|
|
4
4
|
// src/cache.ts
|
|
@@ -213,6 +213,404 @@ function createTextRequester(options) {
|
|
|
213
213
|
return result;
|
|
214
214
|
};
|
|
215
215
|
}
|
|
216
|
+
// src/bdl-client.ts
|
|
217
|
+
const TABLE_ID_PATTERN$10 = /^P\d{1,6}$/;
|
|
218
|
+
const DEFAULT_MAX_CELLS$6 = 5e3;
|
|
219
|
+
const MAX_CACHED_TABLES$5 = 8;
|
|
220
|
+
/** The API refuses a larger page size. */
|
|
221
|
+
const PAGE_SIZE = 100;
|
|
222
|
+
/** Parallel page requests; the anonymous limit is 5 requests per second. */
|
|
223
|
+
const PAGE_BATCH = 4;
|
|
224
|
+
const MAX_VARIABLE_PAGES = 20;
|
|
225
|
+
const VAR_IDS_PER_CALL = PAGE_SIZE;
|
|
226
|
+
/** Keeps one query well inside the anonymous limit of 100 requests per 15 minutes. */
|
|
227
|
+
const MAX_DATA_CALLS = 20;
|
|
228
|
+
const DIMENSION_FIELDS = [
|
|
229
|
+
"n1",
|
|
230
|
+
"n2",
|
|
231
|
+
"n3",
|
|
232
|
+
"n4",
|
|
233
|
+
"n5"
|
|
234
|
+
];
|
|
235
|
+
const UNIT_CODE = "unit";
|
|
236
|
+
const YEAR_CODE = "year";
|
|
237
|
+
const POLAND = "000000000000";
|
|
238
|
+
const COUNTRY_LEVEL$1 = 0;
|
|
239
|
+
const VOIVODESHIP_LEVEL = 2;
|
|
240
|
+
const VOIVODESHIPS = [
|
|
241
|
+
["030200000000", "Dolnośląskie"],
|
|
242
|
+
["040400000000", "Kujawsko-pomorskie"],
|
|
243
|
+
["060600000000", "Lubelskie"],
|
|
244
|
+
["020800000000", "Lubuskie"],
|
|
245
|
+
["051000000000", "Łódzkie"],
|
|
246
|
+
["011200000000", "Małopolskie"],
|
|
247
|
+
["071400000000", "Mazowieckie"],
|
|
248
|
+
["031600000000", "Opolskie"],
|
|
249
|
+
["061800000000", "Podkarpackie"],
|
|
250
|
+
["062000000000", "Podlaskie"],
|
|
251
|
+
["042200000000", "Pomorskie"],
|
|
252
|
+
["012400000000", "Śląskie"],
|
|
253
|
+
["052600000000", "Świętokrzyskie"],
|
|
254
|
+
["042800000000", "Warmińsko-mazurskie"],
|
|
255
|
+
["023000000000", "Wielkopolskie"],
|
|
256
|
+
["023200000000", "Zachodniopomorskie"]
|
|
257
|
+
];
|
|
258
|
+
/** Attributes "x", "X", "-" and "n": the value field holds 0, but there is no value. */
|
|
259
|
+
const MISSING_ATTRIBUTES = /* @__PURE__ */ new Set([
|
|
260
|
+
4,
|
|
261
|
+
14,
|
|
262
|
+
15,
|
|
263
|
+
50,
|
|
264
|
+
91
|
|
265
|
+
]);
|
|
266
|
+
const ARCHIVE_GROUP = /archival|archiwaln/i;
|
|
267
|
+
const LABELS = {
|
|
268
|
+
pl: {
|
|
269
|
+
unit: "Jednostka terytorialna",
|
|
270
|
+
year: "Rok",
|
|
271
|
+
measure: "Jednostka miary",
|
|
272
|
+
value: "Wartość",
|
|
273
|
+
poland: "Polska",
|
|
274
|
+
dimension: "Wymiar"
|
|
275
|
+
},
|
|
276
|
+
en: {
|
|
277
|
+
unit: "Territorial unit",
|
|
278
|
+
year: "Year",
|
|
279
|
+
measure: "Measure unit",
|
|
280
|
+
value: "Value",
|
|
281
|
+
poland: "Poland",
|
|
282
|
+
dimension: "Dimension"
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
const subjectListSchema = z.object({
|
|
286
|
+
totalRecords: z.number(),
|
|
287
|
+
results: z.array(z.object({
|
|
288
|
+
id: z.string(),
|
|
289
|
+
parentId: z.string().nullish(),
|
|
290
|
+
name: z.string(),
|
|
291
|
+
hasVariables: z.boolean()
|
|
292
|
+
}))
|
|
293
|
+
});
|
|
294
|
+
const subjectSchema = z.object({
|
|
295
|
+
name: z.string(),
|
|
296
|
+
years: z.array(z.number()).default([]),
|
|
297
|
+
dimensions: z.array(z.string()).default([])
|
|
298
|
+
});
|
|
299
|
+
const variablesSchema = z.object({
|
|
300
|
+
totalRecords: z.number(),
|
|
301
|
+
results: z.array(z.object({
|
|
302
|
+
id: z.number(),
|
|
303
|
+
n1: z.string().nullish(),
|
|
304
|
+
n2: z.string().nullish(),
|
|
305
|
+
n3: z.string().nullish(),
|
|
306
|
+
n4: z.string().nullish(),
|
|
307
|
+
n5: z.string().nullish(),
|
|
308
|
+
level: z.number(),
|
|
309
|
+
measureUnitName: z.string().nullish()
|
|
310
|
+
}))
|
|
311
|
+
});
|
|
312
|
+
const yearValuesSchema = z.array(z.object({
|
|
313
|
+
year: z.string(),
|
|
314
|
+
val: z.number().nullable(),
|
|
315
|
+
attrId: z.number()
|
|
316
|
+
}));
|
|
317
|
+
const dataByUnitSchema = z.object({ results: z.array(z.object({
|
|
318
|
+
id: z.number(),
|
|
319
|
+
values: yearValuesSchema
|
|
320
|
+
})) });
|
|
321
|
+
const dataByVariableSchema = z.object({ results: z.array(z.object({
|
|
322
|
+
id: z.string(),
|
|
323
|
+
values: yearValuesSchema
|
|
324
|
+
})) });
|
|
325
|
+
function labelsFor(lang) {
|
|
326
|
+
const labels = LABELS[lang];
|
|
327
|
+
if (!labels) throw new PxwebError(`Language "${lang}" is not supported.`, 400);
|
|
328
|
+
return labels;
|
|
329
|
+
}
|
|
330
|
+
function notFound$14(tableId) {
|
|
331
|
+
return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
|
|
332
|
+
}
|
|
333
|
+
/** The API's own error reason, from a body such as `{"errors":[{"errorReason":"…"}]}`. */
|
|
334
|
+
function upstreamReason(message) {
|
|
335
|
+
return /"errorReason"\s*:\s*"([^"]+)"/.exec(message)?.[1] ?? message.replace(/^.*?HTTP \d+:\s*/, "");
|
|
336
|
+
}
|
|
337
|
+
function upstreamError$3(err) {
|
|
338
|
+
if (!(err instanceof PxwebError)) return err;
|
|
339
|
+
if (err.status === 429) return new PxwebError("Statistics Poland (BDL) refused the request because its request limit for this server is reached. Try again in 15 minutes or later.", 503);
|
|
340
|
+
if (err.status === 401 || err.status === 403) return new PxwebError(`Statistics Poland (BDL) refused the API key of this server (HTTP ${err.status}). Check BDL_CLIENT_ID.`, 502);
|
|
341
|
+
if (err.status >= 500) return new PxwebError(`Statistics Poland (BDL) could not answer (HTTP ${err.status}). Try again later.`, 502);
|
|
342
|
+
return err;
|
|
343
|
+
}
|
|
344
|
+
async function inBatches(items, run) {
|
|
345
|
+
const results = [];
|
|
346
|
+
for (let start = 0; start < items.length; start += PAGE_BATCH) results.push(...await Promise.all(items.slice(start, start + PAGE_BATCH).map(run)));
|
|
347
|
+
return results;
|
|
348
|
+
}
|
|
349
|
+
function range(count) {
|
|
350
|
+
return Array.from({ length: count }, (_, index) => index);
|
|
351
|
+
}
|
|
352
|
+
function chunks(items, size) {
|
|
353
|
+
return range(Math.ceil(items.length / size)).map((index) => items.slice(index * size, (index + 1) * size));
|
|
354
|
+
}
|
|
355
|
+
function chosenCodes$6(variable, selection) {
|
|
356
|
+
if (!selection) return variable.code === UNIT_CODE ? [POLAND] : variable.values;
|
|
357
|
+
const { filter, values } = selection.selection;
|
|
358
|
+
if (filter === "all") return variable.values;
|
|
359
|
+
if (filter === "top") return variable.values.slice(-Math.max(1, Number(values[0]) || 1));
|
|
360
|
+
const unknown = values.filter((code) => !variable.values.includes(code));
|
|
361
|
+
if (unknown.length > 0) throw new PxwebError(`Unknown value "${unknown[0]}" for ${variable.code}. Check the value codes with get_table_metadata.`, 400);
|
|
362
|
+
return [...new Set(values)];
|
|
363
|
+
}
|
|
364
|
+
function valueLabel(variable, code) {
|
|
365
|
+
return variable.valueLabels[variable.values.indexOf(code)] ?? code;
|
|
366
|
+
}
|
|
367
|
+
function toValue(entry) {
|
|
368
|
+
return MISSING_ATTRIBUTES.has(entry.attrId) ? null : entry.val;
|
|
369
|
+
}
|
|
370
|
+
async function allPages(load, maxPages) {
|
|
371
|
+
const first = await load(0);
|
|
372
|
+
const pages = Math.ceil(first.totalRecords / PAGE_SIZE);
|
|
373
|
+
if (pages > maxPages) throw new PxwebError(`Statistics Poland (BDL) lists ${first.totalRecords} entries here, more than this server reads.`, 400);
|
|
374
|
+
return [first, ...await inBatches(range(pages).slice(1), load)];
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Client for Statistics Poland (GUS), Local Data Bank (BDL) API, in Polish and English.
|
|
378
|
+
*
|
|
379
|
+
* - Table id: a BDL subgroup, the subject level that holds variables (for example "P2567").
|
|
380
|
+
* - Search: a local index over every subject. `subjects/search?name=%` matches all
|
|
381
|
+
* 2,700 subjects (28 pages of 100, the largest page size), which is far fewer calls
|
|
382
|
+
* than the K → G → P tree walk (about 300). Path is the subject's ancestors (domain,
|
|
383
|
+
* group); subjects under an "archival data" group are marked discontinued. The list
|
|
384
|
+
* has no years, so the docs have no `lastPeriod`.
|
|
385
|
+
* - Metadata: `subjects/{id}` (years, dimension names) and `variables?subject-id=…`
|
|
386
|
+
* (one call per 100 variables). A BDL variable is one series: its labels n1…n5 are
|
|
387
|
+
* the dimensions, named by the subject's `dimensions`. Each dimension becomes a
|
|
388
|
+
* variable `n1`…`n5` with ordinal value codes in API order (the same in both
|
|
389
|
+
* languages). `unit` offers Poland (eliminable, the default) and, when the series
|
|
390
|
+
* go down to level 2 or deeper, the 16 voivodeships. `year` is the subject's years.
|
|
391
|
+
* - Query: the selection picks the series whose labels match and the cell limit is
|
|
392
|
+
* checked on series × units × years. Data comes from `data/by-unit` (100 series per
|
|
393
|
+
* call for one unit) or `data/by-variable` (one series for Poland or all
|
|
394
|
+
* voivodeships per call), whichever needs fewer calls.
|
|
395
|
+
* - Limits: anonymous clients get 100 requests per 15 minutes; `clientId` raises it.
|
|
396
|
+
* HTTP 429 becomes a 503 error that says to try again later.
|
|
397
|
+
* - Caching: list pages, subjects and variables in the shared cache for a day, data
|
|
398
|
+
* for an hour; the parsed table in memory for an hour.
|
|
399
|
+
*/
|
|
400
|
+
function createBdlClient(options) {
|
|
401
|
+
const root = options.baseUrl.replace(/\/+$/, "");
|
|
402
|
+
const maxCells = options.maxCells ?? DEFAULT_MAX_CELLS$6;
|
|
403
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
404
|
+
const request = createRequester(options);
|
|
405
|
+
const init = options.clientId ? {
|
|
406
|
+
method: "GET",
|
|
407
|
+
headers: { "X-ClientId": options.clientId }
|
|
408
|
+
} : { method: "GET" };
|
|
409
|
+
function get(path, params, lang, schema, ttlSeconds) {
|
|
410
|
+
const query = new URLSearchParams([
|
|
411
|
+
...params,
|
|
412
|
+
["lang", lang],
|
|
413
|
+
["format", "json"]
|
|
414
|
+
]);
|
|
415
|
+
const url = `${root}/${path}?${query}`;
|
|
416
|
+
return request(url, init, schema, (data) => data, ttlSeconds, url);
|
|
417
|
+
}
|
|
418
|
+
async function listTables(lang) {
|
|
419
|
+
labelsFor(lang);
|
|
420
|
+
const subjects = (await allPages((page) => get("subjects/search", [
|
|
421
|
+
["name", "%"],
|
|
422
|
+
["sort", "Id"],
|
|
423
|
+
["page-size", String(PAGE_SIZE)],
|
|
424
|
+
["page", String(page)]
|
|
425
|
+
], lang, subjectListSchema, METADATA_TTL_SECONDS), Number.POSITIVE_INFINITY).catch((err) => {
|
|
426
|
+
throw upstreamError$3(err);
|
|
427
|
+
})).flatMap((page) => page.results);
|
|
428
|
+
const byId = new Map(subjects.map((subject) => [subject.id, subject]));
|
|
429
|
+
function ancestors(parentId) {
|
|
430
|
+
const names = [];
|
|
431
|
+
const seen = /* @__PURE__ */ new Set();
|
|
432
|
+
for (let parent = parentId ? byId.get(parentId) : void 0; parent && !seen.has(parent.id); parent = parent.parentId ? byId.get(parent.parentId) : void 0) {
|
|
433
|
+
seen.add(parent.id);
|
|
434
|
+
names.unshift(parent.name.trim());
|
|
435
|
+
}
|
|
436
|
+
return names;
|
|
437
|
+
}
|
|
438
|
+
return subjects.filter((subject) => subject.hasVariables).map((subject) => {
|
|
439
|
+
const path = ancestors(subject.parentId);
|
|
440
|
+
return {
|
|
441
|
+
id: subject.id,
|
|
442
|
+
title: subject.name.trim(),
|
|
443
|
+
path,
|
|
444
|
+
...path.some((name) => ARCHIVE_GROUP.test(name)) && { discontinued: true }
|
|
445
|
+
};
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
const tableIndex = createTableIndexLoader(preferCrawled(listTables, options.crawledList), {
|
|
449
|
+
fallback: options.listFallback,
|
|
450
|
+
ttlSeconds: SEARCH_TTL_SECONDS,
|
|
451
|
+
currentYear: () => now().getUTCFullYear()
|
|
452
|
+
});
|
|
453
|
+
async function loadTable(lang, tableId) {
|
|
454
|
+
const labels = labelsFor(lang);
|
|
455
|
+
const variablePage = (page) => get("variables", [
|
|
456
|
+
["subject-id", tableId],
|
|
457
|
+
["page-size", String(PAGE_SIZE)],
|
|
458
|
+
["page", String(page)]
|
|
459
|
+
], lang, variablesSchema, METADATA_TTL_SECONDS);
|
|
460
|
+
const [subject, pages] = await Promise.all([get(`subjects/${tableId}`, [], lang, subjectSchema, METADATA_TTL_SECONDS), allPages(variablePage, MAX_VARIABLE_PAGES)]).catch((err) => {
|
|
461
|
+
if (err instanceof PxwebError && err.status === 404) throw notFound$14(tableId);
|
|
462
|
+
throw upstreamError$3(err);
|
|
463
|
+
});
|
|
464
|
+
const variables = pages.flatMap((page) => page.results);
|
|
465
|
+
if (variables.length === 0) throw notFound$14(tableId);
|
|
466
|
+
const dimensionCount = Math.max(...variables.map((variable) => DIMENSION_FIELDS.findLastIndex((field) => variable[field]) + 1));
|
|
467
|
+
const dimensions = DIMENSION_FIELDS.slice(0, dimensionCount).map((field, index) => {
|
|
468
|
+
const labelsInOrder = [...new Set(variables.map((variable) => variable[field]?.trim() ?? ""))];
|
|
469
|
+
return {
|
|
470
|
+
field,
|
|
471
|
+
codes: new Map(labelsInOrder.map((label, position) => [label, String(position + 1)])),
|
|
472
|
+
variable: {
|
|
473
|
+
code: field,
|
|
474
|
+
label: subject.dimensions[index]?.trim() || `${labels.dimension} ${index + 1}`,
|
|
475
|
+
values: labelsInOrder.map((_, position) => String(position + 1)),
|
|
476
|
+
valueLabels: labelsInOrder,
|
|
477
|
+
eliminable: false,
|
|
478
|
+
isTime: false
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
});
|
|
482
|
+
const deepest = Math.max(...variables.map((variable) => variable.level));
|
|
483
|
+
const units = [[POLAND, labels.poland], ...deepest >= VOIVODESHIP_LEVEL ? VOIVODESHIPS : []];
|
|
484
|
+
const years = subject.years.toSorted((a, b) => a - b).map(String);
|
|
485
|
+
const dimensionVariables = dimensions.map((dimension) => dimension.variable);
|
|
486
|
+
const unitVariable = {
|
|
487
|
+
code: UNIT_CODE,
|
|
488
|
+
label: labels.unit,
|
|
489
|
+
values: units.map(([id]) => id),
|
|
490
|
+
valueLabels: units.map(([, name]) => name),
|
|
491
|
+
eliminable: true,
|
|
492
|
+
isTime: false
|
|
493
|
+
};
|
|
494
|
+
const yearVariable = {
|
|
495
|
+
code: YEAR_CODE,
|
|
496
|
+
label: labels.year,
|
|
497
|
+
values: years,
|
|
498
|
+
valueLabels: years,
|
|
499
|
+
eliminable: false,
|
|
500
|
+
isTime: true
|
|
501
|
+
};
|
|
502
|
+
return {
|
|
503
|
+
metadata: {
|
|
504
|
+
title: subject.name.trim(),
|
|
505
|
+
variables: [
|
|
506
|
+
...dimensionVariables,
|
|
507
|
+
unitVariable,
|
|
508
|
+
yearVariable
|
|
509
|
+
]
|
|
510
|
+
},
|
|
511
|
+
dimensions: dimensionVariables,
|
|
512
|
+
units: unitVariable,
|
|
513
|
+
years: yearVariable,
|
|
514
|
+
series: variables.map((variable) => ({
|
|
515
|
+
id: variable.id,
|
|
516
|
+
codes: dimensions.map((dimension) => dimension.codes.get(variable[dimension.field]?.trim() ?? "") ?? ""),
|
|
517
|
+
measure: variable.measureUnitName?.trim() || null
|
|
518
|
+
}))
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
const tables = /* @__PURE__ */ new Map();
|
|
522
|
+
async function cachedTable(lang, tableId) {
|
|
523
|
+
labelsFor(lang);
|
|
524
|
+
if (!TABLE_ID_PATTERN$10.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it, for example "P2567".`, 400);
|
|
525
|
+
const key = `${lang}:${tableId}`;
|
|
526
|
+
const cached = tables.get(key);
|
|
527
|
+
if (cached && cached.expires > Date.now()) return cached.table;
|
|
528
|
+
const table = await loadTable(lang, tableId);
|
|
529
|
+
tables.delete(key);
|
|
530
|
+
tables.set(key, {
|
|
531
|
+
expires: Date.now() + DATA_TTL_SECONDS * 1e3,
|
|
532
|
+
table
|
|
533
|
+
});
|
|
534
|
+
const oldest = tables.keys().next().value;
|
|
535
|
+
if (tables.size > MAX_CACHED_TABLES$5 && oldest !== void 0) tables.delete(oldest);
|
|
536
|
+
return table;
|
|
537
|
+
}
|
|
538
|
+
async function fetchCells(lang, series, units, yearParams) {
|
|
539
|
+
const levels = [...units.includes(POLAND) ? [COUNTRY_LEVEL$1] : [], ...units.some((unit) => unit !== POLAND) ? [VOIVODESHIP_LEVEL] : []];
|
|
540
|
+
const byUnitCalls = units.length * Math.ceil(series.length / VAR_IDS_PER_CALL);
|
|
541
|
+
const byVariableCalls = series.length * levels.length;
|
|
542
|
+
if (Math.min(byUnitCalls, byVariableCalls) > MAX_DATA_CALLS) throw new PxwebError(`This selection needs more than ${MAX_DATA_CALLS} requests to Statistics Poland. Select fewer units or values.`, 400);
|
|
543
|
+
if (byUnitCalls <= byVariableCalls) return (await inBatches(units.flatMap((unit) => chunks(series, VAR_IDS_PER_CALL).map((chunk) => ({
|
|
544
|
+
unit,
|
|
545
|
+
chunk
|
|
546
|
+
}))), ({ unit, chunk }) => get(`data/by-unit/${unit}`, [
|
|
547
|
+
...chunk.map((entry) => ["var-id", String(entry.id)]),
|
|
548
|
+
...yearParams,
|
|
549
|
+
["page-size", String(PAGE_SIZE)]
|
|
550
|
+
], lang, dataByUnitSchema, DATA_TTL_SECONDS).then((data) => data.results.map((result) => ({
|
|
551
|
+
unit,
|
|
552
|
+
series: result.id,
|
|
553
|
+
values: result.values
|
|
554
|
+
}))))).flat();
|
|
555
|
+
return (await inBatches(series.flatMap((entry) => levels.map((level) => ({
|
|
556
|
+
entry,
|
|
557
|
+
level
|
|
558
|
+
}))), ({ entry, level }) => get(`data/by-variable/${entry.id}`, [
|
|
559
|
+
["unit-level", String(level)],
|
|
560
|
+
...yearParams,
|
|
561
|
+
["page-size", String(PAGE_SIZE)]
|
|
562
|
+
], lang, dataByVariableSchema, DATA_TTL_SECONDS).then((data) => data.results.map((result) => ({
|
|
563
|
+
unit: result.id,
|
|
564
|
+
series: entry.id,
|
|
565
|
+
values: result.values
|
|
566
|
+
}))))).flat();
|
|
567
|
+
}
|
|
568
|
+
return {
|
|
569
|
+
listTables,
|
|
570
|
+
async search(lang, query, searchOptions) {
|
|
571
|
+
labelsFor(lang);
|
|
572
|
+
return (await tableIndex(lang)).search(query, searchOptions);
|
|
573
|
+
},
|
|
574
|
+
async getMetadata(lang, tableId) {
|
|
575
|
+
return (await cachedTable(lang, tableId)).metadata;
|
|
576
|
+
},
|
|
577
|
+
async query(lang, tableId, selections) {
|
|
578
|
+
const labels = labelsFor(lang);
|
|
579
|
+
const table = await cachedTable(lang, tableId);
|
|
580
|
+
const byCode = new Map(selections.map((selection) => [selection.code, selection]));
|
|
581
|
+
const pick = (variable) => chosenCodes$6(variable, byCode.get(variable.code));
|
|
582
|
+
const chosen = table.dimensions.map(pick);
|
|
583
|
+
const units = pick(table.units);
|
|
584
|
+
const years = pick(table.years);
|
|
585
|
+
const series = table.series.filter((entry) => entry.codes.every((code, index) => chosen[index]?.includes(code)));
|
|
586
|
+
if (series.length === 0) throw new PxwebError("No series of this table has that combination of values. Choose other values with get_table_metadata.", 400);
|
|
587
|
+
const cells = series.length * units.length * years.length;
|
|
588
|
+
if (cells > maxCells) throw new PxwebError(`The query could return ${cells} cells, above the limit of ${maxCells}. Select fewer values.`, 400);
|
|
589
|
+
const yearParams = years.map((year) => ["year", year]);
|
|
590
|
+
const cellsByKey = new Map((await fetchCells(lang, series, units, years.length === table.years.values.length ? [] : yearParams).catch((err) => {
|
|
591
|
+
if (err instanceof PxwebError && (err.status === 400 || err.status === 412)) throw new PxwebError(`Statistics Poland (BDL) refused this selection: ${upstreamReason(err.message)}. Check the value codes with get_table_metadata.`, 400);
|
|
592
|
+
throw upstreamError$3(err);
|
|
593
|
+
})).map((cell) => [`${cell.unit}|${cell.series}`, cell.values]));
|
|
594
|
+
return {
|
|
595
|
+
label: table.metadata.title,
|
|
596
|
+
columns: [
|
|
597
|
+
labels.unit,
|
|
598
|
+
...table.dimensions.map((dimension) => dimension.label),
|
|
599
|
+
labels.year,
|
|
600
|
+
labels.measure,
|
|
601
|
+
labels.value
|
|
602
|
+
],
|
|
603
|
+
rows: units.flatMap((unit) => series.flatMap((entry) => (cellsByKey.get(`${unit}|${entry.id}`) ?? []).map((value) => [
|
|
604
|
+
valueLabel(table.units, unit),
|
|
605
|
+
...table.dimensions.map((dimension, index) => valueLabel(dimension, entry.codes[index] ?? "")),
|
|
606
|
+
value.year,
|
|
607
|
+
entry.measure,
|
|
608
|
+
toValue(value)
|
|
609
|
+
])))
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}
|
|
216
614
|
// src/cbs-odata-client.ts
|
|
217
615
|
const TABLE_ID_PATTERN$9 = /^[A-Za-z0-9]+$/;
|
|
218
616
|
const NOT_FOUND_STATUSES$4 = /* @__PURE__ */ new Set([400, 404]);
|
|
@@ -5410,7 +5808,7 @@ function snapshotTableList(preset, tableSnapshots) {
|
|
|
5410
5808
|
};
|
|
5411
5809
|
}
|
|
5412
5810
|
function createPresetClient(preset, options) {
|
|
5413
|
-
const { tableSnapshots, ...http } = options;
|
|
5811
|
+
const { tableSnapshots, clientId, ...http } = options;
|
|
5414
5812
|
const api = preset.api ?? "pxweb-v1";
|
|
5415
5813
|
if (api === "pxweb-v1") return createPxwebClient({
|
|
5416
5814
|
...http,
|
|
@@ -5479,6 +5877,12 @@ function createPresetClient(preset, options) {
|
|
|
5479
5877
|
maxCells: preset.maxCells,
|
|
5480
5878
|
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5481
5879
|
});
|
|
5880
|
+
if (api === "bdl") return createBdlClient({
|
|
5881
|
+
...indexed,
|
|
5882
|
+
maxCells: preset.maxCells,
|
|
5883
|
+
...clientId && { clientId },
|
|
5884
|
+
...tableSnapshots && { crawledList: async (lang) => (await tableSnapshots(preset.name, lang))?.docs }
|
|
5885
|
+
});
|
|
5482
5886
|
if (api === "osp") return createOspClient({
|
|
5483
5887
|
...indexed,
|
|
5484
5888
|
maxCells: preset.maxCells,
|
|
@@ -5499,6 +5903,7 @@ function createPresetServer(preset, options = {}) {
|
|
|
5499
5903
|
cache: options.cache,
|
|
5500
5904
|
fetch: options.fetch,
|
|
5501
5905
|
tableSnapshots: options.tableSnapshots,
|
|
5906
|
+
...options.clientId && { clientId: options.clientId },
|
|
5502
5907
|
userAgent: options.userAgent ?? `${preset.name}-mcp/${preset.version}`
|
|
5503
5908
|
}));
|
|
5504
5909
|
}
|
|
@@ -5620,4 +6025,4 @@ function createMultiServer(entries, options) {
|
|
|
5620
6025
|
});
|
|
5621
6026
|
return server;
|
|
5622
6027
|
}
|
|
5623
|
-
export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SEARCH_INDEX_VERSION, SNAPSHOT_VERSION, asPrebuiltIndex, bucketSnapshotReader, buildSearchIndex, createCbsODataClient, createCzsoClient, createEurostatClient, createIbgeClient, createIneEsClient, createInePtClient, createInseeClient, createMemoryCache, createMultiServer, createOnsClient, createOspClient, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatbelClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, onsTableUrl, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
|
|
6028
|
+
export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SEARCH_INDEX_VERSION, SNAPSHOT_VERSION, asPrebuiltIndex, bucketSnapshotReader, buildSearchIndex, createBdlClient, createCbsODataClient, createCzsoClient, createEurostatClient, createIbgeClient, createIneEsClient, createInePtClient, createInseeClient, createMemoryCache, createMultiServer, createOnsClient, createOspClient, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatbelClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, onsTableUrl, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
|
package/dist/node.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as snapshotKey, i as readSnapshot, o as urlSnapshotReader, r as firstSnapshot } from "./snapshot-
|
|
1
|
+
import { a as snapshotKey, i as readSnapshot, o as urlSnapshotReader, r as firstSnapshot } from "./snapshot-CMstGbu-.js";
|
|
2
2
|
import { readFile } from "node:fs/promises";
|
|
3
3
|
// src/node.ts
|
|
4
4
|
const DEFAULT_INDEX_URL = "https://statsmcp.dev";
|
|
@@ -209,6 +209,47 @@ const STOP_WORDS = {
|
|
|
209
209
|
"pa",
|
|
210
210
|
"til"
|
|
211
211
|
],
|
|
212
|
+
es: [
|
|
213
|
+
"al",
|
|
214
|
+
"con",
|
|
215
|
+
"de",
|
|
216
|
+
"del",
|
|
217
|
+
"el",
|
|
218
|
+
"en",
|
|
219
|
+
"la",
|
|
220
|
+
"las",
|
|
221
|
+
"los",
|
|
222
|
+
"para",
|
|
223
|
+
"por",
|
|
224
|
+
"segun",
|
|
225
|
+
"un",
|
|
226
|
+
"una"
|
|
227
|
+
],
|
|
228
|
+
pt: [
|
|
229
|
+
"ao",
|
|
230
|
+
"aos",
|
|
231
|
+
"as",
|
|
232
|
+
"com",
|
|
233
|
+
"da",
|
|
234
|
+
"das",
|
|
235
|
+
"de",
|
|
236
|
+
"do",
|
|
237
|
+
"dos",
|
|
238
|
+
"em",
|
|
239
|
+
"na",
|
|
240
|
+
"nas",
|
|
241
|
+
"no",
|
|
242
|
+
"nos",
|
|
243
|
+
"os",
|
|
244
|
+
"ou",
|
|
245
|
+
"pela",
|
|
246
|
+
"pelas",
|
|
247
|
+
"pelo",
|
|
248
|
+
"pelos",
|
|
249
|
+
"por",
|
|
250
|
+
"um",
|
|
251
|
+
"uma"
|
|
252
|
+
],
|
|
212
253
|
sl: [
|
|
213
254
|
"in",
|
|
214
255
|
"na",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@statsmcp/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "MCP server toolkit for statistics APIs: PxWeb v1 and v2, StatBank Denmark, CBS OData, PxStat, SDMX, Eurostat, Statistics Canada and SingStat",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Tadej Polajnar",
|