reunion_get_housing_overview
Retrieve a comprehensive housing and demographic snapshot of La Réunion, including population, density, age structure, unemployment, poverty, housing units, social housing indicators, and vacancy rates, sorted by publication year.
Instructions
Comprehensive housing and demographic snapshot of La Réunion department from the Banque des Territoires atlas (1 row per publication year). Returns: population, density per km², 10-year population change, age structure (% <20 and ≥60), unemployment rate (T4), poverty rate, total housing units, principal residences, social-housing rate, vacancy rate, individual-housing rate, and social-park-specific indicators (count, average rent EUR/m²/month, average age, energy-poor rate for E/F/G DPE labels). Sorted by publication year descending.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| year | No | Publication year filter, 4 digits (e.g. "2024") | |
| limit | No | Max yearly snapshots to return (1-50, default 20) |
Implementation Reference
- src/modules/housing.ts:20-53 (handler)Handler function for 'reunion_get_housing_overview' tool. Fetches comprehensive housing/demographic data from the 'logements-et-logements-sociaux-dans-les-departements-a-la-reunion' dataset on data.regionreunion.com, returning population, density, age structure, unemployment, poverty, housing units, social housing stats, etc. sorted by publication year descending.
async ({ year, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_HOUSING, { where: buildWhere([year ? `annee_publication = date${quote(`${year}-01-01`)}` : undefined]), order_by: 'annee_publication DESC', limit, }); return jsonResult({ total_snapshots: data.total_count, snapshots: data.results.map((row) => ({ publication_year: pickString(row, ['annee_publication']), department: pickString(row, ['nom_departement']), population: pickNumber(row, ['nombre_d_habitants']), density_per_km2: pickNumber(row, ['densite_de_population_au_km2']), population_change_10y_pct: pickNumber(row, ['variation_de_la_population_sur_10_ans_en']), pct_under_20: pickNumber(row, ['population_de_moins_de_20_ans']), pct_60_plus: pickNumber(row, ['population_de_60_ans_et_plus']), unemployment_rate_pct: pickNumber(row, ['taux_de_chomage_au_t4_en']), poverty_rate_pct: pickNumber(row, ['taux_de_pauvrete_en']), total_housing: pickNumber(row, ['nombre_de_logements']), principal_residences: pickNumber(row, ['nombre_de_residences_principales']), social_housing_rate_pct: pickNumber(row, ['taux_de_logements_sociaux_en']), vacancy_rate_pct: pickNumber(row, ['taux_de_logements_vacants_en']), individual_housing_rate_pct: pickNumber(row, ['taux_de_logements_individuels_en']), social_stock_count: pickNumber(row, ['parc_social_nombre_de_logements']), social_avg_rent_eur_m2: pickNumber(row, ['parc_social_loyer_moyen_en_eur_m2_mois']), social_avg_age_years: pickNumber(row, ['parc_social_age_moyen_du_parc_en_annees']), social_energy_poor_rate_pct: pickNumber(row, ['parc_social_taux_de_logements_energivores_e_f_g_en']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch housing overview'); } } - src/modules/housing.ts:17-19 (schema)Zod schema defining tool inputs: optional year string filter and optional limit (1-50, default 20).
year: z.string().optional().describe('Publication year filter, 4 digits (e.g. "2024")'), limit: z.number().int().min(1).max(50).default(20).describe('Max yearly snapshots to return (1-50, default 20)'), }, - src/modules/housing.ts:13-54 (registration)Registration of the 'reunion_get_housing_overview' tool on the MCP server via the McpServer.tool() call, with name, description, input schema, and handler.
server.tool( 'reunion_get_housing_overview', 'Comprehensive housing and demographic snapshot of La Réunion department from the Banque des Territoires atlas (1 row per publication year). Returns: population, density per km², 10-year population change, age structure (% <20 and ≥60), unemployment rate (T4), poverty rate, total housing units, principal residences, social-housing rate, vacancy rate, individual-housing rate, and social-park-specific indicators (count, average rent EUR/m²/month, average age, energy-poor rate for E/F/G DPE labels). Sorted by publication year descending.', { year: z.string().optional().describe('Publication year filter, 4 digits (e.g. "2024")'), limit: z.number().int().min(1).max(50).default(20).describe('Max yearly snapshots to return (1-50, default 20)'), }, async ({ year, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_HOUSING, { where: buildWhere([year ? `annee_publication = date${quote(`${year}-01-01`)}` : undefined]), order_by: 'annee_publication DESC', limit, }); return jsonResult({ total_snapshots: data.total_count, snapshots: data.results.map((row) => ({ publication_year: pickString(row, ['annee_publication']), department: pickString(row, ['nom_departement']), population: pickNumber(row, ['nombre_d_habitants']), density_per_km2: pickNumber(row, ['densite_de_population_au_km2']), population_change_10y_pct: pickNumber(row, ['variation_de_la_population_sur_10_ans_en']), pct_under_20: pickNumber(row, ['population_de_moins_de_20_ans']), pct_60_plus: pickNumber(row, ['population_de_60_ans_et_plus']), unemployment_rate_pct: pickNumber(row, ['taux_de_chomage_au_t4_en']), poverty_rate_pct: pickNumber(row, ['taux_de_pauvrete_en']), total_housing: pickNumber(row, ['nombre_de_logements']), principal_residences: pickNumber(row, ['nombre_de_residences_principales']), social_housing_rate_pct: pickNumber(row, ['taux_de_logements_sociaux_en']), vacancy_rate_pct: pickNumber(row, ['taux_de_logements_vacants_en']), individual_housing_rate_pct: pickNumber(row, ['taux_de_logements_individuels_en']), social_stock_count: pickNumber(row, ['parc_social_nombre_de_logements']), social_avg_rent_eur_m2: pickNumber(row, ['parc_social_loyer_moyen_en_eur_m2_mois']), social_avg_age_years: pickNumber(row, ['parc_social_age_moyen_du_parc_en_annees']), social_energy_poor_rate_pct: pickNumber(row, ['parc_social_taux_de_logements_energivores_e_f_g_en']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to fetch housing overview'); } } ); - src/modules/index.ts:46-56 (registration)Call to registerHousingTools from index.ts, which is invoked by registerAllTools during server startup.
registerHousingTools(server); registerNationalElectionsTools(server); registerPossessionTools(server); registerSocialTools(server); registerTelecomTools(server); registerTerritoryTools(server); registerTourismTools(server); registerTransportTools(server); registerUrbanismTools(server); registerWeatherTools(server); } - src/client.ts:33-261 (helper)ReunionClient class (singleton instance 'client') used by the handler to call the OpenDataSoft API's getRecords method with the housing dataset ID.
export class ReunionClient { private readonly baseUrl = 'https://data.regionreunion.com/api/explore/v2.1/'; private readonly timeout = 30000; private readonly maxRetries = 2; private readonly metadataCache = new Map<string, Promise<DatasetMetadata | undefined>>(); private readonly recordsCache = new Map<string, { value: unknown; expiresAt: number }>(); /** * Fetch records from a dataset */ 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();