@statsmcp/core 0.3.0 → 0.4.1

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 CHANGED
@@ -80,6 +80,7 @@ interface TableVariable {
80
80
  valueLabels: string[];
81
81
  eliminable: boolean;
82
82
  isTime: boolean;
83
+ periodsIncomplete?: boolean;
83
84
  }
84
85
  interface TableMetadata {
85
86
  title: string;
@@ -321,6 +322,18 @@ interface SdmxClientOptions extends HttpOptions, TableListOptions {
321
322
  * a local index over the dataflow list.
322
323
  */
323
324
  export declare function createSdmxClient(options: SdmxClientOptions): PxwebClient;
325
+ interface MultiServerEntry {
326
+ code: string;
327
+ preset: PxwebPreset;
328
+ /** Called at most once, when a tool call first uses this country. */
329
+ client: () => PxwebClient;
330
+ }
331
+ interface MultiServerOptions {
332
+ name: string;
333
+ title: string;
334
+ version: string;
335
+ }
336
+ export declare function createMultiServer(entries: readonly MultiServerEntry[], options: MultiServerOptions): McpServer;
324
337
  interface CbsODataClientOptions extends HttpOptions, TableListOptions {
325
338
  /** Root of the CBS open data service, for example "https://opendata.cbs.nl". */
326
339
  baseUrl: string;
@@ -361,4 +374,4 @@ interface PxwebV2ClientOptions extends HttpOptions, TableListOptions {
361
374
  }
362
375
  /** Client for the PxWeb API v2, with the same interface as the v1 client. */
363
376
  export declare function createPxwebV2Client(options: PxwebV2ClientOptions): PxwebClient;
364
- export { type ApiBaseUrl, type Cache, type CbsODataClientOptions, type EurostatClientOptions, type FlatTable, type JsonStatDataset, type MemoryCacheOptions, 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 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 };
377
+ export { type ApiBaseUrl, type Cache, type CbsODataClientOptions, type EurostatClientOptions, type FlatTable, type JsonStatDataset, type MemoryCacheOptions, type MultiServerEntry, type MultiServerOptions, 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 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
@@ -667,6 +667,18 @@ const DEFAULT_DATASETS_URL = "https://datasets.cbs.nl/odata/v1/CBS";
667
667
  function isNotFound(err) {
668
668
  return err instanceof PxwebError && NOT_FOUND_STATUSES$4.has(err.status);
669
669
  }
670
+ function isTransient(err) {
671
+ if (!(err instanceof PxwebError)) return true;
672
+ return err.status === 429 || err.status >= 500;
673
+ }
674
+ function sameOriginLink(next, current) {
675
+ if (!next) return void 0;
676
+ try {
677
+ return new URL(next).origin === new URL(current).origin ? next : void 0;
678
+ } catch {
679
+ return;
680
+ }
681
+ }
670
682
  function notFound$5(tableId) {
671
683
  return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
672
684
  }
@@ -682,7 +694,7 @@ function odataUrl(base, params) {
682
694
  ...params
683
695
  }).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&")}`;
684
696
  }
685
- function checkTableId$3(tableId) {
697
+ function checkTableId$4(tableId) {
686
698
  if (!TABLE_ID_PATTERN$3.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
687
699
  }
688
700
  function selectedCodes$2(variable, selection) {
@@ -744,7 +756,7 @@ function createCbsODataClient(options) {
744
756
  for (let page = 0; url && page < MAX_KEY_PAGES; page++) {
745
757
  const data = await request(url, get, keysSchema, (parsed) => parsed, METADATA_TTL_SECONDS, `meta:${url}`);
746
758
  keys.push(...data.value);
747
- url = data["odata.nextLink"];
759
+ url = sameOriginLink(data["odata.nextLink"], firstUrl);
748
760
  }
749
761
  return keys;
750
762
  }
@@ -789,7 +801,7 @@ function createCbsODataClient(options) {
789
801
  for (let page = 0; url && page < MAX_KEY_PAGES; page++) {
790
802
  const data = await request(url, get, v4CodesSchema, (parsed) => parsed, METADATA_TTL_SECONDS, `meta:${url}`);
791
803
  codes.push(...data.value);
792
- url = data["@odata.nextLink"];
804
+ url = sameOriginLink(data["@odata.nextLink"], firstUrl);
793
805
  }
794
806
  return codes;
795
807
  }
@@ -838,7 +850,7 @@ function createCbsODataClient(options) {
838
850
  };
839
851
  }
840
852
  async function table(tableId) {
841
- checkTableId$3(tableId);
853
+ checkTableId$4(tableId);
842
854
  try {
843
855
  return await loadTable(tableId);
844
856
  } catch (err) {
@@ -846,7 +858,7 @@ function createCbsODataClient(options) {
846
858
  try {
847
859
  return await loadV4Table(tableId);
848
860
  } catch (v4Err) {
849
- if (isNotFound(v4Err)) throw notFound$5(tableId);
861
+ if (isNotFound(v4Err)) throw isTransient(err) ? err : notFound$5(tableId);
850
862
  throw v4Err;
851
863
  }
852
864
  }
@@ -934,7 +946,7 @@ function createCbsODataClient(options) {
934
946
  };
935
947
  }
936
948
  // src/eurostat-client.ts
937
- const CODE_PATTERN = /^[A-Za-z0-9_$.-]+$/;
949
+ const CODE_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9_$.-]+$/;
938
950
  const CLOSED_TITLE = /\(\d{4}\s*-\s*\d{4}\)\s*$/;
939
951
  const TIME_CODE$2 = "time";
940
952
  const NOT_FOUND_STATUSES$3 = /* @__PURE__ */ new Set([400, 404]);
@@ -1154,13 +1166,15 @@ function createEurostatClient(options) {
1154
1166
  isTime: false
1155
1167
  }));
1156
1168
  const periods = periodsBetween(entry.start, entry.end);
1169
+ const incomplete = stepOf(entry.end) === void 0 || !periodParts(entry.start) || !periodParts(entry.end);
1157
1170
  variables.push({
1158
1171
  code: TIME_CODE$2,
1159
1172
  label: TIME_CODE$2,
1160
1173
  values: periods,
1161
1174
  valueLabels: periods,
1162
1175
  eliminable: false,
1163
- isTime: true
1176
+ isTime: true,
1177
+ ...incomplete && { periodsIncomplete: true }
1164
1178
  });
1165
1179
  return {
1166
1180
  title: entry.title,
@@ -1252,7 +1266,7 @@ function toTable(data) {
1252
1266
  function notFound$3(tableId) {
1253
1267
  return new PxwebError(`Table "${tableId}" was not found. Use search_tables to find a table id.`, 404);
1254
1268
  }
1255
- function checkTableId$2(tableId) {
1269
+ function checkTableId$3(tableId) {
1256
1270
  if (!MATRIX_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
1257
1271
  }
1258
1272
  function requestedCodes(values, selection, total) {
@@ -1274,7 +1288,7 @@ function createPxstatClient(options) {
1274
1288
  currentYear: () => now().getUTCFullYear()
1275
1289
  });
1276
1290
  async function loadTable(lang, tableId) {
1277
- checkTableId$2(tableId);
1291
+ checkTableId$3(tableId);
1278
1292
  const url = `${root}/api.restful/PxStat.Data.Cube_API.ReadMetadata/${tableId}/JSON-stat/2.0/${encodeURIComponent(lang)}`;
1279
1293
  try {
1280
1294
  return await request(url, { method: "GET" }, metadataSchema$3, toTable, METADATA_TTL_SECONDS, `meta:${url}`);
@@ -1339,7 +1353,7 @@ const NOT_FOUND_STATUSES$2 = /* @__PURE__ */ new Set([400, 404]);
1339
1353
  * dashes and diacritics; "." and ".." and URL syntax characters are refused.
1340
1354
  */
1341
1355
  const SEGMENT_PATTERN = /^(?!\.{1,2}$)[^\s/\\?#%\p{Cc}\p{Cs}](?:[^/\\?#%\p{Cc}\p{Cs}]*[^\s/\\?#%\p{Cc}\p{Cs}])?$/u;
1342
- const MAX_TABLE_ID_LENGTH = 400;
1356
+ const MAX_TABLE_ID_LENGTH$1 = 400;
1343
1357
  const searchHitSchema = z.object({
1344
1358
  id: z.string(),
1345
1359
  path: z.string().optional(),
@@ -1371,7 +1385,7 @@ const metadataSchema$2 = z.object({
1371
1385
  variables: z.array(variableSchema)
1372
1386
  });
1373
1387
  function isValidTableId(tableId) {
1374
- return tableId.length <= MAX_TABLE_ID_LENGTH && tableId.split("/").every((segment) => SEGMENT_PATTERN.test(segment));
1388
+ return tableId.length <= MAX_TABLE_ID_LENGTH$1 && tableId.split("/").every((segment) => SEGMENT_PATTERN.test(segment));
1375
1389
  }
1376
1390
  const encodePath = (path) => path.split("/").map(encodeURIComponent).join("/");
1377
1391
  function rootForLanguage(baseUrl, lang) {
@@ -1841,7 +1855,8 @@ function toTableStructure(structure, availability, lang) {
1841
1855
  values: periods,
1842
1856
  valueLabels: periods,
1843
1857
  eliminable: false,
1844
- isTime: true
1858
+ isTime: true,
1859
+ ...periods.length === 0 && { periodsIncomplete: true }
1845
1860
  });
1846
1861
  return {
1847
1862
  metadata: {
@@ -2149,7 +2164,7 @@ function unwrap(envelope) {
2149
2164
  if (status !== 200 || !envelope.Data) throw new PxwebError(`SingStat returned ${status}: ${envelope.Message ?? "no data"}`, status === 200 ? 502 : status);
2150
2165
  return envelope.Data;
2151
2166
  }
2152
- function checkTableId$1(tableId) {
2167
+ function checkTableId$2(tableId) {
2153
2168
  if (!TABLE_ID_PATTERN$1.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
2154
2169
  }
2155
2170
  function notFound$1(tableId) {
@@ -2221,11 +2236,11 @@ function createSingstatClient(options) {
2221
2236
  return rankSearchHits([...inTitle, ...hits.filter((hit) => !titled.has(hit.tableId))], now().getUTCFullYear());
2222
2237
  },
2223
2238
  async getMetadata(_lang, tableId) {
2224
- checkTableId$1(tableId);
2239
+ checkTableId$2(tableId);
2225
2240
  return metadata(tableId);
2226
2241
  },
2227
2242
  async query(_lang, tableId, selections) {
2228
- checkTableId$1(tableId);
2243
+ checkTableId$2(tableId);
2229
2244
  const table = await metadata(tableId);
2230
2245
  const byCode = new Map(selections.map((selection) => [selection.code, selection]));
2231
2246
  const [seriesVariable, timeVariable] = table.variables;
@@ -2338,7 +2353,7 @@ function valueCodes(selection) {
2338
2353
  if (filter === "all") return ["*"];
2339
2354
  return values;
2340
2355
  }
2341
- function checkTableId(tableId) {
2356
+ function checkTableId$1(tableId) {
2342
2357
  if (!TABLE_ID_PATTERN.test(tableId)) throw new PxwebError(`Invalid table id "${tableId}". Use the id exactly as search_tables returns it.`, 400);
2343
2358
  }
2344
2359
  function post$1(body) {
@@ -2377,7 +2392,7 @@ function createStatbankDkClient(options) {
2377
2392
  return (await tableIndex(lang)).search(query, searchOptions);
2378
2393
  },
2379
2394
  async getMetadata(lang, tableId) {
2380
- checkTableId(tableId);
2395
+ checkTableId$1(tableId);
2381
2396
  const url = `${baseUrl}/tableinfo/${encodeURIComponent(tableId)}?${new URLSearchParams({ lang }).toString()}`;
2382
2397
  try {
2383
2398
  return await request(url, { method: "GET" }, tableInfoSchema, toTableMetadata, METADATA_TTL_SECONDS, `meta:${url}`);
@@ -2387,7 +2402,7 @@ function createStatbankDkClient(options) {
2387
2402
  }
2388
2403
  },
2389
2404
  async query(lang, tableId, selections) {
2390
- checkTableId(tableId);
2405
+ checkTableId$1(tableId);
2391
2406
  const url = `${baseUrl}/data`;
2392
2407
  const body = {
2393
2408
  table: tableId,
@@ -2586,13 +2601,15 @@ function createStatcanClient(options) {
2586
2601
  isTime: false
2587
2602
  }));
2588
2603
  const periods = periodsOf(listed.cubeStartDate ?? void 0, listed.cubeEndDate ?? void 0, frequency);
2604
+ const incomplete = !REGULAR_FREQUENCIES[frequency ?? ""] || !listed.cubeStartDate;
2589
2605
  variables.push({
2590
2606
  code: TIME_CODE,
2591
2607
  label: french ? "Période de référence" : "Reference period",
2592
2608
  values: periods,
2593
2609
  valueLabels: periods,
2594
2610
  eliminable: false,
2595
- isTime: true
2611
+ isTime: true,
2612
+ ...incomplete && { periodsIncomplete: true }
2596
2613
  });
2597
2614
  return {
2598
2615
  metadata: {
@@ -2729,7 +2746,7 @@ function planQuery(metadata, inputs, maxCells, maxResultChars = DEFAULT_MAX_RESU
2729
2746
  for (const variable of metadata.variables) {
2730
2747
  const input = inputByCode.get(variable.code);
2731
2748
  if (input?.latest !== void 0) {
2732
- const count = Math.min(input.latest, variable.values.length);
2749
+ const count = variable.periodsIncomplete ? input.latest : Math.min(input.latest, variable.values.length);
2733
2750
  selections.push({
2734
2751
  code: variable.code,
2735
2752
  selection: {
@@ -2788,6 +2805,50 @@ function planQuery(metadata, inputs, maxCells, maxResultChars = DEFAULT_MAX_RESU
2788
2805
  estimatedChars
2789
2806
  };
2790
2807
  }
2808
+ const MAX_VALUES_PER_SELECTION = 5e3;
2809
+ function checkLength(name, value, max, hint) {
2810
+ if (value.length > max) throw new QueryPlanError(`${name} is too long (over ${max} characters). ${hint}`);
2811
+ }
2812
+ function checkTableId(tableId) {
2813
+ checkLength("tableId", tableId, 200, "Use the id exactly as search_tables returns it.");
2814
+ }
2815
+ function checkSearchInput(query) {
2816
+ checkLength("query", query, 200, "Use a few short keywords.");
2817
+ }
2818
+ function checkMetadataInput(tableId, valueFilter) {
2819
+ checkTableId(tableId);
2820
+ if (valueFilter !== void 0) checkLength("valueFilter", valueFilter, 100, "Use a short piece of a label.");
2821
+ }
2822
+ function checkQueryInput(tableId, selections) {
2823
+ checkTableId(tableId);
2824
+ if (selections.length > 30) throw new QueryPlanError(`Too many selections (over 30). Leave out variables you do not need.`);
2825
+ for (const selection of selections) {
2826
+ const values = selection.values ?? [];
2827
+ if (values.length > 5e3) throw new QueryPlanError(`Too many values for "${selection.code}" (over ${MAX_VALUES_PER_SELECTION}). Select fewer values or use latest.`);
2828
+ for (const value of values) checkLength("A value code", value, 200, "Use value codes exactly as get_table_metadata returns them.");
2829
+ }
2830
+ }
2831
+ // src/tools/tool-input.ts
2832
+ /** Tool input without the `$schema` URI: clients send it to the model on every turn, and it carries no meaning there. */
2833
+ function toolInput(shape) {
2834
+ const schema = z.object(shape);
2835
+ const standard = schema["~standard"];
2836
+ const { jsonSchema } = standard;
2837
+ schema["~standard"] = {
2838
+ ...standard,
2839
+ jsonSchema: {
2840
+ input: (options) => {
2841
+ const { $schema: _uri, ...rest } = jsonSchema.input(options);
2842
+ return rest;
2843
+ },
2844
+ output: (options) => {
2845
+ const { $schema: _uri, ...rest } = jsonSchema.output(options);
2846
+ return rest;
2847
+ }
2848
+ }
2849
+ };
2850
+ return schema;
2851
+ }
2791
2852
  // src/tools/tool-result.ts
2792
2853
  function textResult(text) {
2793
2854
  return { content: [{
@@ -2840,18 +2901,14 @@ async function searchWithAliases(client, preset, lang, query, includeArchived) {
2840
2901
  return true;
2841
2902
  });
2842
2903
  }
2843
- function registerSearchTools(server, client, preset) {
2844
- server.registerTool("search_tables", {
2845
- title: "Search statistical tables",
2846
- description: "Find tables by keywords in their titles. Returns table ids, titles and publish dates, best match first. Search with short topic words, for example \"unemployment municipalities\", not full questions.",
2847
- inputSchema: z.object({
2848
- query: z.string().min(2).describe("Keywords to search for."),
2849
- lang: z.enum(preset.languages).optional().describe(`Language of titles. Default "${preset.languages[0]}".`),
2850
- limit: z.number().int().min(1).max(50).optional().describe(`Maximum results. Default ${preset.searchLimit}.`),
2851
- includeArchived: z.boolean().optional().describe("Also list discontinued tables, for older periods. Default false.")
2852
- }),
2853
- annotations: readAnnotations("Search statistical tables")
2854
- }, async ({ query, lang = preset.languages[0], limit = preset.searchLimit, includeArchived = false }) => runTool(async () => {
2904
+ const SEARCH_DESCRIPTION = "Find tables by keywords in their titles. Returns table ids, titles and publish dates, best match first. Search with short topic words, for example \"unemployment municipalities\", not full questions.";
2905
+ const searchQuerySchema = z.string().min(2).describe("Keywords to search for.");
2906
+ const limitSchema = (searchLimit) => z.number().int().min(1).max(50).optional().describe(`Maximum results. Default ${searchLimit}.`);
2907
+ const includeArchivedSchema = z.boolean().optional().describe("Also list discontinued tables, for older periods. Default false.");
2908
+ function searchTables(client, preset, args) {
2909
+ const { query, lang, limit, includeArchived } = args;
2910
+ return runTool(async () => {
2911
+ checkSearchInput(query);
2855
2912
  const hits = await searchWithAliases(client, preset, lang, query, includeArchived);
2856
2913
  if (!hits.length) {
2857
2914
  const archived = includeArchived ? [] : await searchWithAliases(client, preset, lang, query, true);
@@ -2860,6 +2917,24 @@ function registerSearchTools(server, client, preset) {
2860
2917
  }
2861
2918
  const lines = hits.slice(0, limit).map((hit) => `${hit.tableId} | ${hit.title}${hit.published ? ` | ${hit.published.slice(0, 10)}` : ""}${hit.archived ? " | archived" : ""}`);
2862
2919
  return textResult(`${hits.length} tables match; showing ${lines.length}.\n${lines.join("\n")}\n\n${preset.attribution(lang)}`);
2920
+ });
2921
+ }
2922
+ function registerSearchTools(server, client, preset) {
2923
+ server.registerTool("search_tables", {
2924
+ title: "Search statistical tables",
2925
+ description: SEARCH_DESCRIPTION,
2926
+ inputSchema: toolInput({
2927
+ query: searchQuerySchema,
2928
+ lang: z.enum(preset.languages).optional().describe(`Language of titles. Default "${preset.languages[0]}".`),
2929
+ limit: limitSchema(preset.searchLimit),
2930
+ includeArchived: includeArchivedSchema
2931
+ }),
2932
+ annotations: readAnnotations("Search statistical tables")
2933
+ }, async ({ query, lang = preset.languages[0], limit = preset.searchLimit, includeArchived = false }) => searchTables(client, preset, {
2934
+ query,
2935
+ lang,
2936
+ limit,
2937
+ includeArchived
2863
2938
  }));
2864
2939
  }
2865
2940
  // src/metadata.ts
@@ -2903,51 +2978,83 @@ function formatMetadata(tableId, metadata, valueFilter) {
2903
2978
  return lines.join("\n");
2904
2979
  }
2905
2980
  // src/tools/table-tools.ts
2906
- const tableId = z.string().min(1).describe("Table id exactly as search_tables returns it.");
2981
+ const tableIdSchema = z.string().min(1).describe("Table id exactly as search_tables returns it.");
2982
+ const valueFilterSchema = z.string().optional().describe("Show only values whose label contains this text, for example \"Ljubljana\".");
2983
+ const selectionsSchema = z.array(z.object({
2984
+ code: z.string().describe("Variable code from get_table_metadata."),
2985
+ values: z.array(z.string()).optional().describe("Value codes to include."),
2986
+ latest: z.number().int().min(1).optional().describe("Include only the last N values. Use it for time variables, for example the latest 4 quarters.")
2987
+ })).describe("One entry per variable to filter. Leave out variables you do not need.");
2988
+ const METADATA_DESCRIPTION = "List the variables of a table and their value codes. Call this before query_table. Long value lists are shortened; use valueFilter to find specific values, for example a municipality name.";
2989
+ function queryTableDescription(maxCells) {
2990
+ return `Get data from a table as CSV with readable labels. For each variable, give value codes from get_table_metadata, or "latest" for the most recent N periods. Results above ${maxCells} cells, or too large for the context, are refused with advice on how to narrow the query.`;
2991
+ }
2992
+ function sourceLine(preset, language, id) {
2993
+ return `${preset.attribution(language)}, table ${id}: ${preset.tableUrl(language, id)}`;
2994
+ }
2995
+ function getTableMetadata(client, preset, args) {
2996
+ return runTool(async () => {
2997
+ checkMetadataInput(args.tableId, args.valueFilter);
2998
+ const metadata = await client.getMetadata(args.lang, args.tableId);
2999
+ return textResult(`${formatMetadata(args.tableId, metadata, args.valueFilter)}\n\nOptional variables can be left out; the result then shows their total. Required variables left out return all their values.\n\n${sourceLine(preset, args.lang, args.tableId)}`);
3000
+ });
3001
+ }
3002
+ function queryTable(client, preset, args) {
3003
+ return runTool(async () => {
3004
+ checkQueryInput(args.tableId, args.selections);
3005
+ const metadata = await client.getMetadata(args.lang, args.tableId);
3006
+ const plan = planQuery(metadata, args.selections, preset.maxCells, preset.maxResultChars);
3007
+ const table = await client.query(args.lang, args.tableId, plan.selections);
3008
+ const csv = toCsv(table);
3009
+ const maxChars = preset.maxResultChars ?? 3e4;
3010
+ if (table.rows.length > preset.maxCells) throw new QueryPlanError(`The result has ${table.rows.length} rows, above the limit of ${preset.maxCells}. Select fewer values or use a smaller latest.`);
3011
+ if (csv.length > maxChars) throw new QueryPlanError(`The result has ${csv.length} characters, above the limit of ${maxChars}. Select fewer values or use a smaller latest.`);
3012
+ return textResult(`${`${table.label ?? metadata.title}. ${table.rows.length} rows.`}\n\n${csv}\n\n${sourceLine(preset, args.lang, args.tableId)}`);
3013
+ });
3014
+ }
2907
3015
  function registerTableTools(server, client, preset) {
2908
3016
  const lang = z.enum(preset.languages).optional().describe(`Language of labels. Default "${preset.languages[0]}".`);
2909
- function sourceLine(language, id) {
2910
- return `${preset.attribution(language)}, table ${id}: ${preset.tableUrl(language, id)}`;
2911
- }
2912
3017
  server.registerTool("get_table_metadata", {
2913
3018
  title: "Get table variables",
2914
- description: "List the variables of a table and their value codes. Call this before query_table. Long value lists are shortened; use valueFilter to find specific values, for example a municipality name.",
2915
- inputSchema: z.object({
2916
- tableId,
3019
+ description: METADATA_DESCRIPTION,
3020
+ inputSchema: toolInput({
3021
+ tableId: tableIdSchema,
2917
3022
  lang,
2918
- valueFilter: z.string().optional().describe("Show only values whose label contains this text, for example \"Ljubljana\".")
3023
+ valueFilter: valueFilterSchema
2919
3024
  }),
2920
3025
  annotations: readAnnotations("Get table variables")
2921
- }, async ({ tableId: id, lang: language = preset.languages[0], valueFilter }) => runTool(async () => {
2922
- return textResult(`${formatMetadata(id, await client.getMetadata(language, id), valueFilter)}\n\nOptional variables can be left out; the result then shows their total. Required variables left out return all their values.\n\n${sourceLine(language, id)}`);
3026
+ }, async ({ tableId, lang: language = preset.languages[0], valueFilter }) => getTableMetadata(client, preset, {
3027
+ tableId,
3028
+ lang: language,
3029
+ valueFilter
2923
3030
  }));
2924
3031
  server.registerTool("query_table", {
2925
3032
  title: "Query table data",
2926
- description: `Get data from a table as CSV with readable labels. For each variable, give value codes from get_table_metadata, or "latest" for the most recent N periods. Results above ${preset.maxCells} cells, or too large for the context, are refused with advice on how to narrow the query.`,
2927
- inputSchema: z.object({
2928
- tableId,
3033
+ description: queryTableDescription(preset.maxCells),
3034
+ inputSchema: toolInput({
3035
+ tableId: tableIdSchema,
2929
3036
  lang,
2930
- selections: z.array(z.object({
2931
- code: z.string().describe("Variable code from get_table_metadata."),
2932
- values: z.array(z.string()).optional().describe("Value codes to include."),
2933
- latest: z.number().int().min(1).optional().describe("Include only the last N values. Use it for time variables, for example the latest 4 quarters.")
2934
- })).describe("One entry per variable to filter. Leave out variables you do not need.")
3037
+ selections: selectionsSchema
2935
3038
  }),
2936
3039
  annotations: readAnnotations("Query table data")
2937
- }, async ({ tableId: id, lang: language = preset.languages[0], selections }) => runTool(async () => {
2938
- const metadata = await client.getMetadata(language, id);
2939
- const plan = planQuery(metadata, selections, preset.maxCells, preset.maxResultChars);
2940
- const table = await client.query(language, id, plan.selections);
2941
- return textResult(`${`${table.label ?? metadata.title}. ${table.rows.length} rows.`}\n\n${toCsv(table)}\n\n${sourceLine(language, id)}`);
3040
+ }, async ({ tableId, lang: language = preset.languages[0], selections }) => queryTable(client, preset, {
3041
+ tableId,
3042
+ lang: language,
3043
+ selections
2942
3044
  }));
2943
3045
  }
2944
3046
  // src/create-pxweb-server.ts
3047
+ /**
3048
+ * Models remember table ids for well-known statistics and skip the search; a
3049
+ * remembered id can be outdated or wrong, so every server asks for a search first.
3050
+ */
3051
+ const SEARCH_FIRST = "Always call `search_tables` first, unless the user gives a table id. Use only table ids from search results or from the user.";
2945
3052
  function createPxwebServer(preset, client) {
2946
3053
  const server = new McpServer({
2947
3054
  name: preset.name,
2948
3055
  title: preset.title,
2949
3056
  version: preset.version
2950
- }, { instructions: preset.instructions });
3057
+ }, { instructions: `${preset.instructions}\n\n${SEARCH_FIRST}` });
2951
3058
  registerSearchTools(server, client, preset);
2952
3059
  registerTableTools(server, client, preset);
2953
3060
  return server;
@@ -3011,4 +3118,122 @@ function createPresetServer(preset, options = {}) {
3011
3118
  userAgent: options.userAgent ?? `${preset.name}-mcp/${preset.version}`
3012
3119
  }));
3013
3120
  }
3014
- export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SNAPSHOT_VERSION, bucketSnapshotReader, createCbsODataClient, createEurostatClient, createMemoryCache, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
3121
+ // src/create-multi-server.ts
3122
+ const INSTRUCTIONS = `Official statistics from national statistics offices and Eurostat. Not affiliated with or endorsed by any of them.
3123
+
3124
+ Workflow: search_tables with short topic keywords (always search first, unless the user gives a table id), then get_table_metadata, then query_table with only the values you need. Call list_countries with a country code for that office's hints. To compare countries, query each one separately and say which office each number comes from.
3125
+
3126
+ Always cite the source line that each result ends with. Mark your own calculations.`;
3127
+ function createMultiServer(entries, options) {
3128
+ const [first, ...rest] = entries.map((entry) => entry.code);
3129
+ if (first === void 0) throw new Error("createMultiServer needs at least one country.");
3130
+ const byCode = new Map(entries.map((entry) => [entry.code, entry]));
3131
+ if (byCode.size !== entries.length) throw new Error("createMultiServer needs unique country codes.");
3132
+ const searchLimits = new Set(entries.map((entry) => entry.preset.searchLimit));
3133
+ const [sharedLimit] = searchLimits;
3134
+ const limitArg = searchLimits.size === 1 && sharedLimit !== void 0 ? limitSchema(sharedLimit) : limitSchema(0).describe("Maximum results. Default: the country's own limit.");
3135
+ const clients = /* @__PURE__ */ new Map();
3136
+ const country = z.enum([first, ...rest]).describe("\"eu\" is Eurostat.");
3137
+ const lang = z.string().optional().describe("Language of the search words and labels, for example \"is\". Default: the country's first language.");
3138
+ function resolve(code, language) {
3139
+ const entry = byCode.get(code);
3140
+ if (!entry) return { error: toolError(`Unknown country "${code}". Valid codes: ${[...byCode.keys()].join(", ")}.`) };
3141
+ const { languages } = entry.preset;
3142
+ const chosen = language ?? languages[0];
3143
+ if (!languages.includes(chosen)) return { error: toolError(`Country "${code}" has no language "${chosen}". Use one of: ${languages.join(", ")}.`) };
3144
+ let client = clients.get(code);
3145
+ if (!client) {
3146
+ try {
3147
+ client = entry.client();
3148
+ } catch (err) {
3149
+ console.error("Could not create the client", code, err);
3150
+ return { error: toolError(`Country "${code}" is not available now.`) };
3151
+ }
3152
+ clients.set(code, client);
3153
+ }
3154
+ return {
3155
+ preset: entry.preset,
3156
+ client,
3157
+ lang: chosen
3158
+ };
3159
+ }
3160
+ const server = new McpServer({
3161
+ name: options.name,
3162
+ title: options.title,
3163
+ version: options.version
3164
+ }, { instructions: INSTRUCTIONS });
3165
+ server.registerTool("list_countries", {
3166
+ title: "List countries",
3167
+ description: "List the country codes, offices and languages. With a country code, show the hints for that office.",
3168
+ inputSchema: toolInput({ country: country.optional() }),
3169
+ annotations: readAnnotations("List countries")
3170
+ }, async ({ country: code }) => {
3171
+ if (code !== void 0) {
3172
+ const entry = byCode.get(code);
3173
+ return entry ? textResult(`${entry.preset.title}\n\n${entry.preset.instructions}`) : toolError(`Unknown country "${code}".`);
3174
+ }
3175
+ return textResult(entries.map((entry) => `${entry.code} | ${entry.preset.title} | languages: ${entry.preset.languages.join(", ")}`).join("\n"));
3176
+ });
3177
+ server.registerTool("search_tables", {
3178
+ title: "Search statistical tables",
3179
+ description: SEARCH_DESCRIPTION,
3180
+ inputSchema: toolInput({
3181
+ country,
3182
+ query: searchQuerySchema,
3183
+ lang,
3184
+ limit: limitArg,
3185
+ includeArchived: includeArchivedSchema
3186
+ }),
3187
+ annotations: readAnnotations("Search statistical tables")
3188
+ }, async ({ country: code, query, lang: language, limit, includeArchived }) => {
3189
+ const target = resolve(code, language);
3190
+ if ("error" in target) return target.error;
3191
+ return searchTables(target.client, target.preset, {
3192
+ query,
3193
+ lang: target.lang,
3194
+ limit: limit ?? target.preset.searchLimit,
3195
+ includeArchived: includeArchived ?? false
3196
+ });
3197
+ });
3198
+ server.registerTool("get_table_metadata", {
3199
+ title: "Get table variables",
3200
+ description: METADATA_DESCRIPTION,
3201
+ inputSchema: toolInput({
3202
+ country,
3203
+ tableId: tableIdSchema,
3204
+ lang,
3205
+ valueFilter: valueFilterSchema
3206
+ }),
3207
+ annotations: readAnnotations("Get table variables")
3208
+ }, async ({ country: code, tableId, lang: language, valueFilter }) => {
3209
+ const target = resolve(code, language);
3210
+ if ("error" in target) return target.error;
3211
+ return getTableMetadata(target.client, target.preset, {
3212
+ tableId,
3213
+ lang: target.lang,
3214
+ valueFilter
3215
+ });
3216
+ });
3217
+ const maxCells = Math.min(...entries.map((entry) => entry.preset.maxCells));
3218
+ server.registerTool("query_table", {
3219
+ title: "Query table data",
3220
+ description: queryTableDescription(maxCells),
3221
+ inputSchema: toolInput({
3222
+ country,
3223
+ tableId: tableIdSchema,
3224
+ lang,
3225
+ selections: selectionsSchema
3226
+ }),
3227
+ annotations: readAnnotations("Query table data")
3228
+ }, async ({ country: code, tableId, lang: language, selections }) => {
3229
+ const target = resolve(code, language);
3230
+ if ("error" in target) return target.error;
3231
+ return queryTable(target.client, target.preset, {
3232
+ tableId,
3233
+ lang: target.lang,
3234
+ selections
3235
+ });
3236
+ });
3237
+ return server;
3238
+ }
3239
+ export { DEFAULT_MAX_RESULT_CHARS, PxwebError, QueryPlanError, SNAPSHOT_VERSION, bucketSnapshotReader, createCbsODataClient, createEurostatClient, createMemoryCache, createMultiServer, createPresetClient, createPresetServer, createPxstatClient, createPxwebClient, createPxwebServer, createPxwebV2Client, createSdmxClient, createSingstatClient, createStatbankDkClient, createStatcanClient, createTableIndex, createTableIndexLoader, firstSnapshot, flattenJsonStat, planQuery, readSnapshot, searchTitles, snapshotKey, tableDocSchema, toCsv, urlSnapshotReader, writeSnapshot };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@statsmcp/core",
3
- "version": "0.3.0",
4
- "description": "MCP server toolkit for PxWeb API v1 statistics databases",
3
+ "version": "0.4.1",
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",
7
7
  "homepage": "https://statsmcp.dev/",