reunion_get_tourism_frequentation
Retrieve monthly tourist arrivals to La Réunion since 2017, segmented by purpose of stay (business, leisure, etc.) and total spending in EUR. Useful for tourism monitoring and trend analysis.
Instructions
Monthly tourism frequentation in La Réunion since 2017: external (non-resident) tourist arrivals broken down by purpose of stay — affaires (business), affinitaire (visiting family/friends), agrément (leisure), autres (other) — and total spending in EUR. Each row is one month. Sorted by date descending. Source: IRT (Île de La Réunion Tourisme) via data.regionreunion.com. Useful for tourism-policy monitoring, seasonal-trend analysis, economic-impact studies.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| year | No | Year filter, 4 digits (e.g. "2024") | |
| limit | No | Max months to return (1-200, default 24 = 2 years) |
Implementation Reference
- src/modules/tourism.ts:184-216 (handler)Handler function for 'reunion_get_tourism_frequentation' tool. Fetches monthly tourism frequentation data from the 'frequentation-touristique-mensuelle-a-la-reunion-depuis-2017' dataset and returns it as JSON. Accepts optional 'year' (string) and 'limit' (number, default 24) parameters.
server.tool( 'reunion_get_tourism_frequentation', 'Monthly tourism frequentation in La Réunion since 2017: external (non-resident) tourist arrivals broken down by purpose of stay — affaires (business), affinitaire (visiting family/friends), agrément (leisure), autres (other) — and total spending in EUR. Each row is one month. Sorted by date descending. Source: IRT (Île de La Réunion Tourisme) via data.regionreunion.com. Useful for tourism-policy monitoring, seasonal-trend analysis, economic-impact studies.', { year: z.string().optional().describe('Year filter, 4 digits (e.g. "2024")'), limit: z.number().int().min(1).max(200).default(24).describe('Max months to return (1-200, default 24 = 2 years)'), }, async ({ year, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_FREQUENTATION, { where: buildWhere([year ? `annee = ${quote(year)}` : undefined]), order_by: 'date DESC', limit, }); return jsonResult({ total_months: data.total_count, series: data.results.map((row) => ({ date: pickString(row, ['date']), month: pickString(row, ['mois']), year: pickString(row, ['annee']), external_tourists: pickNumber(row, ['touristes_exterieurs']), business: pickString(row, ['affaires']), family: pickNumber(row, ['affinitaire']), leisure: pickNumber(row, ['agrement']), other: pickNumber(row, ['autres']), spending_eur: pickNumber(row, ['depenses_des_touristes_exterieurs']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch tourism frequentation'); } } ); - src/modules/tourism.ts:187-190 (schema)Zod schema for the tool's input parameters: 'year' is an optional string (4-digit year), 'limit' is an optional integer (1-200, default 24).
{ year: z.string().optional().describe('Year filter, 4 digits (e.g. "2024")'), limit: z.number().int().min(1).max(200).default(24).describe('Max months to return (1-200, default 24 = 2 years)'), }, - src/modules/tourism.ts:184-216 (registration)Registration of the tool via server.tool('reunion_get_tourism_frequentation', ...) inside the registerTourismTools() function.
server.tool( 'reunion_get_tourism_frequentation', 'Monthly tourism frequentation in La Réunion since 2017: external (non-resident) tourist arrivals broken down by purpose of stay — affaires (business), affinitaire (visiting family/friends), agrément (leisure), autres (other) — and total spending in EUR. Each row is one month. Sorted by date descending. Source: IRT (Île de La Réunion Tourisme) via data.regionreunion.com. Useful for tourism-policy monitoring, seasonal-trend analysis, economic-impact studies.', { year: z.string().optional().describe('Year filter, 4 digits (e.g. "2024")'), limit: z.number().int().min(1).max(200).default(24).describe('Max months to return (1-200, default 24 = 2 years)'), }, async ({ year, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_FREQUENTATION, { where: buildWhere([year ? `annee = ${quote(year)}` : undefined]), order_by: 'date DESC', limit, }); return jsonResult({ total_months: data.total_count, series: data.results.map((row) => ({ date: pickString(row, ['date']), month: pickString(row, ['mois']), year: pickString(row, ['annee']), external_tourists: pickNumber(row, ['touristes_exterieurs']), business: pickString(row, ['affaires']), family: pickNumber(row, ['affinitaire']), leisure: pickNumber(row, ['agrement']), other: pickNumber(row, ['autres']), spending_eur: pickNumber(row, ['depenses_des_touristes_exterieurs']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch tourism frequentation'); } } ); - src/utils/helpers.ts:84-138 (helper)Helper functions pickValue, pickString, and pickNumber used by the handler to extract fields from API response records.
export function pickValue<T = unknown>( record: RecordObject, candidates: string[] ): T | undefined { for (const candidate of candidates) { if (candidate in record) { const value = record[candidate]; if (value !== undefined && value !== null) { // OpenDataSoft v2.1 wraps some text fields as single-element arrays // (e.g. com_name → ["Saint-Denis"]). Unwrap so downstream pickers // see the scalar they expect. if (Array.isArray(value) && value.length === 1) { return value[0] as T; } return value as T; } } } return undefined; } /** * Pick the first string-like value from a record */ export function pickString( record: RecordObject, candidates: string[] ): string | undefined { const value = pickValue(record, candidates); if (typeof value === 'string') { return value; } if (typeof value === 'number' || typeof value === 'boolean') { return String(value); } return undefined; } /** * Pick the first numeric value from a record */ export function pickNumber( record: RecordObject, candidates: string[] ): number | undefined { const value = pickValue(record, candidates); if (typeof value === 'number' && Number.isFinite(value)) { return value; } if (typeof value === 'string' && value.trim() !== '') { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : undefined; } return undefined; } - src/client.ts:43-261 (helper)ReunionClient.getRecords method called by the handler to fetch data from the OpenDataSoft API.
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();