reunion_get_consumer_price_index
Retrieve monthly consumer price index data for La Réunion. Filter by period, COICOP category, and population to track inflation, deflate nominal values, or compare price trends.
Instructions
INSEE monthly Indice des Prix à la Consommation (IPC, consumer price index) for La Réunion. Time series broken down by COICOP category (Classification of Individual Consumption by Purpose) and population (whole population vs urban households). Use it to track inflation, deflate nominal values to real, or compare price evolution across categories (food, energy, housing, transport, etc.). Returns period, COICOP code/label, base year, population, zone, IDBANK identifier, index value. Sorted most recent first.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| period | No | Period prefix match in YYYY-MM format. Examples: "2023" (whole year), "2023-12" (specific month) | |
| coicop_code | No | COICOP category code prefix. Examples: "01" food and beverages, "02" alcohol/tobacco, "04" housing/water/energy, "07" transport, "11" restaurants/hotels, "00" general index | |
| type | No | Type label prefix match (e.g. "Indice général", "Indice mensuel") | |
| limit | No | Max rows to return (1-500, default 100) |
Implementation Reference
- src/modules/economy.ts:66-107 (handler)The handler function for 'reunion_get_consumer_price_index' tool. It queries the INSEE CPI dataset (insee-indices-des-prix-a-la-consommation-a-la-reunion-valeurs-mensuelles) via the OpenDataSoft client, filtering by period, COICOP code, and type. Returns monthly consumer price index data for La Réunion sorted most recent first.
server.tool( 'reunion_get_consumer_price_index', 'INSEE monthly Indice des Prix à la Consommation (IPC, consumer price index) for La Réunion. Time series broken down by COICOP category (Classification of Individual Consumption by Purpose) and population (whole population vs urban households). Use it to track inflation, deflate nominal values to real, or compare price evolution across categories (food, energy, housing, transport, etc.). Returns period, COICOP code/label, base year, population, zone, IDBANK identifier, index value. Sorted most recent first.', { period: z.string().optional().describe('Period prefix match in YYYY-MM format. Examples: "2023" (whole year), "2023-12" (specific month)'), coicop_code: z.string().optional().describe('COICOP category code prefix. Examples: "01" food and beverages, "02" alcohol/tobacco, "04" housing/water/energy, "07" transport, "11" restaurants/hotels, "00" general index'), type: z.string().optional().describe('Type label prefix match (e.g. "Indice général", "Indice mensuel")'), limit: z.number().int().min(1).max(500).default(100).describe('Max rows to return (1-500, default 100)'), }, async ({ period, coicop_code, type, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_CPI, { where: buildWhere([ period ? `periode LIKE ${quote(`${period}%`)}` : undefined, coicop_code ? `coicop_code LIKE ${quote(`${coicop_code}%`)}` : undefined, type ? `type LIKE ${quote(`${type}%`)}` : undefined, ]), order_by: 'periode DESC', limit, }); return jsonResult({ total_rows: data.total_count, series: data.results.map((row) => ({ period: pickString(row, ['periode']), code: pickString(row, ['code']), type: pickString(row, ['type']), sub_type: pickString(row, ['sous_type']), coicop_code: pickString(row, ['coicop_code']), coicop_label: pickString(row, ['coicop_texte']), base: pickString(row, ['base']), population: pickString(row, ['population']), zone: pickString(row, ['zone']), index_name: pickString(row, ['indice']), value: pickNumber(row, ['valeur']), idbank: pickString(row, ['insee_idbank']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch CPI'); } } ); - src/modules/economy.ts:69-74 (schema)Input schema for the tool defining parameters: period (YYYY-MM prefix), coicop_code (category code prefix), type (label prefix), and limit (max rows, 1-500, default 100).
{ period: z.string().optional().describe('Period prefix match in YYYY-MM format. Examples: "2023" (whole year), "2023-12" (specific month)'), coicop_code: z.string().optional().describe('COICOP category code prefix. Examples: "01" food and beverages, "02" alcohol/tobacco, "04" housing/water/energy, "07" transport, "11" restaurants/hotels, "00" general index'), type: z.string().optional().describe('Type label prefix match (e.g. "Indice général", "Indice mensuel")'), limit: z.number().int().min(1).max(500).default(100).describe('Max rows to return (1-500, default 100)'), }, - src/modules/economy.ts:66-107 (registration)Tool registration via server.tool() call in registerEconomyTools(), binding the name 'reunion_get_consumer_price_index' to its schema and handler.
server.tool( 'reunion_get_consumer_price_index', 'INSEE monthly Indice des Prix à la Consommation (IPC, consumer price index) for La Réunion. Time series broken down by COICOP category (Classification of Individual Consumption by Purpose) and population (whole population vs urban households). Use it to track inflation, deflate nominal values to real, or compare price evolution across categories (food, energy, housing, transport, etc.). Returns period, COICOP code/label, base year, population, zone, IDBANK identifier, index value. Sorted most recent first.', { period: z.string().optional().describe('Period prefix match in YYYY-MM format. Examples: "2023" (whole year), "2023-12" (specific month)'), coicop_code: z.string().optional().describe('COICOP category code prefix. Examples: "01" food and beverages, "02" alcohol/tobacco, "04" housing/water/energy, "07" transport, "11" restaurants/hotels, "00" general index'), type: z.string().optional().describe('Type label prefix match (e.g. "Indice général", "Indice mensuel")'), limit: z.number().int().min(1).max(500).default(100).describe('Max rows to return (1-500, default 100)'), }, async ({ period, coicop_code, type, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_CPI, { where: buildWhere([ period ? `periode LIKE ${quote(`${period}%`)}` : undefined, coicop_code ? `coicop_code LIKE ${quote(`${coicop_code}%`)}` : undefined, type ? `type LIKE ${quote(`${type}%`)}` : undefined, ]), order_by: 'periode DESC', limit, }); return jsonResult({ total_rows: data.total_count, series: data.results.map((row) => ({ period: pickString(row, ['periode']), code: pickString(row, ['code']), type: pickString(row, ['type']), sub_type: pickString(row, ['sous_type']), coicop_code: pickString(row, ['coicop_code']), coicop_label: pickString(row, ['coicop_texte']), base: pickString(row, ['base']), population: pickString(row, ['population']), zone: pickString(row, ['zone']), index_name: pickString(row, ['indice']), value: pickNumber(row, ['valeur']), idbank: pickString(row, ['insee_idbank']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch CPI'); } } ); - src/utils/helpers.ts:36-41 (helper)buildWhere helper used to construct the ODSQL WHERE clause from optional filter conditions.
export function buildWhere( conditions: Array<string | undefined | null | false> ): string | undefined { const valid = conditions.filter((condition): condition is string => Boolean(condition)); return valid.length > 0 ? valid.join(' AND ') : undefined; } - src/client.ts:43-261 (helper)ReunionClient.getRecords method used to fetch records from the CPI dataset on data.regionreunion.com.
async getRecords<T extends RecordObject = RecordObject>( datasetId: string, params: ODSQueryParams = {} ): Promise<ODSResponse<T>> { const url = this.buildUrl(`/catalog/datasets/${datasetId}/records`, params); if (REFERENTIAL_DATASETS.has(datasetId)) { const now = Date.now(); const cached = this.recordsCache.get(url); if (cached && cached.expiresAt > now) { return cached.value as ODSResponse<T>; } const value = await this.fetchJson<ODSResponse<T>>(url); this.recordsCache.set(url, { value, expiresAt: now + REFERENTIAL_TTL_MS }); return value; } return this.fetchJson<ODSResponse<T>>(url); } /** * Clear the in-memory caches. Intended for tests. */ clearCaches(): void { this.metadataCache.clear(); this.recordsCache.clear(); } /** * Fetch aggregated data from a dataset */ async getAggregates<T extends RecordObject = RecordObject>( datasetId: string, select: string, options: { where?: string; groupBy?: string; orderBy?: string; limit?: number; } = {} ): Promise<ODSResponse<T>> { const params: Record<string, string | number | undefined> = { select }; if (options.where) params.where = options.where; if (options.groupBy) params.group_by = options.groupBy; if (options.orderBy) params.order_by = options.orderBy; if (options.limit !== undefined) params.limit = options.limit; const url = this.buildUrl(`/catalog/datasets/${datasetId}/aggregates`, params); return this.fetchJson<ODSResponse<T>>(url); } /** * Search across all datasets */ async searchDatasets(query: string): Promise<CatalogResponse> { const url = this.buildUrl('/catalog/datasets', { where: `search(${quote(query)})`, limit: 20, }); return this.fetchJson<CatalogResponse>(url); } /** * List datasets with an optional raw ODSQL where clause. */ async listDatasets( options: { where?: string; limit?: number; offset?: number } = {} ): Promise<CatalogResponse> { const url = this.buildUrl('/catalog/datasets', { where: options.where, limit: options.limit ?? 20, offset: options.offset, }); return this.fetchJson<CatalogResponse>(url); } /** * Fetch dataset metadata from the catalog */ async getDatasetMetadata(datasetId: string): Promise<DatasetMetadata | undefined> { if (!this.metadataCache.has(datasetId)) { const promise = this.fetchJson<CatalogResponse>( this.buildUrl('/catalog/datasets', { where: `dataset_id = ${quote(datasetId)}`, limit: 1, }) ).then((data) => data.results[0]); this.metadataCache.set(datasetId, promise); } return this.metadataCache.get(datasetId); } /** * Check whether a dataset currently exists in the public catalog */ async datasetExists(datasetId: string): Promise<boolean> { return Boolean(await this.getDatasetMetadata(datasetId)); } /** * Resolve the first matching field name for a dataset */ async resolveField( datasetId: string, candidates: string[] ): Promise<string | undefined> { const metadata = await this.getDatasetMetadata(datasetId); const fields = metadata?.fields ?? []; if (fields.length === 0) { return candidates[0]; } const byNormalizedName = new Map( fields.map((field) => [normalizeText(field.name), field.name] as const) ); for (const candidate of candidates) { const direct = byNormalizedName.get(normalizeText(candidate)); if (direct) { return direct; } } const fieldNames = fields.map((field) => field.name); for (const candidate of candidates) { const normalizedCandidate = normalizeText(candidate); const partial = fieldNames.find((fieldName) => normalizeText(fieldName).includes(normalizedCandidate) ); if (partial) { return partial; } } return candidates[0]; } /** * Build URL with query parameters */ private buildUrl( path: string, params: Record<string, string | number | undefined> ): string { const normalizedPath = path.startsWith('/') ? path.slice(1) : path; const url = new URL(normalizedPath, this.baseUrl); for (const [key, value] of Object.entries(params)) { if (value !== undefined && value !== null && value !== '') { url.searchParams.set(key, String(value)); } } return url.toString(); } /** * Execute HTTP request with retries and timeout handling */ private async fetchJson<T>(url: string, remainingRetries = this.maxRetries): Promise<T> { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); try { const response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json', 'User-Agent': 'mcp-reunion/1.0', }, signal: controller.signal, }); if (!response.ok) { const errorText = await response.text(); if (response.status >= 500 && remainingRetries > 0) { await this.delay(250); return this.fetchJson<T>(url, remainingRetries - 1); } throw new Error( `API error ${response.status}: ${response.statusText}. ${errorText}` ); } return (await response.json()) as T; } catch (error) { if (error instanceof Error) { if (error.name === 'AbortError') { throw new Error(`Request timeout after ${this.timeout}ms`); } if (remainingRetries > 0 && this.isRetryableError(error)) { await this.delay(250); return this.fetchJson<T>(url, remainingRetries - 1); } throw error; } throw new Error('Unknown error occurred'); } finally { clearTimeout(timeoutId); } } private isRetryableError(error: Error): boolean { return /fetch failed|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN/i.test(error.message); } private async delay(ms: number): Promise<void> { await new Promise((resolve) => setTimeout(resolve, ms)); } } // Singleton instance export const client = new ReunionClient();