@statsmcp/core 0.3.0 → 0.4.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 CHANGED
@@ -321,6 +321,18 @@ interface SdmxClientOptions extends HttpOptions, TableListOptions {
321
321
  * a local index over the dataflow list.
322
322
  */
323
323
  export declare function createSdmxClient(options: SdmxClientOptions): PxwebClient;
324
+ interface MultiServerEntry {
325
+ code: string;
326
+ preset: PxwebPreset;
327
+ /** Called at most once, when a tool call first uses this country. */
328
+ client: () => PxwebClient;
329
+ }
330
+ interface MultiServerOptions {
331
+ name: string;
332
+ title: string;
333
+ version: string;
334
+ }
335
+ export declare function createMultiServer(entries: readonly MultiServerEntry[], options: MultiServerOptions): McpServer;
324
336
  interface CbsODataClientOptions extends HttpOptions, TableListOptions {
325
337
  /** Root of the CBS open data service, for example "https://opendata.cbs.nl". */
326
338
  baseUrl: string;
@@ -361,4 +373,4 @@ interface PxwebV2ClientOptions extends HttpOptions, TableListOptions {
361
373
  }
362
374
  /** Client for the PxWeb API v2, with the same interface as the v1 client. */
363
375
  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 };
376
+ 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
@@ -2687,6 +2687,27 @@ function createStatcanClient(options) {
2687
2687
  }
2688
2688
  };
2689
2689
  }
2690
+ // src/tools/tool-input.ts
2691
+ /** Tool input without the `$schema` URI: clients send it to the model on every turn, and it carries no meaning there. */
2692
+ function toolInput(shape) {
2693
+ const schema = z.object(shape);
2694
+ const standard = schema["~standard"];
2695
+ const { jsonSchema } = standard;
2696
+ schema["~standard"] = {
2697
+ ...standard,
2698
+ jsonSchema: {
2699
+ input: (options) => {
2700
+ const { $schema: _uri, ...rest } = jsonSchema.input(options);
2701
+ return rest;
2702
+ },
2703
+ output: (options) => {
2704
+ const { $schema: _uri, ...rest } = jsonSchema.output(options);
2705
+ return rest;
2706
+ }
2707
+ }
2708
+ };
2709
+ return schema;
2710
+ }
2690
2711
  // src/query-plan.ts
2691
2712
  const DEFAULT_MAX_RESULT_CHARS = 3e4;
2692
2713
  const VALUE_CHARS = 10;
@@ -2840,18 +2861,13 @@ async function searchWithAliases(client, preset, lang, query, includeArchived) {
2840
2861
  return true;
2841
2862
  });
2842
2863
  }
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 () => {
2864
+ 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.";
2865
+ const searchQuerySchema = z.string().min(2).describe("Keywords to search for.");
2866
+ const limitSchema = (searchLimit) => z.number().int().min(1).max(50).optional().describe(`Maximum results. Default ${searchLimit}.`);
2867
+ const includeArchivedSchema = z.boolean().optional().describe("Also list discontinued tables, for older periods. Default false.");
2868
+ function searchTables(client, preset, args) {
2869
+ const { query, lang, limit, includeArchived } = args;
2870
+ return runTool(async () => {
2855
2871
  const hits = await searchWithAliases(client, preset, lang, query, includeArchived);
2856
2872
  if (!hits.length) {
2857
2873
  const archived = includeArchived ? [] : await searchWithAliases(client, preset, lang, query, true);
@@ -2860,6 +2876,24 @@ function registerSearchTools(server, client, preset) {
2860
2876
  }
2861
2877
  const lines = hits.slice(0, limit).map((hit) => `${hit.tableId} | ${hit.title}${hit.published ? ` | ${hit.published.slice(0, 10)}` : ""}${hit.archived ? " | archived" : ""}`);
2862
2878
  return textResult(`${hits.length} tables match; showing ${lines.length}.\n${lines.join("\n")}\n\n${preset.attribution(lang)}`);
2879
+ });
2880
+ }
2881
+ function registerSearchTools(server, client, preset) {
2882
+ server.registerTool("search_tables", {
2883
+ title: "Search statistical tables",
2884
+ description: SEARCH_DESCRIPTION,
2885
+ inputSchema: toolInput({
2886
+ query: searchQuerySchema,
2887
+ lang: z.enum(preset.languages).optional().describe(`Language of titles. Default "${preset.languages[0]}".`),
2888
+ limit: limitSchema(preset.searchLimit),
2889
+ includeArchived: includeArchivedSchema
2890
+ }),
2891
+ annotations: readAnnotations("Search statistical tables")
2892
+ }, async ({ query, lang = preset.languages[0], limit = preset.searchLimit, includeArchived = false }) => searchTables(client, preset, {
2893
+ query,
2894
+ lang,
2895
+ limit,
2896
+ includeArchived
2863
2897
  }));
2864
2898
  }
2865
2899
  // src/metadata.ts
@@ -2903,51 +2937,77 @@ function formatMetadata(tableId, metadata, valueFilter) {
2903
2937
  return lines.join("\n");
2904
2938
  }
2905
2939
  // src/tools/table-tools.ts
2906
- const tableId = z.string().min(1).describe("Table id exactly as search_tables returns it.");
2940
+ const tableIdSchema = z.string().min(1).describe("Table id exactly as search_tables returns it.");
2941
+ const valueFilterSchema = z.string().optional().describe("Show only values whose label contains this text, for example \"Ljubljana\".");
2942
+ const selectionsSchema = z.array(z.object({
2943
+ code: z.string().describe("Variable code from get_table_metadata."),
2944
+ values: z.array(z.string()).optional().describe("Value codes to include."),
2945
+ 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.")
2946
+ })).describe("One entry per variable to filter. Leave out variables you do not need.");
2947
+ 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.";
2948
+ function queryTableDescription(maxCells) {
2949
+ 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.`;
2950
+ }
2951
+ function sourceLine(preset, language, id) {
2952
+ return `${preset.attribution(language)}, table ${id}: ${preset.tableUrl(language, id)}`;
2953
+ }
2954
+ function getTableMetadata(client, preset, args) {
2955
+ return runTool(async () => {
2956
+ const metadata = await client.getMetadata(args.lang, args.tableId);
2957
+ 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)}`);
2958
+ });
2959
+ }
2960
+ function queryTable(client, preset, args) {
2961
+ return runTool(async () => {
2962
+ const metadata = await client.getMetadata(args.lang, args.tableId);
2963
+ const plan = planQuery(metadata, args.selections, preset.maxCells, preset.maxResultChars);
2964
+ const table = await client.query(args.lang, args.tableId, plan.selections);
2965
+ return textResult(`${`${table.label ?? metadata.title}. ${table.rows.length} rows.`}\n\n${toCsv(table)}\n\n${sourceLine(preset, args.lang, args.tableId)}`);
2966
+ });
2967
+ }
2907
2968
  function registerTableTools(server, client, preset) {
2908
2969
  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
2970
  server.registerTool("get_table_metadata", {
2913
2971
  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,
2972
+ description: METADATA_DESCRIPTION,
2973
+ inputSchema: toolInput({
2974
+ tableId: tableIdSchema,
2917
2975
  lang,
2918
- valueFilter: z.string().optional().describe("Show only values whose label contains this text, for example \"Ljubljana\".")
2976
+ valueFilter: valueFilterSchema
2919
2977
  }),
2920
2978
  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)}`);
2979
+ }, async ({ tableId, lang: language = preset.languages[0], valueFilter }) => getTableMetadata(client, preset, {
2980
+ tableId,
2981
+ lang: language,
2982
+ valueFilter
2923
2983
  }));
2924
2984
  server.registerTool("query_table", {
2925
2985
  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,
2986
+ description: queryTableDescription(preset.maxCells),
2987
+ inputSchema: toolInput({
2988
+ tableId: tableIdSchema,
2929
2989
  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.")
2990
+ selections: selectionsSchema
2935
2991
  }),
2936
2992
  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)}`);
2993
+ }, async ({ tableId, lang: language = preset.languages[0], selections }) => queryTable(client, preset, {
2994
+ tableId,
2995
+ lang: language,
2996
+ selections
2942
2997
  }));
2943
2998
  }
2944
2999
  // src/create-pxweb-server.ts
3000
+ /**
3001
+ * Models remember table ids for well-known statistics and skip the search; a
3002
+ * remembered id can be outdated or wrong, so every server asks for a search first.
3003
+ */
3004
+ 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
3005
  function createPxwebServer(preset, client) {
2946
3006
  const server = new McpServer({
2947
3007
  name: preset.name,
2948
3008
  title: preset.title,
2949
3009
  version: preset.version
2950
- }, { instructions: preset.instructions });
3010
+ }, { instructions: `${preset.instructions}\n\n${SEARCH_FIRST}` });
2951
3011
  registerSearchTools(server, client, preset);
2952
3012
  registerTableTools(server, client, preset);
2953
3013
  return server;
@@ -3011,4 +3071,122 @@ function createPresetServer(preset, options = {}) {
3011
3071
  userAgent: options.userAgent ?? `${preset.name}-mcp/${preset.version}`
3012
3072
  }));
3013
3073
  }
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 };
3074
+ // src/create-multi-server.ts
3075
+ const INSTRUCTIONS = `Official statistics from national statistics offices and Eurostat. Not affiliated with or endorsed by any of them.
3076
+
3077
+ 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.
3078
+
3079
+ Always cite the source line that each result ends with. Mark your own calculations.`;
3080
+ function createMultiServer(entries, options) {
3081
+ const [first, ...rest] = entries.map((entry) => entry.code);
3082
+ if (first === void 0) throw new Error("createMultiServer needs at least one country.");
3083
+ const byCode = new Map(entries.map((entry) => [entry.code, entry]));
3084
+ if (byCode.size !== entries.length) throw new Error("createMultiServer needs unique country codes.");
3085
+ const searchLimits = new Set(entries.map((entry) => entry.preset.searchLimit));
3086
+ const [sharedLimit] = searchLimits;
3087
+ const limitArg = searchLimits.size === 1 && sharedLimit !== void 0 ? limitSchema(sharedLimit) : limitSchema(0).describe("Maximum results. Default: the country's own limit.");
3088
+ const clients = /* @__PURE__ */ new Map();
3089
+ const country = z.enum([first, ...rest]).describe("\"eu\" is Eurostat.");
3090
+ const lang = z.string().optional().describe("Language of the search words and labels, for example \"is\". Default: the country's first language.");
3091
+ function resolve(code, language) {
3092
+ const entry = byCode.get(code);
3093
+ if (!entry) return { error: toolError(`Unknown country "${code}". Valid codes: ${[...byCode.keys()].join(", ")}.`) };
3094
+ const { languages } = entry.preset;
3095
+ const chosen = language ?? languages[0];
3096
+ if (!languages.includes(chosen)) return { error: toolError(`Country "${code}" has no language "${chosen}". Use one of: ${languages.join(", ")}.`) };
3097
+ let client = clients.get(code);
3098
+ if (!client) {
3099
+ try {
3100
+ client = entry.client();
3101
+ } catch (err) {
3102
+ console.error("Could not create the client", code, err);
3103
+ return { error: toolError(`Country "${code}" is not available now.`) };
3104
+ }
3105
+ clients.set(code, client);
3106
+ }
3107
+ return {
3108
+ preset: entry.preset,
3109
+ client,
3110
+ lang: chosen
3111
+ };
3112
+ }
3113
+ const server = new McpServer({
3114
+ name: options.name,
3115
+ title: options.title,
3116
+ version: options.version
3117
+ }, { instructions: INSTRUCTIONS });
3118
+ server.registerTool("list_countries", {
3119
+ title: "List countries",
3120
+ description: "List the country codes, offices and languages. With a country code, show the hints for that office.",
3121
+ inputSchema: toolInput({ country: country.optional() }),
3122
+ annotations: readAnnotations("List countries")
3123
+ }, async ({ country: code }) => {
3124
+ if (code !== void 0) {
3125
+ const entry = byCode.get(code);
3126
+ return entry ? textResult(`${entry.preset.title}\n\n${entry.preset.instructions}`) : toolError(`Unknown country "${code}".`);
3127
+ }
3128
+ return textResult(entries.map((entry) => `${entry.code} | ${entry.preset.title} | languages: ${entry.preset.languages.join(", ")}`).join("\n"));
3129
+ });
3130
+ server.registerTool("search_tables", {
3131
+ title: "Search statistical tables",
3132
+ description: SEARCH_DESCRIPTION,
3133
+ inputSchema: toolInput({
3134
+ country,
3135
+ query: searchQuerySchema,
3136
+ lang,
3137
+ limit: limitArg,
3138
+ includeArchived: includeArchivedSchema
3139
+ }),
3140
+ annotations: readAnnotations("Search statistical tables")
3141
+ }, async ({ country: code, query, lang: language, limit, includeArchived }) => {
3142
+ const target = resolve(code, language);
3143
+ if ("error" in target) return target.error;
3144
+ return searchTables(target.client, target.preset, {
3145
+ query,
3146
+ lang: target.lang,
3147
+ limit: limit ?? target.preset.searchLimit,
3148
+ includeArchived: includeArchived ?? false
3149
+ });
3150
+ });
3151
+ server.registerTool("get_table_metadata", {
3152
+ title: "Get table variables",
3153
+ description: METADATA_DESCRIPTION,
3154
+ inputSchema: toolInput({
3155
+ country,
3156
+ tableId: tableIdSchema,
3157
+ lang,
3158
+ valueFilter: valueFilterSchema
3159
+ }),
3160
+ annotations: readAnnotations("Get table variables")
3161
+ }, async ({ country: code, tableId, lang: language, valueFilter }) => {
3162
+ const target = resolve(code, language);
3163
+ if ("error" in target) return target.error;
3164
+ return getTableMetadata(target.client, target.preset, {
3165
+ tableId,
3166
+ lang: target.lang,
3167
+ valueFilter
3168
+ });
3169
+ });
3170
+ const maxCells = Math.min(...entries.map((entry) => entry.preset.maxCells));
3171
+ server.registerTool("query_table", {
3172
+ title: "Query table data",
3173
+ description: queryTableDescription(maxCells),
3174
+ inputSchema: toolInput({
3175
+ country,
3176
+ tableId: tableIdSchema,
3177
+ lang,
3178
+ selections: selectionsSchema
3179
+ }),
3180
+ annotations: readAnnotations("Query table data")
3181
+ }, async ({ country: code, tableId, lang: language, selections }) => {
3182
+ const target = resolve(code, language);
3183
+ if ("error" in target) return target.error;
3184
+ return queryTable(target.client, target.preset, {
3185
+ tableId,
3186
+ lang: target.lang,
3187
+ selections
3188
+ });
3189
+ });
3190
+ return server;
3191
+ }
3192
+ 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,6 +1,6 @@
1
1
  {
2
2
  "name": "@statsmcp/core",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "MCP server toolkit for PxWeb API v1 statistics databases",
5
5
  "license": "MIT",
6
6
  "author": "Tadej Polajnar",