reunion_search_building_permits
Search non-residential building authorizations (PC, DP, PA) in La Réunion from the Sitadel database. Returns commune, type, dates, applicant, and address.
Instructions
Search non-residential building authorizations from the Sitadel database (Système d'information et de traitement automatisé des données élémentaires sur les logements et les locaux), restricted to La Réunion. Covers permis de construire (PC), déclarations préalables (DP), and permis d'aménager (PA) for non-residential premises (commerce, offices, industry, agriculture, equipment). Returns commune INSEE, type, reference, filing year, authorization date, works start (DOC) and completion (DAACT) dates, project nature code, primary destination, applicant identity, site address, terrain surface. Sorted by authorization date descending.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| commune | No | Commune INSEE code, exact match (e.g. "97411" for Saint-Denis) | |
| year | No | Filing year (4 digits) | |
| type | No | Authorization type: "PC" = Permis de Construire (full construction permit), "DP" = Déclaration Préalable (light works), "PA" = Permis d'Aménager (land development) | |
| limit | No | Max permits to return (1-500, default 100) |
Implementation Reference
- src/modules/urbanism.ts:60-96 (handler)Handler function for reunion_search_building_permits tool. Queries the 'liste-des-permis-de-constuire-creant-des-locaux-non-residentiels-a-la-reunion' dataset from data.regionreunion.com, filtering by commune INSEE, filing year, authorization type (PC/DP/PA), and returns sorted results with permit details.
async ({ commune, year, type, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_PERMITS_NR, { where: buildWhere([ commune ? `comm = ${quote(commune)}` : undefined, year !== undefined ? `an_depot = ${year}` : undefined, type ? `type_dau = ${quote(type)}` : undefined, ]), order_by: 'date_reelle_autorisation DESC', limit, }); return jsonResult({ total_permits: data.total_count, permits: data.results.map((row) => ({ commune_insee: pickString(row, ['comm']), department: pickString(row, ['dep']), type: pickString(row, ['type_dau']), reference: pickString(row, ['num_dau']), filing_year: pickNumber(row, ['an_depot']), authorized_on: pickString(row, ['date_reelle_autorisation']), works_started_on: pickString(row, ['date_reelle_doc']), works_completed_on: pickString(row, ['date_reelle_daact']), project_nature_code: pickNumber(row, ['nature_projet_declaree']), primary_destination_code: pickNumber(row, ['destination_principale']), applicant_name: pickString(row, ['denom_dem']), applicant_city: pickString(row, ['localite_dem']), site_address_street: pickString(row, ['adr_libvoie_ter']), site_postal_code: pickString(row, ['adr_codpost_ter']), site_city: pickString(row, ['adr_localite_ter']), terrain_surface_m2: pickNumber(row, ['superficie_terrain']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to search building permits'); } } ); - src/modules/urbanism.ts:51-96 (registration)Registration of reunion_search_building_permits tool via server.tool() in the registerUrbanismTools function. Defines schema, description, and attaches the handler.
server.tool( 'reunion_search_building_permits', 'Search non-residential building authorizations from the Sitadel database (Système d\'information et de traitement automatisé des données élémentaires sur les logements et les locaux), restricted to La Réunion. Covers permis de construire (PC), déclarations préalables (DP), and permis d\'aménager (PA) for non-residential premises (commerce, offices, industry, agriculture, equipment). Returns commune INSEE, type, reference, filing year, authorization date, works start (DOC) and completion (DAACT) dates, project nature code, primary destination, applicant identity, site address, terrain surface. Sorted by authorization date descending.', { commune: z.string().optional().describe('Commune INSEE code, exact match (e.g. "97411" for Saint-Denis)'), year: z.number().int().optional().describe('Filing year (4 digits)'), type: z.enum(['PC', 'DP', 'PA']).optional().describe('Authorization type: "PC" = Permis de Construire (full construction permit), "DP" = Déclaration Préalable (light works), "PA" = Permis d\'Aménager (land development)'), limit: z.number().int().min(1).max(500).default(100).describe('Max permits to return (1-500, default 100)'), }, async ({ commune, year, type, limit }) => { try { const data = await client.getRecords<RecordObject>(DATASET_PERMITS_NR, { where: buildWhere([ commune ? `comm = ${quote(commune)}` : undefined, year !== undefined ? `an_depot = ${year}` : undefined, type ? `type_dau = ${quote(type)}` : undefined, ]), order_by: 'date_reelle_autorisation DESC', limit, }); return jsonResult({ total_permits: data.total_count, permits: data.results.map((row) => ({ commune_insee: pickString(row, ['comm']), department: pickString(row, ['dep']), type: pickString(row, ['type_dau']), reference: pickString(row, ['num_dau']), filing_year: pickNumber(row, ['an_depot']), authorized_on: pickString(row, ['date_reelle_autorisation']), works_started_on: pickString(row, ['date_reelle_doc']), works_completed_on: pickString(row, ['date_reelle_daact']), project_nature_code: pickNumber(row, ['nature_projet_declaree']), primary_destination_code: pickNumber(row, ['destination_principale']), applicant_name: pickString(row, ['denom_dem']), applicant_city: pickString(row, ['localite_dem']), site_address_street: pickString(row, ['adr_libvoie_ter']), site_postal_code: pickString(row, ['adr_codpost_ter']), site_city: pickString(row, ['adr_localite_ter']), terrain_surface_m2: pickNumber(row, ['superficie_terrain']), })), }); } catch (error) { return errorResult(error instanceof Error ? error.message : 'Failed to search building permits'); } } ); - src/modules/urbanism.ts:54-59 (schema)Zod schema defining input parameters for the tool: commune (optional string), year (optional integer), type (optional enum of PC/DP/PA), limit (integer 1-500, default 100).
{ commune: z.string().optional().describe('Commune INSEE code, exact match (e.g. "97411" for Saint-Denis)'), year: z.number().int().optional().describe('Filing year (4 digits)'), type: z.enum(['PC', 'DP', 'PA']).optional().describe('Authorization type: "PC" = Permis de Construire (full construction permit), "DP" = Déclaration Préalable (light works), "PA" = Permis d\'Aménager (land development)'), limit: z.number().int().min(1).max(500).default(100).describe('Max permits to return (1-500, default 100)'), }, - src/client.ts:33-260 (helper)ReunionClient class providing getRecords() used by the handler to fetch data from the OpenDataSoft API (data.regionreunion.com). Includes caching for referential datasets.
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(); - src/utils/helpers.ts:36-176 (helper)Utility functions used by the handler: buildWhere for constructing ODQL WHERE clauses, quote for escaping strings, pickString/pickNumber for extracting typed values from records, jsonResult/errorResult for formatting tool responses.
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; } /** * Escape a string literal for ODSQL */ export function escapeOdSqlString(value: string): string { return value.replace(/'/g, "''"); } /** * Quote an ODSQL string literal */ export function quote(value: string): string { return `'${escapeOdSqlString(value)}'`; } /** * Format date as YYYY-MM-DD */ export function formatDate(date: Date): string { return date.toISOString().split('T')[0]; } /** * Get today's date as YYYY-MM-DD */ export function today(): string { return formatDate(new Date()); } /** * Calculate days between two dates */ export function daysBetween(date1: string, date2: string): number { const d1 = new Date(date1); const d2 = new Date(date2); const diffTime = d2.getTime() - d1.getTime(); return Math.ceil(diffTime / (1000 * 60 * 60 * 24)); } /** * Pick the first defined value from a record */ 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; } /** * Pick the first boolean-like value from a record */ export function pickBoolean( record: RecordObject, candidates: string[] ): boolean | undefined { const value = pickValue(record, candidates); if (typeof value === 'boolean') { return value; } if (typeof value === 'number') { return value !== 0; } if (typeof value === 'string') { const normalized = value.trim().toLowerCase(); if (['true', '1', 'oui', 'yes'].includes(normalized)) { return true; } if (['false', '0', 'non', 'no'].includes(normalized)) { return false; } } return undefined; } /** * Normalize a string for case-insensitive comparisons */ export function normalizeText(value: string): string { return value .normalize('NFD') .replace(/[\u0300-\u036f]/g, '') .toLowerCase() .trim(); }