Qdonnars Claude Opus 5 (1M context) commited on
Commit
febc39b
·
1 Parent(s): 3fb80f4

Gradio 6 (transport MCP Streamable HTTP + SSE), sorties JSON compactes, sources réparées, find_territory, page Space

Browse files

- Gradio 5.29 → 6.15.2 : /gradio_api/mcp/ répondait 404 (SSE seul), d'où le 502 des
connecteurs claude.ai / Claude Code ; noms d'outils corrigés (préfixe sans underscore).
- Outils déclarés via gr.api() : schéma dérivé des docstrings, réponses en JSON compact
(plus de repr pydantic « root={...} »), limites et troncature signalées, valeurs numériques.
- get_indicator_details : les sources échouaient toujours (dimension « libelle » inexistante) ;
seules les dimensions listées par /meta sont demandées.
- Recherche insensible aux accents/pluriels avec score ; find_territory (nom → code INSEE/SIREN).
- Interface : accueil, tableaux, bloc de connexion (URL réelle, snippets), exemples ; README carte HF.
- Tests hors ligne sur un backend simulé construit à partir de réponses réelles (17 tests).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

.gitignore CHANGED
@@ -1,8 +1,9 @@
1
  # Environment
2
  .env
 
3
  venv/
4
  __pycache__/
5
- *.pyc
6
 
7
  # IDE
8
  .vscode/
 
1
  # Environment
2
  .env
3
+ .venv/
4
  venv/
5
  __pycache__/
6
+ *.py[cod]
7
 
8
  # IDE
9
  .vscode/
README.md CHANGED
@@ -1,299 +1,120 @@
1
  ---
2
- title: MCP Indicators
3
- emoji: 📉
4
  colorFrom: blue
5
- colorTo: pink
6
  sdk: gradio
7
- sdk_version: 5.29.0
 
8
  app_file: app.py
9
  pinned: false
 
 
 
 
 
 
 
 
10
  ---
11
 
12
- # MCP Server - Indicateurs Territoriaux de Transition Écologique
13
 
14
- Serveur MCP (Model Context Protocol) exposant l'API du **Hub d'Indicateurs Territoriaux de Transition Écologique** (CGDD/Ministère de la Transition Écologique).
15
 
16
- Ce serveur permet à des LLMs (Claude, GPT, etc.) d'interroger les données environnementales territoriales françaises.
17
 
18
- ## Outils MCP disponibles
19
 
20
- ### 1. `list_indicators`
21
- Liste tous les indicateurs avec filtres optionnels.
22
 
23
- **Paramètres :**
24
- - `thematique` (optionnel) : Filtre par thématique FNV ("mieux se déplacer", "mieux se loger"...)
25
- - `maille` (optionnel) : Filtre par niveau géographique ("region", "departement", "epci", "commune")
26
 
27
- ### 2. `get_indicator_details`
28
- Retourne les détails complets d'un indicateur (description, méthode de calcul, sources).
29
-
30
- **Paramètres :**
31
- - `indicator_id` : ID numérique de l'indicateur
32
-
33
- ### 3. `query_indicator_data`
34
- Interroge les données d'un indicateur pour un territoire.
35
-
36
- **Paramètres :**
37
- - `indicator_id` : ID de l'indicateur
38
- - `geographic_level` : "region" | "departement" | "epci" | "commune"
39
- - `geographic_code` (optionnel) : Code INSEE du territoire
40
- - `year` (optionnel) : Année des données
41
-
42
- ### 4. `search_indicators`
43
- Recherche d'indicateurs par mots-clés.
44
-
45
- **Paramètres :**
46
- - `query` : Termes de recherche (recherche dans libellé et description)
47
-
48
- ## Installation
49
-
50
- ### Prérequis
51
-
52
- - Python >= 3.10
53
- - Un token d'authentification pour l'API Indicateurs
54
-
55
- ### Installation locale
56
-
57
- ```bash
58
- # Cloner le dépôt
59
- git clone https://github.com/your-repo/mcp-indicateurs-te.git
60
- cd mcp-indicateurs-te
61
-
62
- # Créer un environnement virtuel
63
- python -m venv venv
64
- source venv/bin/activate # Linux/Mac
65
- # ou: venv\Scripts\activate # Windows
66
-
67
- # Installer les dépendances
68
- pip install -r requirements.txt
69
-
70
- # Configurer le token
71
- cp .env.example .env
72
- # Éditer .env et ajouter votre token INDICATEURS_TE_TOKEN
73
-
74
- # Lancer le serveur
75
- python app.py
76
- ```
77
-
78
- Le serveur sera accessible sur `http://localhost:7860`.
79
-
80
- ### Déploiement HuggingFace Spaces
81
-
82
- 1. Créer un nouveau Space avec le SDK Gradio
83
- 2. Pousser le code vers le Space
84
- 3. Configurer le secret `INDICATEURS_TE_TOKEN` dans les paramètres du Space
85
-
86
- ## Configuration MCP Client
87
-
88
- ### Claude Desktop
89
-
90
- Ajouter dans `claude_desktop_config.json` :
91
-
92
- ```json
93
- {
94
- "mcpServers": {
95
- "indicateurs-te": {
96
- "url": "https://YOUR-SPACE.hf.space/gradio_api/mcp/"
97
- }
98
- }
99
- }
100
- ```
101
-
102
- ### Cursor
103
-
104
- Ajouter dans les paramètres MCP de Cursor :
105
-
106
- ```json
107
- {
108
- "mcpServers": {
109
- "indicateurs-te": {
110
- "url": "http://localhost:7860/gradio_api/mcp/"
111
- }
112
- }
113
- }
114
  ```
115
-
116
- ### Avec mcp-remote (pour clients ne supportant pas HTTP)
117
-
118
- ```json
119
- {
120
- "mcpServers": {
121
- "indicateurs-te": {
122
- "command": "npx",
123
- "args": [
124
- "mcp-remote",
125
- "http://localhost:7860/gradio_api/mcp/"
126
- ]
127
- }
128
- }
129
- }
130
  ```
131
 
132
- ## Architecture de l'API (validée par tests)
 
 
 
 
 
133
 
134
- ### Convention de nommage des cubes
135
 
136
- Les cubes de **données** suivent le format : `{thematique}_{maille}`
137
 
138
- | Suffixe | Maille |
139
- |---------|--------|
140
- | `_com` | Commune |
141
- | `_epci` | EPCI |
142
- | `_dpt` | Département |
143
- | `_reg` | Région |
144
 
145
- Exemples :
146
- - `conso_enaf_com` → Consommation ENAF, maille commune
147
- - `surface_bio_dpt` → Surface bio, maille département
148
 
149
- ### Les measures contiennent l'ID de l'indicateur
 
 
 
 
 
 
150
 
151
- Format : `{cube_name}.id_{indicator_id}`
152
 
153
- Exemples :
154
- - `conso_enaf_com.id_611` → Indicateur 611 dans le cube conso_enaf_com
155
- - `surface_bio_dpt.id_606` → Indicateur 606 dans le cube surface_bio_dpt
156
 
157
- ### Dimensions géographiques (standardisées)
158
 
159
- | Dimension | Description |
160
- |-----------|-------------|
161
- | `geocode_commune` | Code INSEE commune (5 chiffres) |
162
- | `libelle_commune` | Nom de la commune |
163
- | `geocode_epci` | Code SIREN EPCI (9 chiffres) |
164
- | `libelle_epci` | Nom de l'EPCI |
165
- | `geocode_departement` | Code département (2-3 car.) |
166
- | `libelle_departement` | Nom du département |
167
- | `geocode_region` | Code région (2 chiffres) |
168
- | `libelle_region` | Nom de la région |
169
 
170
- ### Dimensions temporelles
171
-
172
- | Dimension | Description |
173
- |-----------|-------------|
174
- | `annee` | Année (string : "2020") |
175
 
176
- ## Exemples d'utilisation
 
177
 
178
- ### Via un LLM
 
179
 
 
 
 
180
  ```
181
- Utilisateur: Quels indicateurs sur la consommation d'espace ?
182
-
183
- LLM: [appelle search_indicators("consommation espace")]
184
- Voici les indicateurs disponibles :
185
- - ID 611: Consommation d'espaces naturels, agricoles et forestiers
186
 
187
- Utilisateur: Détails sur l'indicateur 611
188
 
189
- LLM: [appelle get_indicator_details("611")]
190
- L'indicateur 611 mesure la consommation d'ENAF...
191
- Mailles disponibles: commune, epci, departement, region
 
 
 
 
 
 
192
 
193
- Utilisateur: Valeurs pour la région PACA en 2020
194
 
195
- LLM: [appelle query_indicator_data("611", "region", "93", "2020")]
196
- Pour PACA (code 93) en 2020 : 1737.29 ha
197
- ```
198
 
199
- ### Exemple de requête Cube.js validée
200
-
201
- ```json
202
- {
203
- "query": {
204
- "measures": ["conso_enaf_com.id_611"],
205
- "dimensions": [
206
- "conso_enaf_com.libelle_region",
207
- "conso_enaf_com.annee"
208
- ],
209
- "filters": [
210
- {
211
- "member": "conso_enaf_com.geocode_region",
212
- "operator": "equals",
213
- "values": ["93"]
214
- }
215
- ],
216
- "limit": 100
217
- }
218
- }
219
- ```
220
 
221
- ## Codes géographiques INSEE
222
 
223
- | Niveau | Format | Exemples |
224
- |--------|--------|----------|
225
- | Région | 2 chiffres | 93 (PACA), 11 (Île-de-France), 75 (Nouvelle-Aquitaine), 84 (Auvergne-Rhône-Alpes) |
226
  | Département | 2-3 caractères | 13, 2A, 974 |
227
- | EPCI | 9 chiffres (SIREN) | 200054807 |
228
- | Commune | 5 chiffres | 75056 (Paris), 13055 (Marseille) |
229
-
230
- ## Variables d'environnement
231
-
232
- | Variable | Description | Défaut |
233
- |----------|-------------|--------|
234
- | `INDICATEURS_TE_TOKEN` | Token JWT pour l'API | (requis) |
235
- | `INDICATEURS_TE_BASE_URL` | URL de base de l'API | `https://api.indicateurs.ecologie.gouv.fr` |
236
- | `CACHE_REFRESH_SECONDS` | Intervalle de rafraîchissement du cache | 3600 |
237
-
238
- ## Architecture technique
239
-
240
- ```
241
- ┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
242
- │ MCP Client │────▶│ Gradio App │────▶│ Cube.js API │
243
- │ (Claude, etc.) │ │ (MCP Server) │ │ (Indicateurs) │
244
- └─────────────────┘ └──────────────────┘ └─────────────────┘
245
- │
246
- ┌──────┴──────┐
247
- │ CubeResolver │
248
- │ + Cache │
249
- └─────────────┘
250
- ```
251
-
252
- - **Gradio** : Interface web + endpoint SSE MCP
253
- - **CubeResolver** : Mapping indicator_id → cube_name via parsing /meta
254
- - **Cache** : Métadonnées des indicateurs chargées au démarrage
255
-
256
- ## Structure du projet
257
-
258
- ```
259
- ├── src/
260
- │ ├── __init__.py # Package init
261
- │ ├── api_client.py # Client HTTP Cube.js async
262
- │ ├── cube_resolver.py # Logique find_cube_for_indicator
263
- │ ├── cache.py # Cache des métadonnées
264
- │ ├── models.py # Modèles Pydantic
265
- │ └── tools.py # Implémentation des 4 outils MCP
266
- ├── app.py # Point d'entrée Gradio
267
- ├── requirements.txt # Dépendances
268
- └── .env.example # Template de configuration
269
- ```
270
-
271
- ## Développement
272
-
273
- ### Test avec MCP Inspector
274
-
275
- ```bash
276
- # Lancer le serveur
277
- python app.py
278
-
279
- # Dans un autre terminal
280
- npx @modelcontextprotocol/inspector
281
- # Connecter à http://localhost:7860/gradio_api/mcp/
282
- ```
283
-
284
- ### Points d'attention
285
-
286
- 1. **Cache du /meta** : ~100+ cubes, chargé une fois au startup
287
- 2. **Mapping indicator_id → cube** : Parcours des measures de chaque cube
288
- 3. **Mailles non uniformes** : Vérifier `mailles_disponibles` avant de requêter
289
- 4. **Valeurs string** : Les filtres Cube.js attendent des strings (`"93"` pas `93`)
290
 
291
- ## Ressources
292
 
293
- - [Documentation MCP](https://modelcontextprotocol.io/)
294
- - [Gradio MCP Guide](https://gradio.app/guides/building-mcp-server-with-gradio)
295
- - [API Cube.js](https://cube.dev/docs/rest-api)
296
- - [Portail Indicateurs](https://ecologie.data.gouv.fr/indicators)
297
 
298
  ## Licence
299
 
 
1
  ---
2
+ title: Indicateurs TE MCP
3
+ emoji: 📊
4
  colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ sdk_version: 6.15.2
8
+ python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
11
+ license: mit
12
+ short_description: Serveur MCP — indicateurs territoriaux transition écologique
13
+ tags:
14
+ - mcp-server
15
+ - transition-ecologique
16
+ - indicateurs-territoriaux
17
+ - open-data
18
+ - france
19
  ---
20
 
21
+ # 📊 Indicateurs territoriaux de transition écologique — serveur MCP
22
 
23
+ **Interrogez les indicateurs environnementaux des territoires français (régions, départements, EPCI, communes) directement depuis votre assistant IA.**
24
 
25
+ Ce Space expose un serveur [MCP](https://modelcontextprotocol.io) (Model Context Protocol) que Claude, ChatGPT, Cursor ou tout autre client compatible peut interroger en langage naturel. Il s'appuie sur l'API du [Hub d'indicateurs territoriaux de la transition écologique](https://ecologie.data.gouv.fr/indicators) (CGDD · Ministère de la Transition écologique) : ~170 indicateurs — émissions de gaz à effet de serre, consommation d'espaces, agriculture biologique, mobilité, logement, déchets… — avec les valeurs par territoire et par année, les définitions, les méthodes de calcul et les sources.
26
 
27
+ > « Quelle est l'évolution de la consommation d'espaces naturels en PACA depuis 2015 ? » → l'assistant appelle `search_indicators`, retient l'indicateur 611, interroge `query_indicator_data(611, region, 93)` et vous restitue la série avec son unité et sa source.
28
 
29
+ ## Connecter le serveur en une minute
 
30
 
31
+ URL du serveur (transport *Streamable HTTP*, sans authentification côté client) :
 
 
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  ```
34
+ https://ekimetrics-mcp-indicators.hf.space/gradio_api/mcp/
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  ```
36
 
37
+ | Client | Comment faire |
38
+ |---|---|
39
+ | **Claude Code** | `claude mcp add --transport http indicateurs-te https://ekimetrics-mcp-indicators.hf.space/gradio_api/mcp/` |
40
+ | **Claude.ai / Claude Desktop** | Paramètres → *Connecteurs* → *Ajouter un connecteur personnalisé* → coller l'URL |
41
+ | **Cursor, Windsurf, VS Code…** | Dans `mcp.json` : `{"mcpServers": {"indicateurs-te": {"url": "https://ekimetrics-mcp-indicators.hf.space/gradio_api/mcp/"}}}` |
42
+ | **Clients SSE uniquement** | `https://ekimetrics-mcp-indicators.hf.space/gradio_api/mcp/sse` |
43
 
44
+ Schéma des outils : <https://ekimetrics-mcp-indicators.hf.space/gradio_api/mcp/schema>
45
 
46
+ ### À essayer une fois connecté
47
 
48
+ - « Quelle est l'évolution de la consommation d'espaces naturels en PACA depuis 2015 ? »
49
+ - « Compare les émissions de gaz à effet de serre par habitant des départements bretons. »
50
+ - « Quelle part de l'agriculture bio dans la Métropole de Lyon ? »
51
+ - « Quels indicateurs de mobilité existent à l'échelle communale ? »
 
 
52
 
53
+ ## Outils
 
 
54
 
55
+ | Outil | Rôle |
56
+ |---|---|
57
+ | `search_indicators` | **Point d'entrée.** Recherche par mots-clés (accents, casse et pluriels ignorés), meilleurs résultats d'abord, 30 max. |
58
+ | `list_indicators` | Catalogue complet, filtrable par thématique France Nation Verte (`déplacer`, `loger`, `produire`…) et par maille disponible. |
59
+ | `get_indicator_details` | Métadonnées d'un indicateur : définition, méthode de calcul, années et mailles disponibles, taux de complétude, sources. |
60
+ | `query_indicator_data` | Valeurs d'un indicateur pour un territoire (ou tous les territoires d'une maille), filtrables par année ; `limit` (100 par défaut, 500 max) et signalement de troncature. |
61
+ | `find_territory` | Code officiel d'un territoire à partir de son nom (« Métropole de Lyon » → SIREN 200046977, « Bouches-du-Rhône » → 13). |
62
 
63
+ Toutes les réponses sont en JSON compact ; les erreurs sont renvoyées avec un `hint` exploitable par l'assistant (niveau indisponible, année absente, code mal formé…).
64
 
65
+ ## Interface web
 
 
66
 
67
+ La page du Space permet de tester chaque outil (tableaux + JSON brut tel que reçu par l'assistant) et fournit les extraits de configuration pour chaque client.
68
 
69
+ ## Développement local
 
 
 
 
 
 
 
 
 
70
 
71
+ ```bash
72
+ git clone https://huggingface.co/spaces/Ekimetrics/MCP_indicators
73
+ cd MCP_indicators
74
+ python -m venv .venv && source .venv/bin/activate
75
+ pip install -r requirements.txt
76
 
77
+ # Tests hors ligne (backend simulé, aucun token requis)
78
+ python -m unittest discover -s tests -v
79
 
80
+ # Serveur sur le backend simulé
81
+ GRADIO_SERVER_PORT=7861 python tests/run_fake_server.py
82
 
83
+ # Serveur réel : token de l'API dans .env (voir .env.example)
84
+ cp .env.example .env # puis renseigner INDICATEURS_TE_TOKEN
85
+ python app.py # http://127.0.0.1:7860 — MCP : http://127.0.0.1:7860/gradio_api/mcp/
86
  ```
 
 
 
 
 
87
 
88
+ Structure :
89
 
90
+ | Fichier | Rôle |
91
+ |---|---|
92
+ | `app.py` | Application Gradio : déclaration des outils MCP (`gr.api`) et interface de démonstration |
93
+ | `src/tools.py` | Implémentation des 5 outils (formats de sortie, limites, messages d'erreur) |
94
+ | `src/api_client.py` | Client HTTP Cube.js (authentification, `/meta`, `/load`) |
95
+ | `src/cube_resolver.py` | Correspondance indicateur → cube de données par maille, à partir de `/meta` |
96
+ | `src/cache.py` | Cache des métadonnées (rafraîchi toutes les heures) et recherche |
97
+ | `src/models.py` | Modèles Pydantic, constantes géographiques |
98
+ | `tests/` | Backend simulé (`fake_api.py`, construit sur des réponses réelles) et tests |
99
 
100
+ ## Déploiement Hugging Face Spaces
101
 
102
+ Pousser le dépôt sur le Space (SDK Gradio) et définir le secret **`INDICATEURS_TE_TOKEN`** dans *Settings → Variables and secrets*. Variables optionnelles : `INDICATEURS_TE_BASE_URL` (défaut `https://api.indicateurs.ecologie.gouv.fr`), `CACHE_REFRESH_SECONDS` (défaut 3600).
 
 
103
 
104
+ ## Architecture de l'API interrogée
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
+ Les cubes de **données** suivent le format `{thematique}_{maille}` (`conso_enaf_com`, `surface_bio_dpt`…) ; chaque indicateur y est une mesure `{cube}.id_{indicator_id}` ; les dimensions géographiques sont `geocode_{maille}` / `libelle_{maille}` et la dimension temporelle `annee` (chaîne). Un même cube peut exposer plusieurs mailles. Les métadonnées viennent des cubes `indicateur_metadata` et `indicateur_x_source_metadata`, dont les dimensions réellement disponibles sont lues dans `/meta` au démarrage.
107
 
108
+ | Niveau | Format du code | Exemples |
109
+ |---|---|---|
110
+ | Région | 2 chiffres | 93 (PACA), 11 (Île-de-France), 84 (Auvergne-Rhône-Alpes) |
111
  | Département | 2-3 caractères | 13, 2A, 974 |
112
+ | EPCI | SIREN, 9 chiffres | 200046977 (Métropole de Lyon) |
113
+ | Commune | INSEE, 5 chiffres | 75056 (Paris), 13055 (Marseille) |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
+ ## Avertissement
116
 
117
+ Démonstration réalisée par [Ekimetrics](https://ekimetrics.com). Les valeurs sont restituées telles que publiées par le Hub d'indicateurs ; consultez les métadonnées (`get_indicator_details`) pour la méthode de calcul, la couverture et les sources avant toute interprétation.
 
 
 
118
 
119
  ## Licence
120
 
app.py CHANGED
@@ -1,220 +1,319 @@
1
- """Gradio MCP Server for Indicateurs Territoriaux de Transition Écologique.
2
-
3
- This application exposes 4 MCP tools for querying French territorial
4
- ecological indicators via the Cube.js API.
5
-
6
- Tools:
7
- - list_indicators: List all indicators with optional filters
8
- - get_indicator_details: Get detailed info about a specific indicator
9
- - query_indicator_data: Query data values for a territory
10
- - search_indicators: Search indicators by keywords
11
-
12
- Usage:
13
- Run locally:
14
- python app.py
15
-
16
- Deploy on HuggingFace Spaces:
17
- Push to a Space with Gradio SDK configured.
18
-
19
- Connect as MCP Server:
20
- URL: http://your-server:7860/gradio_api/mcp/
21
- """
22
 
23
- import os
24
- import logging
25
- import gradio as gr
26
- from dotenv import load_dotenv
27
 
 
 
28
 
29
- # =============================================================================
30
- # Logging Configuration - Filter out non-critical ASGI errors
31
- # =============================================================================
32
- class ASGIErrorFilter(logging.Filter):
33
- """Filter to suppress known non-critical ASGI/MCP errors.
34
-
35
- These errors occur when external clients send malformed requests
36
- or when health checks hit MCP endpoints. They don't affect functionality.
37
- """
38
-
39
- SUPPRESSED_MESSAGES = [
40
- "Exception in ASGI application",
41
- "'NoneType' object is not callable",
42
- "Exception Group Traceback",
43
- ]
44
-
45
- def filter(self, record: logging.LogRecord) -> bool:
46
- """Return False to suppress the log record."""
47
- message = record.getMessage()
48
- for suppressed in self.SUPPRESSED_MESSAGES:
49
- if suppressed in message:
50
- return False
51
- return True
52
 
 
53
 
54
- # Apply filter to uvicorn error logger
55
- uvicorn_error_logger = logging.getLogger("uvicorn.error")
56
- uvicorn_error_logger.addFilter(ASGIErrorFilter())
57
 
58
- # Also filter the root logger for starlette errors
59
- logging.getLogger("starlette").addFilter(ASGIErrorFilter())
60
 
61
- # Load environment variables
62
  load_dotenv()
63
 
64
- # Import tools
65
- from src.tools import (
66
- list_indicators,
67
  get_indicator_details,
 
68
  query_indicator_data,
69
  search_indicators,
70
  )
71
- from src.models import GEOGRAPHIC_LEVELS
72
 
73
- # Check if token is configured
74
  if not os.getenv("INDICATEURS_TE_TOKEN"):
75
  print("WARNING: INDICATEURS_TE_TOKEN not set. API calls will fail.")
76
- print("Set the token in .env file or as environment variable.")
77
-
78
-
79
- # Create individual interfaces for each tool
80
- list_interface = gr.Interface(
81
- fn=list_indicators,
82
- inputs=[
83
- gr.Textbox(
84
- label="Thématique FNV",
85
- placeholder="Ex: mieux se déplacer, mieux se loger...",
86
- info="Filtre par thématique France Nation Verte (recherche partielle)",
87
- ),
88
- gr.Dropdown(
89
- choices=[""] + GEOGRAPHIC_LEVELS,
90
- label="Maille géographique",
91
- info="Filtre par niveau géographique disponible",
92
- ),
93
- ],
94
- outputs=gr.JSON(label="Indicateurs"),
95
- title="Lister les indicateurs",
96
- description="Liste tous les indicateurs disponibles avec filtres optionnels.",
97
- api_name="list_indicators",
98
- )
99
 
100
- details_interface = gr.Interface(
101
- fn=get_indicator_details,
102
- inputs=[
103
- gr.Textbox(
104
- label="ID de l'indicateur",
105
- placeholder="Ex: 611",
106
- info="Identifiant numérique de l'indicateur",
107
- ),
108
- ],
109
- outputs=gr.JSON(label="Détails"),
110
- title="Détails d'un indicateur",
111
- description="Retourne les métadonnées complètes et les sources d'un indicateur.",
112
- api_name="get_indicator_details",
113
- )
114
 
115
- query_interface = gr.Interface(
116
- fn=query_indicator_data,
117
- inputs=[
118
- gr.Textbox(
119
- label="ID de l'indicateur",
120
- placeholder="Ex: 611",
121
- info="Identifiant numérique de l'indicateur",
122
- ),
123
- gr.Dropdown(
124
- choices=GEOGRAPHIC_LEVELS,
125
- label="Niveau géographique",
126
- value="region",
127
- info="Maille territoriale à interroger",
128
- ),
129
- gr.Textbox(
130
- label="Code INSEE",
131
- placeholder="Ex: 93 (PACA), 13 (Bouches-du-Rhône)...",
132
- info="Code du territoire (optionnel)",
133
- ),
134
- gr.Textbox(
135
- label="Année",
136
- placeholder="Ex: 2020",
137
- info="Année des données (optionnel)",
138
- ),
139
- ],
140
- outputs=gr.JSON(label="Données"),
141
- title="Interroger les données",
142
- description="Récupère les valeurs d'un indicateur pour un territoire donné.",
143
- api_name="query_indicator_data",
144
- )
145
 
146
- search_interface = gr.Interface(
147
- fn=search_indicators,
148
- inputs=[
149
- gr.Textbox(
150
- label="Recherche",
151
- placeholder="Ex: consommation espace, surface bio, émissions CO2...",
152
- info="Mots-clés à rechercher dans le nom et la description",
153
- ),
154
- ],
155
- outputs=gr.JSON(label="Résultats"),
156
- title="Rechercher des indicateurs",
157
- description="Recherche des indicateurs par mots-clés.",
158
- api_name="search_indicators",
159
- )
160
 
161
- # Combine all interfaces into a tabbed interface
162
- demo = gr.TabbedInterface(
163
- interface_list=[
164
- list_interface,
165
- search_interface,
166
- details_interface,
167
- query_interface,
168
- ],
169
- tab_names=[
170
- "Lister",
171
- "Rechercher",
172
- "Détails",
173
- "Données",
174
- ],
175
- title="MCP Server - Indicateurs Territoriaux de Transition Écologique",
176
- )
177
 
178
- # Add a description block
179
- with demo:
180
- gr.Markdown(
181
- """
182
- ---
183
- ### Connexion MCP
184
-
185
- Pour utiliser ce serveur comme outil MCP dans Claude Desktop, Cursor ou autre client MCP :
186
-
187
- ```json
188
- {
189
- "mcpServers": {
190
- "indicateurs-te": {
191
- "url": "https://YOUR-SPACE.hf.space/gradio_api/mcp/"
192
- }
193
- }
194
- }
195
- ```
196
-
197
- ### Structure des données
198
-
199
- Les cubes de données suivent le format `{thematique}_{maille}` :
200
- - `conso_enaf_com` → Consommation ENAF, maille commune
201
- - `surface_bio_dpt` → Surface bio, maille département
202
-
203
- Les measures contiennent l'ID de l'indicateur : `{cube}.id_{indicator_id}`
204
-
205
- ### API Cube.js
206
-
207
- Ce serveur interroge l'API du Hub d'Indicateurs Territoriaux du Ministère de la Transition Écologique.
208
-
209
- - Documentation : [ecologie.data.gouv.fr/indicators](https://ecologie.data.gouv.fr/indicators)
210
- - API : `https://api.indicateurs.ecologie.gouv.fr`
211
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
 
215
  if __name__ == "__main__":
216
- demo.launch(
217
- mcp_server=True,
218
- server_name="0.0.0.0",
219
- server_port=7860,
220
- )
 
 
 
1
+ """Serveur MCP « Indicateurs territoriaux de transition écologique » — Gradio / Hugging Face Spaces.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ Les outils MCP sont déclarés avec gr.api() : leur schéma vient des signatures Python et
4
+ des docstrings, indépendamment des composants de l'interface. Gradio ≥ 6 expose les deux
5
+ transports MCP (Streamable HTTP sur /gradio_api/mcp/ et SSE sur /gradio_api/mcp/sse).
6
+ L'interface web sert de vitrine et de banc d'essai ; ses événements sont privés.
7
 
8
+ Outils : search_indicators, list_indicators, get_indicator_details, query_indicator_data,
9
+ find_territory.
10
 
11
+ Configuration : INDICATEURS_TE_TOKEN (secret du Space), voir .env.example.
12
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ from __future__ import annotations
15
 
16
+ import json
17
+ import os
 
18
 
19
+ import gradio as gr
20
+ from dotenv import load_dotenv
21
 
 
22
  load_dotenv()
23
 
24
+ from src.models import GEOGRAPHIC_LEVELS # noqa: E402
25
+ from src.tools import ( # noqa: E402
26
+ find_territory,
27
  get_indicator_details,
28
+ list_indicators,
29
  query_indicator_data,
30
  search_indicators,
31
  )
 
32
 
 
33
  if not os.getenv("INDICATEURS_TE_TOKEN"):
34
  print("WARNING: INDICATEURS_TE_TOKEN not set. API calls will fail.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ SPACE_HOST = os.getenv("SPACE_HOST") # renseigné par Hugging Face Spaces
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ def _is_hf_space() -> bool:
40
+ return os.getenv("SYSTEM") == "spaces" or os.getenv("SPACE_ID") is not None
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ def _base_url() -> str:
44
+ if SPACE_HOST:
45
+ return f"https://{SPACE_HOST}"
46
+ return f"http://127.0.0.1:{os.environ.get('GRADIO_SERVER_PORT', '7860')}"
47
+
48
+
49
+ MCP_URL = f"{_base_url()}/gradio_api/mcp/"
50
+ MCP_SSE_URL = f"{MCP_URL}sse"
51
+
52
+ LEVEL_CHOICES = [("Région", "region"), ("Département", "departement"), ("EPCI", "epci"), ("Commune", "commune")]
53
+ LEVEL_CHOICES_ALL = [("Tous niveaux", "")] + LEVEL_CHOICES
54
+
55
+ ACCUEIL = """
56
+ # 📊 Indicateurs territoriaux de transition écologique — serveur MCP
57
+
58
+ **Interrogez les indicateurs environnementaux des territoires français (régions, départements,
59
+ EPCI, communes) directement depuis votre assistant IA.**
60
+
61
+ Ce serveur [MCP](https://modelcontextprotocol.io) donne à Claude, ChatGPT, Cursor ou tout autre
62
+ client compatible l'accès aux ~170 indicateurs du
63
+ [Hub d'indicateurs territoriaux de la transition écologique](https://ecologie.data.gouv.fr/indicators)
64
+ (CGDD · Ministère de la Transition écologique) : émissions de gaz à effet de serre, consommation
65
+ d'espaces, agriculture bio, mobilité, logement… avec les valeurs par territoire et par année,
66
+ les définitions, les méthodes de calcul et les sources.
67
+
68
+ Testez les outils ci-dessous, ou connectez le serveur à votre assistant en une minute.
69
+ """
70
+
71
+ CONNEXION = """
72
+ ### 🔌 Connecter à votre assistant
73
+
74
+ Même URL pour tous les clients (transport *Streamable HTTP*, sans authentification côté client) :
75
+ """
76
+
77
+ PROMPTS = """
78
+ ### 💬 À essayer une fois connecté
79
+
80
+ - « Quelle est l'évolution de la consommation d'espaces naturels en PACA depuis 2015 ? »
81
+ - « Compare les émissions de gaz à effet de serre par habitant des départements bretons. »
82
+ - « Quelle part de l'agriculture bio dans la Métropole de Lyon ? »
83
+ - « Quels indicateurs de mobilité existent à l'échelle communale ? »
84
+ """
85
+
86
+ PIED = f"""
87
+ <small>
88
+
89
+ **Outils MCP** : `search_indicators` · `list_indicators` · `get_indicator_details` ·
90
+ `query_indicator_data` · `find_territory` — schéma : [{MCP_URL}schema]({MCP_URL}schema)
91
+
92
+ Démonstration réalisée par [Ekimetrics](https://ekimetrics.com). Données : Hub d'indicateurs
93
+ territoriaux de la transition écologique (CGDD / Ministère de la Transition écologique), API
94
+ `api.indicateurs.ecologie.gouv.fr`. Les valeurs sont restituées telles que publiées par le Hub ;
95
+ consultez les métadonnées (`get_indicator_details`) pour la méthode de calcul, la couverture et
96
+ les sources avant toute interprétation.
97
+
98
+ </small>
99
+ """
100
+
101
+ SNIPPET_CLAUDE_CODE = f"claude mcp add --transport http indicateurs-te {MCP_URL}"
102
+ SNIPPET_JSON = f"""{{
103
+ "mcpServers": {{
104
+ "indicateurs-te": {{
105
+ "url": "{MCP_URL}"
106
+ }}
107
+ }}
108
+ }}"""
109
+ SNIPPET_PYTHON = f"""from mcp import ClientSession
110
+ from mcp.client.streamable_http import streamablehttp_client
111
+
112
+ async with streamablehttp_client("{MCP_URL}") as (read, write, _):
113
+ async with ClientSession(read, write) as session:
114
+ await session.initialize()
115
+ result = await session.call_tool(
116
+ "search_indicators", {{"query": "consommation espace"}}
117
+ )
118
+ print(result.content[0].text)"""
119
+
120
+
121
+ # --------------------------------------------------------------------------- UI helpers
122
+
123
+ _LIST_COLUMNS = ["id", "libelle", "unite", "mailles", "thematique"]
124
+ _LIST_WIDTHS = ["7%", "43%", "10%", "22%", "18%"]
125
+
126
+
127
+ def _indicators_table(payload: dict) -> list[list]:
128
+ return [
129
+ [i.get("id"), i.get("libelle"), i.get("unite"), ", ".join(i.get("mailles") or []), i.get("thematique")]
130
+ for i in payload.get("indicators") or []
131
+ ]
132
+
133
+
134
+ def _status(payload: dict, ok: str) -> str:
135
+ if "error" in payload:
136
+ msg = f"⚠️ **{payload['error']}**"
137
+ if payload.get("hint"):
138
+ msg += f" \n_{payload['hint']}_"
139
+ return msg
140
+ if payload.get("hint"):
141
+ return f"{ok} \nℹ️ {payload['hint']}"
142
+ return ok
143
+
144
+
145
+ async def _ui_search(query: str):
146
+ raw = await search_indicators(query)
147
+ payload = json.loads(raw)
148
+ status = _status(payload, f"**{payload.get('total_count', 0)} indicateur(s)**" + (" (30 premiers)" if payload.get("truncated") else ""))
149
+ return status, _indicators_table(payload), raw
150
+
151
+
152
+ async def _ui_list(thematique: str, maille: str):
153
+ raw = await list_indicators(thematique, maille)
154
+ payload = json.loads(raw)
155
+ status = _status(payload, f"**{payload.get('count', 0)} indicateur(s)**")
156
+ return status, _indicators_table(payload), raw
157
+
158
+
159
+ async def _ui_details(indicator_id: str):
160
+ raw = await get_indicator_details(indicator_id)
161
+ payload = json.loads(raw)
162
+ if "error" in payload:
163
+ return _status(payload, ""), None
164
+ m = payload["metadata"]
165
+ lines = [
166
+ f"### {m.get('libelle')} (id {m.get('id')})",
167
+ f"**Unité :** {m.get('unite') or '—'} · **Thème :** {m.get('thematique') or '—'} · "
168
+ f"**Couverture :** {m.get('couverture_geographique') or '—'}",
169
+ f"**Mailles :** {', '.join(m.get('mailles_disponibles') or [])} · "
170
+ f"**Années :** {', '.join(m.get('annees_disponibles') or []) or '—'}",
171
+ ]
172
+ if m.get("description"):
173
+ lines.append(m["description"])
174
+ if m.get("methode_calcul"):
175
+ lines.append(f"**Méthode de calcul :** {m['methode_calcul']}")
176
+ if payload.get("sources"):
177
+ src = "; ".join(
178
+ f"{s.get('producteur_source') or s.get('nom_source')}" + (f" ([lien]({s['lien_page']}))" if s.get("lien_page") else "")
179
+ for s in payload["sources"]
180
+ )
181
+ lines.append(f"**Sources :** {src}")
182
+ if payload.get("sources_warning"):
183
+ lines.append(f"ℹ️ {payload['sources_warning']}")
184
+ return "\n\n".join(lines), payload
185
+
186
+
187
+ async def _ui_query(indicator_id: str, level: str, code: str, year: str, limit: float):
188
+ raw = await query_indicator_data(indicator_id, level, code, year, int(limit))
189
+ payload = json.loads(raw)
190
+ if "error" in payload:
191
+ return _status(payload, ""), [], raw
192
+ unite = payload.get("unite") or ""
193
+ status = _status(
194
+ payload,
195
+ f"**{payload.get('indicator_name')}** — {payload.get('total_count', 0)} ligne(s)"
196
+ + (" (tronqué)" if payload.get("truncated") else "")
197
+ + (f" · unité : {unite}" if unite else ""),
198
  )
199
+ rows = [[d.get("geocode"), d.get("libelle"), d.get("annee"), d.get("valeur")] for d in payload.get("data") or []]
200
+ return status, rows, raw
201
+
202
+
203
+ async def _ui_territory(name: str, level: str):
204
+ raw = await find_territory(name, level)
205
+ payload = json.loads(raw)
206
+ status = _status(payload, f"**{payload.get('total_count', 0)} territoire(s)**")
207
+ rows = [[t.get("geographic_level"), t.get("geocode"), t.get("libelle")] for t in payload.get("territories") or []]
208
+ return status, rows, raw
209
+
210
+
211
+ # --------------------------------------------------------------------------- app
212
+
213
+ with gr.Blocks(title="Indicateurs TE — serveur MCP") as demo:
214
+ # Outils exposés aux assistants IA (schéma MCP dérivé des docstrings).
215
+ gr.api(search_indicators, api_name="search_indicators")
216
+ gr.api(list_indicators, api_name="list_indicators")
217
+ gr.api(get_indicator_details, api_name="get_indicator_details")
218
+ gr.api(query_indicator_data, api_name="query_indicator_data")
219
+ gr.api(find_territory, api_name="find_territory")
220
+
221
+ gr.Markdown(ACCUEIL)
222
+
223
+ with gr.Row(equal_height=False):
224
+ with gr.Column(scale=3, min_width=360):
225
+ with gr.Tab("🔎 Rechercher"):
226
+ q = gr.Textbox(label="Mots-clés", placeholder="consommation espace, émissions gaz effet de serre, surface bio…")
227
+ btn_q = gr.Button("Rechercher", variant="primary")
228
+ st_q = gr.Markdown()
229
+ tbl_q = gr.Dataframe(headers=_LIST_COLUMNS, interactive=False, wrap=True, column_widths=_LIST_WIDTHS, label="Indicateurs")
230
+ with gr.Accordion("Réponse JSON (ce que reçoit l'assistant)", open=False):
231
+ js_q = gr.Code(language="json", label="search_indicators")
232
+ gr.Examples(
233
+ examples=[["consommation espace"], ["émissions gaz effet de serre"], ["surface bio"], ["stationnement vélo"], ["logements vacants"]],
234
+ inputs=[q], outputs=[st_q, tbl_q, js_q], fn=_ui_search, run_on_click=True,
235
+ cache_examples=False, api_visibility="private", label="Exemples",
236
+ )
237
+ btn_q.click(_ui_search, inputs=q, outputs=[st_q, tbl_q, js_q], api_visibility="private")
238
+ q.submit(_ui_search, inputs=q, outputs=[st_q, tbl_q, js_q], api_visibility="private")
239
+
240
+ with gr.Tab("📚 Catalogue"):
241
+ with gr.Row():
242
+ them = gr.Textbox(label="Thématique France Nation Verte", placeholder="déplacer, loger, produire, nourrir, consommer, écosystèmes…")
243
+ maille = gr.Dropdown(label="Disponible à la maille", choices=LEVEL_CHOICES_ALL, value="")
244
+ btn_l = gr.Button("Lister", variant="primary")
245
+ st_l = gr.Markdown()
246
+ tbl_l = gr.Dataframe(headers=_LIST_COLUMNS, interactive=False, wrap=True, column_widths=_LIST_WIDTHS, label="Indicateurs")
247
+ with gr.Accordion("Réponse JSON (ce que reçoit l'assistant)", open=False):
248
+ js_l = gr.Code(language="json", label="list_indicators")
249
+ btn_l.click(_ui_list, inputs=[them, maille], outputs=[st_l, tbl_l, js_l], api_visibility="private")
250
+
251
+ with gr.Tab("📄 Détails"):
252
+ ind = gr.Textbox(label="ID de l'indicateur", placeholder="611")
253
+ btn_d = gr.Button("Voir les détails", variant="primary")
254
+ md_d = gr.Markdown()
255
+ with gr.Accordion("Réponse JSON (ce que reçoit l'assistant)", open=False):
256
+ js_d = gr.JSON(label="get_indicator_details")
257
+ btn_d.click(_ui_details, inputs=ind, outputs=[md_d, js_d], api_visibility="private")
258
+ ind.submit(_ui_details, inputs=ind, outputs=[md_d, js_d], api_visibility="private")
259
+
260
+ with gr.Tab("📈 Données"):
261
+ with gr.Row():
262
+ ind2 = gr.Textbox(label="ID de l'indicateur", placeholder="611")
263
+ lvl = gr.Dropdown(label="Niveau géographique", choices=LEVEL_CHOICES, value="region")
264
+ with gr.Row():
265
+ code = gr.Textbox(label="Code du territoire (optionnel)", placeholder="93 (PACA), 13, 200046977, 75056…")
266
+ year = gr.Textbox(label="Année (optionnel)", placeholder="2022")
267
+ limit = gr.Slider(label="Lignes max", minimum=10, maximum=500, step=10, value=100)
268
+ btn_x = gr.Button("Interroger", variant="primary")
269
+ st_x = gr.Markdown()
270
+ tbl_x = gr.Dataframe(headers=["geocode", "libelle", "annee", "valeur"], interactive=False, label="Valeurs")
271
+ with gr.Accordion("Réponse JSON (ce que reçoit l'assistant)", open=False):
272
+ js_x = gr.Code(language="json", label="query_indicator_data")
273
+ gr.Examples(
274
+ examples=[["611", "region", "93", "", 100], ["611", "departement", "", "2022", 100], ["23", "region", "", "2022", 100]],
275
+ inputs=[ind2, lvl, code, year, limit], outputs=[st_x, tbl_x, js_x], fn=_ui_query,
276
+ run_on_click=True, cache_examples=False, api_visibility="private", label="Exemples",
277
+ )
278
+ btn_x.click(_ui_query, inputs=[ind2, lvl, code, year, limit], outputs=[st_x, tbl_x, js_x], api_visibility="private")
279
+
280
+ with gr.Tab("🗺️ Territoire"):
281
+ with gr.Row():
282
+ name = gr.Textbox(label="Nom (ou fragment)", placeholder="Lyon, Bouches-du-Rhône, Grand Paris…")
283
+ lvl2 = gr.Dropdown(label="Niveau", choices=LEVEL_CHOICES_ALL, value="")
284
+ btn_t = gr.Button("Trouver le code", variant="primary")
285
+ st_t = gr.Markdown()
286
+ tbl_t = gr.Dataframe(headers=["niveau", "geocode", "libelle"], interactive=False, label="Territoires")
287
+ with gr.Accordion("Réponse JSON (ce que reçoit l'assistant)", open=False):
288
+ js_t = gr.Code(language="json", label="find_territory")
289
+ btn_t.click(_ui_territory, inputs=[name, lvl2], outputs=[st_t, tbl_t, js_t], api_visibility="private")
290
+ name.submit(_ui_territory, inputs=[name, lvl2], outputs=[st_t, tbl_t, js_t], api_visibility="private")
291
+
292
+ with gr.Column(scale=2, min_width=300):
293
+ gr.Markdown(CONNEXION)
294
+ gr.Textbox(value=MCP_URL, label="URL du serveur MCP", interactive=False, buttons=["copy"])
295
+ with gr.Accordion("Claude Code (terminal)", open=True):
296
+ gr.Code(value=SNIPPET_CLAUDE_CODE, language="shell", label="commande")
297
+ with gr.Accordion("Claude.ai / Claude Desktop", open=False):
298
+ gr.Markdown(
299
+ "Paramètres → **Connecteurs** → *Ajouter un connecteur personnalisé* → "
300
+ "collez l'URL ci-dessus. Aucune authentification requise."
301
+ )
302
+ with gr.Accordion("Cursor, Windsurf, VS Code… (mcp.json)", open=False):
303
+ gr.Code(value=SNIPPET_JSON, language="json", label="mcp.json")
304
+ with gr.Accordion("Python (SDK mcp)", open=False):
305
+ gr.Code(value=SNIPPET_PYTHON, language="python", label="client")
306
+ gr.Markdown(f"<small>Clients SSE uniquement : `{MCP_SSE_URL}`</small>")
307
+ gr.Markdown(PROMPTS)
308
+
309
+ gr.Markdown(PIED)
310
 
311
 
312
  if __name__ == "__main__":
313
+ launch_kwargs: dict = {
314
+ "mcp_server": True,
315
+ "theme": gr.themes.Soft(primary_hue="blue"),
316
+ "server_name": "0.0.0.0" if _is_hf_space() else "127.0.0.1",
317
+ "server_port": int(os.environ.get("GRADIO_SERVER_PORT", "7860")),
318
+ }
319
+ demo.launch(**launch_kwargs)
requirements.txt CHANGED
@@ -1,17 +1,10 @@
1
- # MCP Server for Indicateurs Territoriaux de Transition Écologique
2
- # Python >= 3.10 required
 
 
 
3
 
4
- # Gradio with MCP support (5.29.x - stable with Claude Desktop)
5
- gradio[mcp]>=5.27.1,<6.0.0
6
-
7
- # HTTP client
8
  httpx>=0.27.0
9
-
10
- # Data validation
11
  pydantic>=2.0.0
12
-
13
- # Environment variables
14
  python-dotenv>=1.0.0
15
-
16
- # Async support
17
  anyio>=4.0.0
 
1
+ # Serveur MCP — Indicateurs territoriaux de transition écologique
2
+ # Python >= 3.11 ; version Gradio alignée sur sdk_version du README (Hugging Face Spaces).
3
+ # Gradio >= 6 est requis : il expose le transport MCP Streamable HTTP (/gradio_api/mcp/)
4
+ # attendu par les clients actuels (connecteurs claude.ai, Claude Code, ChatGPT), en plus du SSE.
5
+ gradio[mcp]>=6.15.0,<7.0.0
6
 
 
 
 
 
7
  httpx>=0.27.0
 
 
8
  pydantic>=2.0.0
 
 
9
  python-dotenv>=1.0.0
 
 
10
  anyio>=4.0.0
src/api_client.py CHANGED
@@ -210,31 +210,51 @@ class CubeJsClient:
210
  result = await self.load(query)
211
  return result.get("data", [])
212
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
  async def load_sources_metadata(
214
  self,
215
  indicator_id: int | None = None,
216
  limit: int = 100,
 
217
  ) -> list[dict[str, Any]]:
218
  """Load source metadata from the indicateur_x_source_metadata cube.
219
 
220
  Args:
221
  indicator_id: Optional indicator ID to filter sources.
222
  limit: Maximum number of results.
 
 
223
 
224
  Returns:
225
  List of source metadata records.
226
  """
227
- dimensions = [
228
- "indicateur_x_source_metadata.id_indicateur",
229
- "indicateur_x_source_metadata.nom_source",
230
- "indicateur_x_source_metadata.libelle",
231
- "indicateur_x_source_metadata.description",
232
- "indicateur_x_source_metadata.producteur_source",
233
- "indicateur_x_source_metadata.distributeur_source",
234
- "indicateur_x_source_metadata.license_source",
235
- "indicateur_x_source_metadata.lien_page",
236
- "indicateur_x_source_metadata.date_derniere_extraction",
237
- ]
238
 
239
  query: dict[str, Any] = {
240
  "dimensions": dimensions,
@@ -293,6 +313,41 @@ class CubeJsClient:
293
  return result.get("data", [])
294
 
295
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
  # Singleton instance for the application
297
  _client_instance: CubeJsClient | None = None
298
 
 
210
  result = await self.load(query)
211
  return result.get("data", [])
212
 
213
+ # Dimensions souhaitées pour les sources ; seules celles réellement exposées par
214
+ # /meta sont demandées (l'API refuse toute dimension inconnue, ex. « libelle »).
215
+ SOURCE_DIMENSIONS_WANTED = (
216
+ "id_indicateur",
217
+ "nom_source",
218
+ "libelle",
219
+ "libelle_source",
220
+ "description",
221
+ "producteur_source",
222
+ "distributeur_source",
223
+ "license_source",
224
+ "licence_source",
225
+ "lien_page",
226
+ "annees_disponibles_source",
227
+ "maille_mini_disponible",
228
+ "couverture_geographique",
229
+ "date_derniere_extraction",
230
+ )
231
+
232
  async def load_sources_metadata(
233
  self,
234
  indicator_id: int | None = None,
235
  limit: int = 100,
236
+ available_dimensions: list[str] | None = None,
237
  ) -> list[dict[str, Any]]:
238
  """Load source metadata from the indicateur_x_source_metadata cube.
239
 
240
  Args:
241
  indicator_id: Optional indicator ID to filter sources.
242
  limit: Maximum number of results.
243
+ available_dimensions: Full dimension names of the cube as listed by /meta.
244
+ When given, only wanted dimensions that actually exist are requested.
245
 
246
  Returns:
247
  List of source metadata records.
248
  """
249
+ cube = "indicateur_x_source_metadata"
250
+ wanted = [f"{cube}.{d}" for d in self.SOURCE_DIMENSIONS_WANTED]
251
+ if available_dimensions is not None:
252
+ existing = set(available_dimensions)
253
+ dimensions = [d for d in wanted if d in existing]
254
+ else:
255
+ dimensions = wanted
256
+ if f"{cube}.id_indicateur" not in dimensions:
257
+ return []
 
 
258
 
259
  query: dict[str, Any] = {
260
  "dimensions": dimensions,
 
313
  return result.get("data", [])
314
 
315
 
316
+ async def find_territories(
317
+ self,
318
+ cube_name: str,
319
+ geocode_dim: str,
320
+ libelle_dim: str,
321
+ name: str,
322
+ limit: int = 20,
323
+ ) -> list[dict[str, Any]]:
324
+ """Find territories whose name contains `name` (case-insensitive, Cube.js `contains`).
325
+
326
+ Args:
327
+ cube_name: A data cube that carries the geographic dimensions.
328
+ geocode_dim: Short dimension name (e.g. "geocode_epci").
329
+ libelle_dim: Short dimension name (e.g. "libelle_epci").
330
+ name: Text to search in the territory label.
331
+ limit: Maximum number of distinct territories.
332
+
333
+ Returns:
334
+ List of rows with the two full dimension names as keys.
335
+ """
336
+ query: dict[str, Any] = {
337
+ "dimensions": [f"{cube_name}.{geocode_dim}", f"{cube_name}.{libelle_dim}"],
338
+ "filters": [
339
+ {
340
+ "member": f"{cube_name}.{libelle_dim}",
341
+ "operator": "contains",
342
+ "values": [name],
343
+ }
344
+ ],
345
+ "limit": limit,
346
+ }
347
+ result = await self.load(query)
348
+ return result.get("data", [])
349
+
350
+
351
  # Singleton instance for the application
352
  _client_instance: CubeJsClient | None = None
353
 
src/cache.py CHANGED
@@ -2,6 +2,8 @@
2
 
3
  import asyncio
4
  import os
 
 
5
  from datetime import datetime, timedelta
6
  from typing import Any
7
 
@@ -10,6 +12,27 @@ from .cube_resolver import CubeResolver, get_resolver
10
  from .models import IndicatorMetadata, IndicatorListItem
11
 
12
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  class IndicatorCache:
14
  """Cache for indicator metadata and cube resolution.
15
 
@@ -188,7 +211,7 @@ class IndicatorCache:
188
  if thematique:
189
  if not indicator.thematique_fnv:
190
  continue
191
- if thematique.lower() not in indicator.thematique_fnv.lower():
192
  continue
193
 
194
  # Apply maille filter
@@ -211,48 +234,57 @@ class IndicatorCache:
211
  return results
212
 
213
  def search_indicators(self, query: str) -> list[IndicatorListItem]:
214
- """Search indicators by keyword.
215
 
216
- Searches in libelle and description fields (case-insensitive).
 
 
 
217
 
218
  Args:
219
  query: Search query string.
220
 
221
  Returns:
222
- List of matching indicators.
223
  """
224
- if not query or not query.strip():
 
225
  return self.list_indicators()
226
 
227
- query_lower = query.lower().strip()
228
- query_words = query_lower.split()
229
- results = []
230
 
 
231
  for indicator in self._indicators.values():
232
- # Search in libelle and description
233
- searchable = " ".join(
234
- filter(None, [indicator.libelle, indicator.description])
235
- ).lower()
236
-
237
- # Check if all query words are present
238
- if all(word in searchable for word in query_words):
239
- results.append(
240
- IndicatorListItem(
241
- id=indicator.id,
242
- libelle=indicator.libelle,
243
- unite=indicator.unite,
244
- mailles_disponibles=indicator.mailles_disponibles,
245
- thematique_fnv=indicator.thematique_fnv,
 
 
 
 
 
 
 
 
 
 
246
  )
247
  )
248
 
249
- # Sort by relevance (exact match in libelle first, then by ID)
250
- def sort_key(item: IndicatorListItem) -> tuple[int, int]:
251
- exact_match = 0 if query_lower in item.libelle.lower() else 1
252
- return (exact_match, item.id)
253
-
254
- results.sort(key=sort_key)
255
- return results
256
 
257
 
258
  # Singleton cache instance
 
2
 
3
  import asyncio
4
  import os
5
+ import re
6
+ import unicodedata
7
  from datetime import datetime, timedelta
8
  from typing import Any
9
 
 
12
  from .models import IndicatorMetadata, IndicatorListItem
13
 
14
 
15
+ _TOKEN_RE = re.compile(r"[a-z0-9]+")
16
+
17
+
18
+ def fold_text(text: str | None) -> str:
19
+ """Lowercase, accent-insensitive form (Émissions → emissions)."""
20
+ text = unicodedata.normalize("NFKD", text or "")
21
+ return "".join(ch for ch in text if not unicodedata.combining(ch)).lower()
22
+
23
+
24
+ def _stem(token: str) -> str:
25
+ """Minimal French stem: drop plural marks (s / x)."""
26
+ if len(token) > 3 and token[-1] in "sx":
27
+ return token[:-1]
28
+ return token
29
+
30
+
31
+ def search_tokens(text: str | None) -> list[str]:
32
+ """Tokens of a text, folded and stemmed (used for both queries and indicators)."""
33
+ return [_stem(t) for t in _TOKEN_RE.findall(fold_text(text)) if len(t) >= 2]
34
+
35
+
36
  class IndicatorCache:
37
  """Cache for indicator metadata and cube resolution.
38
 
 
211
  if thematique:
212
  if not indicator.thematique_fnv:
213
  continue
214
+ if fold_text(thematique) not in fold_text(indicator.thematique_fnv):
215
  continue
216
 
217
  # Apply maille filter
 
234
  return results
235
 
236
  def search_indicators(self, query: str) -> list[IndicatorListItem]:
237
+ """Search indicators by keywords.
238
 
239
+ Accent- and case-insensitive, plural-insensitive, prefix-tolerant
240
+ (« emission » matches « Émissions »). A word matching in the libelle
241
+ weighs more than one matching in the description or thematic. All words
242
+ must match somewhere (AND); results are sorted by score, then by ID.
243
 
244
  Args:
245
  query: Search query string.
246
 
247
  Returns:
248
+ List of matching indicators, best first.
249
  """
250
+ words = search_tokens(query)
251
+ if not words:
252
  return self.list_indicators()
253
 
254
+ def has(tokens: list[str], word: str) -> bool:
255
+ return any(t == word or (len(word) >= 5 and t.startswith(word)) for t in tokens)
 
256
 
257
+ scored: list[tuple[int, IndicatorListItem]] = []
258
  for indicator in self._indicators.values():
259
+ libelle_tokens = search_tokens(indicator.libelle)
260
+ other_tokens = search_tokens(
261
+ " ".join(filter(None, [indicator.description, indicator.thematique_fnv]))
262
+ )
263
+ score = 0
264
+ for word in words:
265
+ if has(libelle_tokens, word):
266
+ score += 3
267
+ elif has(other_tokens, word):
268
+ score += 1
269
+ else:
270
+ score = 0
271
+ break
272
+ if score:
273
+ scored.append(
274
+ (
275
+ score,
276
+ IndicatorListItem(
277
+ id=indicator.id,
278
+ libelle=indicator.libelle,
279
+ unite=indicator.unite,
280
+ mailles_disponibles=indicator.mailles_disponibles,
281
+ thematique_fnv=indicator.thematique_fnv,
282
+ ),
283
  )
284
  )
285
 
286
+ scored.sort(key=lambda x: (-x[0], x[1].id))
287
+ return [item for _, item in scored]
 
 
 
 
 
288
 
289
 
290
  # Singleton cache instance
src/cube_resolver.py CHANGED
@@ -35,6 +35,12 @@ class CubeResolver:
35
  # Set of all indicator IDs found in cubes
36
  self._known_indicator_ids: set[int] = set()
37
 
 
 
 
 
 
 
38
  self._initialized = False
39
 
40
  @property
@@ -57,9 +63,14 @@ class CubeResolver:
57
  self._indicator_cube_map.clear()
58
  self._cube_info.clear()
59
  self._known_indicator_ids.clear()
 
 
60
 
61
  for cube in self._cubes_meta:
62
  cube_name = cube.get("name", "")
 
 
 
63
 
64
  # Skip metadata cubes
65
  if cube_name in ("indicateur_metadata", "indicateur_x_source_metadata"):
@@ -69,6 +80,10 @@ class CubeResolver:
69
  available_mailles = self._detect_all_mailles(cube)
70
  if not available_mailles:
71
  continue
 
 
 
 
72
 
73
  # Extract indicator IDs from measures
74
  indicator_ids = self._extract_indicator_ids(cube)
@@ -258,6 +273,39 @@ class CubeResolver:
258
  """
259
  return list(self._cube_info.values())
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  def get_cubes_for_indicator(self, indicator_id: int) -> dict[str, str]:
262
  """Get all cubes containing a given indicator.
263
 
 
35
  # Set of all indicator IDs found in cubes
36
  self._known_indicator_ids: set[int] = set()
37
 
38
+ # Mapping: cube_name -> full dimension names (all cubes, metadata included)
39
+ self._cube_dimensions: dict[str, list[str]] = {}
40
+
41
+ # Data cube exposing every geographic level (used for territory lookup)
42
+ self._reference_cube: str | None = None
43
+
44
  self._initialized = False
45
 
46
  @property
 
63
  self._indicator_cube_map.clear()
64
  self._cube_info.clear()
65
  self._known_indicator_ids.clear()
66
+ self._cube_dimensions.clear()
67
+ self._reference_cube = None
68
 
69
  for cube in self._cubes_meta:
70
  cube_name = cube.get("name", "")
71
+ self._cube_dimensions[cube_name] = [
72
+ d.get("name", "") for d in cube.get("dimensions", [])
73
+ ]
74
 
75
  # Skip metadata cubes
76
  if cube_name in ("indicateur_metadata", "indicateur_x_source_metadata"):
 
80
  available_mailles = self._detect_all_mailles(cube)
81
  if not available_mailles:
82
  continue
83
+ if self._reference_cube is None and len(available_mailles) == len(
84
+ GEO_DIMENSION_PATTERNS
85
+ ):
86
+ self._reference_cube = cube_name
87
 
88
  # Extract indicator IDs from measures
89
  indicator_ids = self._extract_indicator_ids(cube)
 
273
  """
274
  return list(self._cube_info.values())
275
 
276
+ def get_cube_dimensions(self, cube_name: str) -> list[str]:
277
+ """Get the full dimension names of a cube as listed by /meta.
278
+
279
+ Args:
280
+ cube_name: The cube name (metadata cubes included)
281
+
282
+ Returns:
283
+ List of full dimension names (e.g. 'indicateur_x_source_metadata.nom_source')
284
+ """
285
+ return list(self._cube_dimensions.get(cube_name, []))
286
+
287
+ def find_cube_with_maille(self, maille: str) -> str | None:
288
+ """Find a data cube exposing the given geographic level.
289
+
290
+ Prefers the reference cube (all levels), falls back to any cube with the level.
291
+
292
+ Args:
293
+ maille: The geographic level ('commune', 'epci', 'departement', 'region')
294
+
295
+ Returns:
296
+ A cube name, or None if no cube exposes this level
297
+ """
298
+ geocode_dim = GEO_DIMENSION_PATTERNS.get(maille.lower(), {}).get("geocode", "")
299
+ if not geocode_dim:
300
+ return None
301
+ candidates = [self._reference_cube] if self._reference_cube else []
302
+ candidates.extend(self._cube_info.keys())
303
+ for cube_name in candidates:
304
+ dims = self._cube_dimensions.get(cube_name, [])
305
+ if any(d.endswith(f".{geocode_dim}") for d in dims):
306
+ return cube_name
307
+ return None
308
+
309
  def get_cubes_for_indicator(self, indicator_id: int) -> dict[str, str]:
310
  """Get all cubes containing a given indicator.
311
 
src/tools.py CHANGED
@@ -1,4 +1,11 @@
1
- """MCP tools for querying territorial ecological indicators."""
 
 
 
 
 
 
 
2
 
3
  import json
4
  import logging
@@ -6,11 +13,18 @@ import time
6
  import hashlib
7
  from collections import defaultdict
8
  from dataclasses import dataclass, field
9
- from datetime import datetime, timezone
10
  from functools import wraps
11
- from typing import Any, Callable, Optional
12
 
13
- from .api_client import get_client, CubeJsClient, CubeJsClientError
 
 
 
 
 
 
 
 
14
 
15
  # Configure logging
16
  logging.basicConfig(
@@ -20,6 +34,13 @@ logging.basicConfig(
20
  )
21
  logger = logging.getLogger("mcp_tools")
22
 
 
 
 
 
 
 
 
23
 
24
  # =============================================================================
25
  # Session Tracker - Track usage patterns across calls
@@ -33,13 +54,13 @@ class SessionData:
33
  last_call_time: float = 0
34
  indicators_queried: set = field(default_factory=set)
35
  levels_queried: set = field(default_factory=set)
36
-
37
- def add_call(self, tool: str, params: dict, duration_ms: int,
38
  result_count: int, response_size: int, status: str):
39
  """Record a tool call."""
40
  now = time.time()
41
  time_since_last = int((now - self.last_call_time) * 1000) if self.last_call_time else 0
42
-
43
  self.calls.append({
44
  "tool": tool,
45
  "params": params,
@@ -50,18 +71,18 @@ class SessionData:
50
  "time_since_last_ms": time_since_last,
51
  })
52
  self.last_call_time = now
53
-
54
  # Track what's being queried
55
  if "indicator_id" in params:
56
  self.indicators_queried.add(params["indicator_id"])
57
  if "geographic_level" in params:
58
  self.levels_queried.add(params["geographic_level"])
59
-
60
  def get_sequence(self) -> str:
61
  """Get the sequence of tools called."""
62
- return "→".join(c["tool"].replace("_indicators", "").replace("_indicator", "")
63
  for c in self.calls)
64
-
65
  def get_total_duration_ms(self) -> int:
66
  """Total time spent in API calls."""
67
  return sum(c["duration_ms"] for c in self.calls)
@@ -69,24 +90,24 @@ class SessionData:
69
 
70
  class UsageTracker:
71
  """Track MCP usage patterns across sessions."""
72
-
73
  # Session timeout in seconds (new session if no call for 5 minutes)
74
  SESSION_TIMEOUT = 300
75
-
76
  def __init__(self):
77
  self.sessions: dict[str, SessionData] = {}
78
  self.patterns: defaultdict[str, int] = defaultdict(int) # sequence -> count
79
  self.tool_stats: defaultdict[str, dict] = defaultdict(
80
  lambda: {"calls": 0, "total_ms": 0, "errors": 0}
81
  )
82
-
83
  def get_or_create_session(self, session_hint: str = "default") -> SessionData:
84
  """Get existing session or create new one."""
85
  # Simple session management based on hint (could be IP, user-agent hash, etc.)
86
  session_id = hashlib.md5(session_hint.encode()).hexdigest()[:8]
87
-
88
  now = time.time()
89
-
90
  # Check if session exists and is not expired
91
  if session_id in self.sessions:
92
  session = self.sessions[session_id]
@@ -100,15 +121,15 @@ class UsageTracker:
100
  session = SessionData(session_id=session_id)
101
  self.sessions[session_id] = session
102
  logger.info(f"[SESSION] id={session_id} | new_session")
103
-
104
  return session
105
-
106
  def _finalize_session(self, session: SessionData):
107
  """Log session summary when it ends."""
108
  if len(session.calls) > 1:
109
  sequence = session.get_sequence()
110
  self.patterns[sequence] += 1
111
-
112
  logger.info(
113
  f"[PATTERN] id={session.session_id} | "
114
  f"sequence={sequence} | "
@@ -117,7 +138,7 @@ class UsageTracker:
117
  f"indicators={list(session.indicators_queried)} | "
118
  f"levels={list(session.levels_queried)}"
119
  )
120
-
121
  def log_stats_summary(self):
122
  """Log accumulated statistics."""
123
  if self.patterns:
@@ -135,28 +156,28 @@ def log_tool_call(func: Callable) -> Callable:
135
  async def wrapper(*args, **kwargs):
136
  tool_name = func.__name__
137
  start_time = time.time()
138
-
139
  # Get or create session
140
  session = _tracker.get_or_create_session()
141
-
142
  # Extract params (only non-empty)
143
  params = {k: v for k, v in kwargs.items() if v}
144
-
145
  # Build context info
146
  call_num = len(session.calls) + 1
147
  prev_tool = session.calls[-1]["tool"] if session.calls else None
148
-
149
  # Log the call with context
150
  context = f"call#{call_num}"
151
  if prev_tool:
152
  context += f" | prev={prev_tool}"
153
  logger.info(f"[CALL] {tool_name} | {context} | params={params}")
154
-
155
  try:
156
  result = await func(*args, **kwargs)
157
  elapsed_ms = int((time.time() - start_time) * 1000)
158
  response_size = len(result.encode('utf-8'))
159
-
160
  # Parse result to get metrics
161
  status = "ok"
162
  result_count = 0
@@ -170,8 +191,8 @@ def log_tool_call(func: Callable) -> Callable:
170
  )
171
  else:
172
  result_count = (
173
- result_data.get("count") or
174
- result_data.get("total_count") or
175
  len(result_data.get("data", [])) or
176
  (1 if "metadata" in result_data else 0)
177
  )
@@ -181,7 +202,7 @@ def log_tool_call(func: Callable) -> Callable:
181
  )
182
  except json.JSONDecodeError:
183
  logger.info(f"[OK] {tool_name} | {elapsed_ms}ms | size={response_size}B")
184
-
185
  # Record in session
186
  session.add_call(
187
  tool=tool_name,
@@ -191,164 +212,240 @@ def log_tool_call(func: Callable) -> Callable:
191
  response_size=response_size,
192
  status=status,
193
  )
194
-
195
  # Update global stats
196
  _tracker.tool_stats[tool_name]["calls"] += 1
197
  _tracker.tool_stats[tool_name]["total_ms"] += elapsed_ms
198
  if status == "error":
199
  _tracker.tool_stats[tool_name]["errors"] += 1
200
-
201
  return result
202
-
203
  except Exception as e:
204
  elapsed_ms = int((time.time() - start_time) * 1000)
205
  logger.error(f"[EXCEPTION] {tool_name} | {elapsed_ms}ms | {type(e).__name__}: {e}")
206
  _tracker.tool_stats[tool_name]["errors"] += 1
207
  raise
208
-
209
  return wrapper
210
- from .cache import get_cache, initialize_cache, refresh_cache_if_needed
211
- from .cube_resolver import get_resolver
212
- from .models import (
213
- IndicatorMetadata,
214
- SourceMetadata,
215
- IndicatorListItem,
216
- GEOGRAPHIC_LEVELS,
217
- GEO_DIMENSION_PATTERNS,
218
- )
219
 
220
 
221
- async def _ensure_cache_initialized() -> None:
222
- """Ensure the cache is initialized before tool execution."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  cache = get_cache()
224
- if not cache.is_initialized:
225
- await initialize_cache()
226
- else:
227
- await refresh_cache_if_needed()
 
 
 
 
 
 
 
 
228
 
229
 
 
 
 
230
  @log_tool_call
231
  async def list_indicators(
232
  thematique: str = "",
233
  maille: str = "",
234
  ) -> str:
235
- """List all available territorial ecological indicators.
236
-
237
- Returns a list of indicators with their main characteristics. You can filter
238
- by thematic (France Nation Verte themes like "mieux se déplacer", "mieux se loger")
239
- or by geographic level (region, departement, epci, commune).
240
-
241
  Args:
242
- thematique: Optional filter by FNV thematic. Use partial match, e.g., "déplacer"
243
- for mobility indicators, "loger" for housing, "produire" for production.
244
- maille: Optional filter by available geographic level. Valid values:
245
- "region", "departement", "epci", "commune".
246
-
247
  Returns:
248
- JSON string containing a list of indicators with id, libelle, unite,
249
- mailles_disponibles, and thematique_fnv.
250
-
251
- Example:
252
- To find mobility indicators available at department level:
253
- list_indicators(thematique="déplacer", maille="departement")
254
  """
255
- await _ensure_cache_initialized()
 
 
256
  cache = get_cache()
257
-
258
- # Normalize empty strings to None
259
  theme_filter = thematique.strip() if thematique else None
260
  maille_filter = maille.strip().lower() if maille else None
261
-
262
- # Validate maille if provided
263
  if maille_filter and maille_filter not in GEOGRAPHIC_LEVELS:
264
- return json.dumps({
265
- "error": f"Invalid geographic level: {maille}",
266
- "valid_levels": GEOGRAPHIC_LEVELS,
267
- }, ensure_ascii=False)
268
-
269
- indicators = cache.list_indicators(
270
- thematique=theme_filter,
271
- maille=maille_filter,
272
- )
273
-
274
- return json.dumps({
275
- "indicators": [ind.model_dump() for ind in indicators],
276
  "count": len(indicators),
277
- "filters_applied": {
278
- "thematique": theme_filter,
279
- "maille": maille_filter,
280
- },
281
- }, ensure_ascii=False, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
 
284
  @log_tool_call
285
  async def get_indicator_details(indicator_id: str) -> str:
286
- """Get detailed information about a specific indicator.
287
-
288
- Returns comprehensive metadata including description, calculation method,
289
- data coverage, and data sources for a given indicator ID.
290
-
291
  Args:
292
- indicator_id: The numeric ID of the indicator (e.g., "42", "94", "611").
293
-
294
  Returns:
295
- JSON string containing:
296
- - metadata: Full indicator metadata (description, methode_calcul,
297
- annees_disponibles, completion rates by geographic level, etc.)
298
- - sources: List of data sources with producer, license, and links.
299
- - available_cubes: Dict mapping maille to cube name for data queries.
300
-
301
- Example:
302
- get_indicator_details("611") returns details about indicator 611
303
- (Consommation d'espaces naturels, agricoles et forestiers).
304
  """
305
- await _ensure_cache_initialized()
306
-
307
- # Parse indicator ID
 
308
  try:
309
- ind_id = int(indicator_id)
310
  except ValueError:
311
- return json.dumps({
312
- "error": f"Invalid indicator ID: {indicator_id}. Must be a number.",
313
- }, ensure_ascii=False)
314
-
315
  cache = get_cache()
316
  indicator = cache.get_indicator(ind_id)
317
-
318
  if indicator is None:
319
- return json.dumps({
320
- "error": f"Indicator {ind_id} not found in metadata.",
321
- "hint": "Use list_indicators() to see available indicators.",
322
- }, ensure_ascii=False)
323
-
324
- # Get available cubes from resolver
325
  resolver = get_resolver()
326
  available_cubes = resolver.get_cubes_for_indicator(ind_id)
327
-
328
- # Fetch sources from API
329
  client = get_client()
 
 
330
  try:
331
- sources_data = await client.load_sources_metadata(indicator_id=ind_id)
332
- sources = [
333
- SourceMetadata.from_api_response(row).model_dump()
334
- for row in sources_data
335
- ]
 
 
 
336
  except CubeJsClientError as e:
337
- sources = []
338
- sources_error = str(e)
339
- else:
340
- sources_error = None
341
-
342
- result = {
343
- "metadata": indicator.model_dump(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
  "sources": sources,
345
  "available_cubes": available_cubes,
346
  }
347
-
348
- if sources_error:
349
- result["sources_warning"] = f"Could not fetch sources: {sources_error}"
350
-
351
- return json.dumps(result, ensure_ascii=False, indent=2)
352
 
353
 
354
  @log_tool_call
@@ -357,206 +454,211 @@ async def query_indicator_data(
357
  geographic_level: str,
358
  geographic_code: str = "",
359
  year: str = "",
 
360
  ) -> str:
361
- """Query data values for a specific indicator and territory.
362
-
363
- Retrieves actual data values for an indicator at the specified geographic level.
364
- You can filter by a specific territory code and/or year.
365
-
 
366
  Args:
367
- indicator_id: The numeric ID of the indicator (e.g., "611").
368
- geographic_level: The geographic level to query. Valid values:
369
- "region", "departement", "epci", "commune".
370
- geographic_code: Optional INSEE code to filter by territory:
371
- - Region: 2 digits (e.g., "93" for PACA, "11" for Île-de-France)
372
- - Departement: 2-3 characters (e.g., "13", "2A", "974")
373
- - EPCI: 9 digits (SIREN code)
374
- - Commune: 5 digits (e.g., "75056" for Paris)
375
- year: Optional year to filter data (e.g., "2020").
376
-
377
  Returns:
378
- JSON string containing:
379
- - indicator_id: The queried indicator ID
380
- - indicator_name: Human-readable name
381
- - geographic_level: The queried level
382
- - data: List of data points with geocode, libelle, valeur, annee
383
- - total_count: Number of results
384
-
385
- Example:
386
- Query indicator 611 (ENAF consumption) for PACA region:
387
- query_indicator_data("611", "region", "93")
388
-
389
- Query all departments for 2020:
390
- query_indicator_data("611", "departement", year="2020")
391
  """
392
- await _ensure_cache_initialized()
393
-
394
- # Parse indicator ID
 
395
  try:
396
- ind_id = int(indicator_id)
397
  except ValueError:
398
- return json.dumps({
399
- "error": f"Invalid indicator ID: {indicator_id}. Must be a number.",
400
- }, ensure_ascii=False)
401
-
402
- # Validate geographic level
403
- geo_level = geographic_level.strip().lower()
404
  if geo_level not in GEOGRAPHIC_LEVELS:
405
- return json.dumps({
406
- "error": f"Invalid geographic level: {geographic_level}",
407
- "valid_levels": GEOGRAPHIC_LEVELS,
408
- }, ensure_ascii=False)
409
-
410
  cache = get_cache()
411
  resolver = get_resolver()
412
-
413
  indicator = cache.get_indicator(ind_id)
414
  indicator_name = indicator.libelle if indicator else f"Indicator {ind_id}"
415
  indicator_unite = indicator.unite if indicator else None
416
-
417
- # Find the cube for this indicator and maille
418
  cube_name = resolver.find_cube_for_indicator(ind_id, geo_level)
419
-
420
  if cube_name is None:
421
- # Check if indicator exists at all
422
  if not resolver.is_indicator_known(ind_id):
423
- return json.dumps({
424
- "error": f"Indicator {ind_id} not found in any data cube.",
425
- "hint": "Use get_indicator_details() to check available mailles.",
426
- }, ensure_ascii=False)
427
-
428
- # Indicator exists but not at this maille
429
  available = resolver.get_available_mailles(ind_id)
430
- return json.dumps({
431
- "error": f"Indicator {ind_id} is not available at {geo_level} level.",
432
- "available_levels": available,
433
- "hint": f"Try one of: {', '.join(available)}",
434
- }, ensure_ascii=False)
435
-
436
- # Build the query
437
  geo_patterns = GEO_DIMENSION_PATTERNS[geo_level]
438
-
439
- # Measure and dimensions with full cube prefix
440
  measure = resolver.get_measure_name(cube_name, ind_id)
441
  geocode_dim = resolver.get_dimension_name(cube_name, geo_patterns["geocode"])
442
  libelle_dim = resolver.get_dimension_name(cube_name, geo_patterns["libelle"])
443
  annee_dim = resolver.get_dimension_name(cube_name, "annee")
444
-
 
445
  query: dict[str, Any] = {
446
  "measures": [measure],
447
  "dimensions": [geocode_dim, libelle_dim, annee_dim],
448
- "limit": 500,
449
  }
450
-
451
- # Add filters
452
  filters = []
453
-
454
- geo_code = geographic_code.strip() if geographic_code else None
455
  if geo_code:
456
- filters.append({
457
- "member": geocode_dim,
458
- "operator": "equals",
459
- "values": [geo_code],
460
- })
461
-
462
- year_filter = year.strip() if year else None
463
  if year_filter:
464
- filters.append({
465
- "member": annee_dim,
466
- "operator": "equals",
467
- "values": [year_filter],
468
- })
469
-
470
  if filters:
471
  query["filters"] = filters
472
-
473
- # Execute query
474
  client = get_client()
475
  try:
476
  result = await client.load(query)
477
  data_rows = result.get("data", [])
478
  except CubeJsClientError as e:
479
- return json.dumps({
480
- "error": f"Query failed: {str(e)}",
481
- "cube": cube_name,
482
- "query": query,
483
- }, ensure_ascii=False, indent=2)
484
-
485
- # Parse results
486
- data_points = []
487
- for row in data_rows:
488
- data_points.append({
489
  "geocode": row.get(geocode_dim),
490
  "libelle": row.get(libelle_dim),
491
  "annee": row.get(annee_dim),
492
- "valeur": row.get(measure),
493
- "unite": indicator_unite,
494
- })
495
-
496
- # Sort by year, then by libelle
497
  data_points.sort(key=lambda x: (x.get("annee") or "", x.get("libelle") or ""))
498
-
499
- return json.dumps({
 
 
500
  "indicator_id": ind_id,
501
  "indicator_name": indicator_name,
 
502
  "geographic_level": geo_level,
503
- "data": data_points,
 
504
  "total_count": len(data_points),
505
- "query_info": {
506
- "cube": cube_name,
507
- "measure": measure,
508
- "geographic_code_filter": geo_code,
509
- "year_filter": year_filter,
510
- },
511
- }, ensure_ascii=False, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
512
 
513
 
514
  @log_tool_call
515
- async def search_indicators(query: str) -> str:
516
- """Search indicators by keywords in their name or description.
517
-
518
- Performs a full-text search across indicator names (libelle) and descriptions.
519
- All search terms must be present for an indicator to match (AND logic).
520
-
 
521
  Args:
522
- query: Search terms separated by spaces. Examples:
523
- - "consommation espace" finds indicators about land consumption
524
- - "émissions CO2" finds indicators about CO2 emissions
525
- - "surface bio" finds organic surface indicators
526
-
527
  Returns:
528
- JSON string containing:
529
- - indicators: List of matching indicators with id, libelle, unite,
530
- mailles_disponibles, thematique_fnv
531
- - query: The original search query
532
- - total_count: Number of results
533
-
534
- Example:
535
- search_indicators("consommation espace") returns indicators mentioning
536
- both "consommation" and "espace" in their name or description.
537
  """
538
- await _ensure_cache_initialized()
539
- cache = get_cache()
540
-
541
- search_query = query.strip() if query else ""
542
-
543
- if not search_query:
544
- # Return all indicators if no query
545
- indicators = cache.list_indicators()
546
- else:
547
- indicators = cache.search_indicators(search_query)
548
-
549
- return json.dumps({
550
- "indicators": [ind.model_dump() for ind in indicators],
551
- "query": search_query,
552
- "total_count": len(indicators),
553
- }, ensure_ascii=False, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
554
 
555
 
556
  # Export all tools
557
  __all__ = [
558
  "list_indicators",
 
559
  "get_indicator_details",
560
  "query_indicator_data",
561
- "search_indicators",
562
  ]
 
1
+ """MCP tools for querying territorial ecological indicators.
2
+
3
+ Design notes (the tools are called by LLMs):
4
+ - every tool returns a compact JSON string (no indentation, ASCII kept as UTF-8);
5
+ - long lists are capped and the payload says so (`truncated`, `total_count`);
6
+ - errors are returned as JSON with a `hint`, never raised to the client;
7
+ - parameter names are stable (existing clients keep working).
8
+ """
9
 
10
  import json
11
  import logging
 
13
  import hashlib
14
  from collections import defaultdict
15
  from dataclasses import dataclass, field
 
16
  from functools import wraps
17
+ from typing import Any, Callable
18
 
19
+ from .api_client import get_client, CubeJsClientError
20
+ from .cache import fold_text, get_cache, initialize_cache, refresh_cache_if_needed
21
+ from .cube_resolver import get_resolver
22
+ from .models import (
23
+ SourceMetadata,
24
+ GEOGRAPHIC_LEVELS,
25
+ GEO_DIMENSION_PATTERNS,
26
+ REGION_CODES,
27
+ )
28
 
29
  # Configure logging
30
  logging.basicConfig(
 
34
  )
35
  logger = logging.getLogger("mcp_tools")
36
 
37
+ # Result caps (tokens matter for LLM clients)
38
+ LIST_MAX = 200 # list_indicators: catalogue is ~170 items, never truncated in practice
39
+ SEARCH_MAX = 30 # search_indicators
40
+ QUERY_DEFAULT_LIMIT = 100
41
+ QUERY_MAX_LIMIT = 500 # query_indicator_data: hard cap (Cube.js limit)
42
+ TERRITORY_MAX = 20
43
+
44
 
45
  # =============================================================================
46
  # Session Tracker - Track usage patterns across calls
 
54
  last_call_time: float = 0
55
  indicators_queried: set = field(default_factory=set)
56
  levels_queried: set = field(default_factory=set)
57
+
58
+ def add_call(self, tool: str, params: dict, duration_ms: int,
59
  result_count: int, response_size: int, status: str):
60
  """Record a tool call."""
61
  now = time.time()
62
  time_since_last = int((now - self.last_call_time) * 1000) if self.last_call_time else 0
63
+
64
  self.calls.append({
65
  "tool": tool,
66
  "params": params,
 
71
  "time_since_last_ms": time_since_last,
72
  })
73
  self.last_call_time = now
74
+
75
  # Track what's being queried
76
  if "indicator_id" in params:
77
  self.indicators_queried.add(params["indicator_id"])
78
  if "geographic_level" in params:
79
  self.levels_queried.add(params["geographic_level"])
80
+
81
  def get_sequence(self) -> str:
82
  """Get the sequence of tools called."""
83
+ return "→".join(c["tool"].replace("_indicators", "").replace("_indicator", "")
84
  for c in self.calls)
85
+
86
  def get_total_duration_ms(self) -> int:
87
  """Total time spent in API calls."""
88
  return sum(c["duration_ms"] for c in self.calls)
 
90
 
91
  class UsageTracker:
92
  """Track MCP usage patterns across sessions."""
93
+
94
  # Session timeout in seconds (new session if no call for 5 minutes)
95
  SESSION_TIMEOUT = 300
96
+
97
  def __init__(self):
98
  self.sessions: dict[str, SessionData] = {}
99
  self.patterns: defaultdict[str, int] = defaultdict(int) # sequence -> count
100
  self.tool_stats: defaultdict[str, dict] = defaultdict(
101
  lambda: {"calls": 0, "total_ms": 0, "errors": 0}
102
  )
103
+
104
  def get_or_create_session(self, session_hint: str = "default") -> SessionData:
105
  """Get existing session or create new one."""
106
  # Simple session management based on hint (could be IP, user-agent hash, etc.)
107
  session_id = hashlib.md5(session_hint.encode()).hexdigest()[:8]
108
+
109
  now = time.time()
110
+
111
  # Check if session exists and is not expired
112
  if session_id in self.sessions:
113
  session = self.sessions[session_id]
 
121
  session = SessionData(session_id=session_id)
122
  self.sessions[session_id] = session
123
  logger.info(f"[SESSION] id={session_id} | new_session")
124
+
125
  return session
126
+
127
  def _finalize_session(self, session: SessionData):
128
  """Log session summary when it ends."""
129
  if len(session.calls) > 1:
130
  sequence = session.get_sequence()
131
  self.patterns[sequence] += 1
132
+
133
  logger.info(
134
  f"[PATTERN] id={session.session_id} | "
135
  f"sequence={sequence} | "
 
138
  f"indicators={list(session.indicators_queried)} | "
139
  f"levels={list(session.levels_queried)}"
140
  )
141
+
142
  def log_stats_summary(self):
143
  """Log accumulated statistics."""
144
  if self.patterns:
 
156
  async def wrapper(*args, **kwargs):
157
  tool_name = func.__name__
158
  start_time = time.time()
159
+
160
  # Get or create session
161
  session = _tracker.get_or_create_session()
162
+
163
  # Extract params (only non-empty)
164
  params = {k: v for k, v in kwargs.items() if v}
165
+
166
  # Build context info
167
  call_num = len(session.calls) + 1
168
  prev_tool = session.calls[-1]["tool"] if session.calls else None
169
+
170
  # Log the call with context
171
  context = f"call#{call_num}"
172
  if prev_tool:
173
  context += f" | prev={prev_tool}"
174
  logger.info(f"[CALL] {tool_name} | {context} | params={params}")
175
+
176
  try:
177
  result = await func(*args, **kwargs)
178
  elapsed_ms = int((time.time() - start_time) * 1000)
179
  response_size = len(result.encode('utf-8'))
180
+
181
  # Parse result to get metrics
182
  status = "ok"
183
  result_count = 0
 
191
  )
192
  else:
193
  result_count = (
194
+ result_data.get("count") or
195
+ result_data.get("total_count") or
196
  len(result_data.get("data", [])) or
197
  (1 if "metadata" in result_data else 0)
198
  )
 
202
  )
203
  except json.JSONDecodeError:
204
  logger.info(f"[OK] {tool_name} | {elapsed_ms}ms | size={response_size}B")
205
+
206
  # Record in session
207
  session.add_call(
208
  tool=tool_name,
 
212
  response_size=response_size,
213
  status=status,
214
  )
215
+
216
  # Update global stats
217
  _tracker.tool_stats[tool_name]["calls"] += 1
218
  _tracker.tool_stats[tool_name]["total_ms"] += elapsed_ms
219
  if status == "error":
220
  _tracker.tool_stats[tool_name]["errors"] += 1
221
+
222
  return result
223
+
224
  except Exception as e:
225
  elapsed_ms = int((time.time() - start_time) * 1000)
226
  logger.error(f"[EXCEPTION] {tool_name} | {elapsed_ms}ms | {type(e).__name__}: {e}")
227
  _tracker.tool_stats[tool_name]["errors"] += 1
228
  raise
229
+
230
  return wrapper
 
 
 
 
 
 
 
 
 
231
 
232
 
233
+ # =============================================================================
234
+ # Helpers
235
+ # =============================================================================
236
+ def _dump(payload: dict[str, Any]) -> str:
237
+ """Compact JSON (fewer tokens for LLM clients)."""
238
+ return json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
239
+
240
+
241
+ def _error(message: str, **extra: Any) -> str:
242
+ return _dump({"error": message, **extra})
243
+
244
+
245
+ def _parse_int(value: str | int | None, default: int, lo: int, hi: int) -> int:
246
+ try:
247
+ n = int(value) # type: ignore[arg-type]
248
+ except (TypeError, ValueError):
249
+ return default
250
+ return max(lo, min(n, hi))
251
+
252
+
253
+ def _to_number(value: Any) -> Any:
254
+ """Cube.js returns numeric measures as strings; convert when possible."""
255
+ if isinstance(value, (int, float)) or value is None:
256
+ return value
257
+ try:
258
+ f = float(value)
259
+ except (TypeError, ValueError):
260
+ return value
261
+ return int(f) if f.is_integer() else round(f, 4)
262
+
263
+
264
+ def _split_csv(value: str | None) -> list[str]:
265
+ return [v.strip() for v in (value or "").split(",") if v.strip()]
266
+
267
+
268
+ def _list_item(ind: Any) -> dict[str, Any]:
269
+ return {
270
+ "id": ind.id,
271
+ "libelle": ind.libelle,
272
+ "unite": ind.unite,
273
+ "mailles": _split_csv(ind.mailles_disponibles),
274
+ "thematique": ind.thematique_fnv,
275
+ }
276
+
277
+
278
+ async def _ensure_cache_initialized() -> str | None:
279
+ """Ensure the cache is initialized; return an error JSON string on failure."""
280
  cache = get_cache()
281
+ try:
282
+ if not cache.is_initialized:
283
+ await initialize_cache()
284
+ else:
285
+ await refresh_cache_if_needed()
286
+ except ValueError as e: # missing token
287
+ return _error(f"Server misconfigured: {e}")
288
+ except CubeJsClientError as e:
289
+ if cache.is_initialized:
290
+ return None # stale cache is better than no answer
291
+ return _error(f"Indicators API unavailable: {e}", hint="Retry in a few seconds.")
292
+ return None
293
 
294
 
295
+ # =============================================================================
296
+ # MCP tools
297
+ # =============================================================================
298
  @log_tool_call
299
  async def list_indicators(
300
  thematique: str = "",
301
  maille: str = "",
302
  ) -> str:
303
+ """List the catalogue of French territorial ecological indicators (~170), optionally filtered.
304
+
305
+ Prefer search_indicators for a topic; use this tool to browse a theme or to know
306
+ what exists at a given geographic level.
307
+
 
308
  Args:
309
+ thematique: Optional France Nation Verte theme, partial and accent-insensitive match, e.g. "déplacer" (mobility), "loger" (housing), "produire", "nourrir", "consommer", "ecosystèmes".
310
+ maille: Optional geographic level the indicator must be available at: "region", "departement", "epci" or "commune".
311
+
 
 
312
  Returns:
313
+ JSON: count, indicators [{id, libelle, unite, mailles, thematique}], filters_applied, themes (distinct values, to refine).
 
 
 
 
 
314
  """
315
+ err = await _ensure_cache_initialized()
316
+ if err:
317
+ return err
318
  cache = get_cache()
319
+
 
320
  theme_filter = thematique.strip() if thematique else None
321
  maille_filter = maille.strip().lower() if maille else None
322
+
 
323
  if maille_filter and maille_filter not in GEOGRAPHIC_LEVELS:
324
+ return _error(f"Invalid geographic level: {maille}", valid_levels=GEOGRAPHIC_LEVELS)
325
+
326
+ indicators = cache.list_indicators(thematique=theme_filter, maille=maille_filter)
327
+ themes = sorted({i.thematique_fnv for i in cache.list_indicators() if i.thematique_fnv})
328
+
329
+ payload: dict[str, Any] = {
 
 
 
 
 
 
330
  "count": len(indicators),
331
+ "indicators": [_list_item(i) for i in indicators[:LIST_MAX]],
332
+ "filters_applied": {"thematique": theme_filter, "maille": maille_filter},
333
+ "themes": themes,
334
+ }
335
+ if len(indicators) > LIST_MAX:
336
+ payload["truncated"] = True
337
+ if not indicators:
338
+ payload["hint"] = "No indicator matches; try another theme (see `themes`) or search_indicators."
339
+ return _dump(payload)
340
+
341
+
342
+ @log_tool_call
343
+ async def search_indicators(query: str) -> str:
344
+ """Find indicators by keywords (French), e.g. "émissions gaz effet de serre", "surface bio", "artificialisation".
345
+
346
+ Accent-, case- and plural-insensitive; all words must match (in the name, description
347
+ or theme). Best matches first. Then call get_indicator_details(id) or query_indicator_data.
348
+
349
+ Args:
350
+ query: Keywords separated by spaces, e.g. "consommation espace", "stationnement vélo", "logements vacants".
351
+
352
+ Returns:
353
+ JSON: query, total_count, indicators [{id, libelle, unite, mailles, thematique}] (max 30), truncated flag.
354
+ """
355
+ err = await _ensure_cache_initialized()
356
+ if err:
357
+ return err
358
+ cache = get_cache()
359
+
360
+ search_query = query.strip() if query else ""
361
+ indicators = cache.search_indicators(search_query) if search_query else cache.list_indicators()
362
+
363
+ payload: dict[str, Any] = {
364
+ "query": search_query,
365
+ "total_count": len(indicators),
366
+ "indicators": [_list_item(i) for i in indicators[:SEARCH_MAX]],
367
+ }
368
+ if len(indicators) > SEARCH_MAX:
369
+ payload["truncated"] = True
370
+ payload["hint"] = "Refine with more specific keywords."
371
+ if not indicators:
372
+ payload["hint"] = "Try fewer or broader words (e.g. one noun), or list_indicators(thematique=...)."
373
+ return _dump(payload)
374
 
375
 
376
  @log_tool_call
377
  async def get_indicator_details(indicator_id: str) -> str:
378
+ """Full metadata of one indicator: definition, calculation method, available years and geographic levels, data completeness, sources.
379
+
 
 
 
380
  Args:
381
+ indicator_id: Numeric indicator id as returned by search_indicators / list_indicators (e.g. "611").
382
+
383
  Returns:
384
+ JSON: metadata {id, libelle, unite, description, methode_calcul, annees_disponibles [..], mailles_disponibles [..], couverture_geographique, completion {level: ratio 0-1}}, sources [..], available_cubes {level: cube}.
 
 
 
 
 
 
 
 
385
  """
386
+ err = await _ensure_cache_initialized()
387
+ if err:
388
+ return err
389
+
390
  try:
391
+ ind_id = int(str(indicator_id).strip())
392
  except ValueError:
393
+ return _error(f"Invalid indicator ID: {indicator_id}. Must be a number.")
394
+
 
 
395
  cache = get_cache()
396
  indicator = cache.get_indicator(ind_id)
 
397
  if indicator is None:
398
+ return _error(
399
+ f"Indicator {ind_id} not found.",
400
+ hint="Use search_indicators(query) to find the right id.",
401
+ )
402
+
 
403
  resolver = get_resolver()
404
  available_cubes = resolver.get_cubes_for_indicator(ind_id)
405
+
406
+ # Sources: request only dimensions that the API actually exposes
407
  client = get_client()
408
+ sources: list[dict[str, Any]] = []
409
+ sources_warning: str | None = None
410
  try:
411
+ rows = await client.load_sources_metadata(
412
+ indicator_id=ind_id,
413
+ available_dimensions=resolver.get_cube_dimensions("indicateur_x_source_metadata"),
414
+ )
415
+ for row in rows:
416
+ src = SourceMetadata.from_api_response(row).model_dump(exclude_none=True)
417
+ src.pop("id_indicateur", None)
418
+ sources.append(src)
419
  except CubeJsClientError as e:
420
+ sources_warning = f"Could not fetch sources: {e}"
421
+
422
+ metadata = {
423
+ "id": indicator.id,
424
+ "libelle": indicator.libelle,
425
+ "unite": indicator.unite,
426
+ "description": indicator.description,
427
+ "methode_calcul": indicator.methode_calcul,
428
+ "annees_disponibles": _split_csv(indicator.annees_disponibles),
429
+ "mailles_disponibles": _split_csv(indicator.mailles_disponibles),
430
+ "maille_mini_disponible": indicator.maille_mini_disponible,
431
+ "couverture_geographique": indicator.couverture_geographique,
432
+ "completion": {
433
+ level: indicator.get_completion_for_level(level)
434
+ for level in GEOGRAPHIC_LEVELS
435
+ if indicator.get_completion_for_level(level) is not None
436
+ },
437
+ "thematique": indicator.thematique_fnv,
438
+ }
439
+ result: dict[str, Any] = {
440
+ "metadata": metadata,
441
  "sources": sources,
442
  "available_cubes": available_cubes,
443
  }
444
+ if sources_warning:
445
+ result["sources_warning"] = sources_warning
446
+ if not available_cubes:
447
+ result["hint"] = "No data cube found for this indicator: values cannot be queried."
448
+ return _dump(result)
449
 
450
 
451
  @log_tool_call
 
454
  geographic_level: str,
455
  geographic_code: str = "",
456
  year: str = "",
457
+ limit: int = QUERY_DEFAULT_LIMIT,
458
  ) -> str:
459
+ """Get the values of an indicator for territories (one territory, or all territories of a level).
460
+
461
+ Without geographic_code, returns every territory of the level (use `year` and `limit`
462
+ to keep it small: there are 13 regions, ~100 départements, ~1 250 EPCI, ~35 000 communes).
463
+ Without year, returns all available years. Use find_territory to get a code from a name.
464
+
465
  Args:
466
+ indicator_id: Numeric indicator id (e.g. "611").
467
+ geographic_level: "region", "departement", "epci" or "commune".
468
+ geographic_code: Optional territory code: region 2 digits ("93" PACA, "11" Île-de-France), département 2-3 chars ("13", "2A", "974"), EPCI 9-digit SIREN, commune 5-digit INSEE ("75056" Paris).
469
+ year: Optional year, e.g. "2022".
470
+ limit: Max rows returned (default 100, max 500).
471
+
 
 
 
 
472
  Returns:
473
+ JSON: indicator_id, indicator_name, unite, geographic_level, total_count, truncated, data [{geocode, libelle, annee, valeur}], annees_disponibles, cube.
 
 
 
 
 
 
 
 
 
 
 
 
474
  """
475
+ err = await _ensure_cache_initialized()
476
+ if err:
477
+ return err
478
+
479
  try:
480
+ ind_id = int(str(indicator_id).strip())
481
  except ValueError:
482
+ return _error(f"Invalid indicator ID: {indicator_id}. Must be a number.")
483
+
484
+ geo_level = (geographic_level or "").strip().lower()
 
 
 
485
  if geo_level not in GEOGRAPHIC_LEVELS:
486
+ return _error(f"Invalid geographic level: {geographic_level}", valid_levels=GEOGRAPHIC_LEVELS)
487
+
488
+ max_rows = _parse_int(limit, QUERY_DEFAULT_LIMIT, 1, QUERY_MAX_LIMIT)
489
+
 
490
  cache = get_cache()
491
  resolver = get_resolver()
 
492
  indicator = cache.get_indicator(ind_id)
493
  indicator_name = indicator.libelle if indicator else f"Indicator {ind_id}"
494
  indicator_unite = indicator.unite if indicator else None
495
+ years_available = _split_csv(indicator.annees_disponibles) if indicator else []
496
+
497
  cube_name = resolver.find_cube_for_indicator(ind_id, geo_level)
 
498
  if cube_name is None:
 
499
  if not resolver.is_indicator_known(ind_id):
500
+ return _error(
501
+ f"Indicator {ind_id} not found in any data cube.",
502
+ hint="Use search_indicators(query) to find a valid id.",
503
+ )
 
 
504
  available = resolver.get_available_mailles(ind_id)
505
+ return _error(
506
+ f"Indicator {ind_id} is not available at {geo_level} level.",
507
+ available_levels=available,
508
+ hint=f"Try one of: {', '.join(available)}",
509
+ )
510
+
 
511
  geo_patterns = GEO_DIMENSION_PATTERNS[geo_level]
 
 
512
  measure = resolver.get_measure_name(cube_name, ind_id)
513
  geocode_dim = resolver.get_dimension_name(cube_name, geo_patterns["geocode"])
514
  libelle_dim = resolver.get_dimension_name(cube_name, geo_patterns["libelle"])
515
  annee_dim = resolver.get_dimension_name(cube_name, "annee")
516
+
517
+ # Ask for one extra row to detect truncation
518
  query: dict[str, Any] = {
519
  "measures": [measure],
520
  "dimensions": [geocode_dim, libelle_dim, annee_dim],
521
+ "limit": max_rows + 1,
522
  }
 
 
523
  filters = []
524
+ geo_code = (geographic_code or "").strip()
 
525
  if geo_code:
526
+ filters.append({"member": geocode_dim, "operator": "equals", "values": [geo_code]})
527
+ year_filter = (year or "").strip()
 
 
 
 
 
528
  if year_filter:
529
+ filters.append({"member": annee_dim, "operator": "equals", "values": [year_filter]})
 
 
 
 
 
530
  if filters:
531
  query["filters"] = filters
532
+
 
533
  client = get_client()
534
  try:
535
  result = await client.load(query)
536
  data_rows = result.get("data", [])
537
  except CubeJsClientError as e:
538
+ return _error(f"Query failed: {e}", cube=cube_name)
539
+
540
+ data_points = [
541
+ {
 
 
 
 
 
 
542
  "geocode": row.get(geocode_dim),
543
  "libelle": row.get(libelle_dim),
544
  "annee": row.get(annee_dim),
545
+ "valeur": _to_number(row.get(measure)),
546
+ }
547
+ for row in data_rows
548
+ ]
 
549
  data_points.sort(key=lambda x: (x.get("annee") or "", x.get("libelle") or ""))
550
+ truncated = len(data_points) > max_rows
551
+ data_points = data_points[:max_rows]
552
+
553
+ payload: dict[str, Any] = {
554
  "indicator_id": ind_id,
555
  "indicator_name": indicator_name,
556
+ "unite": indicator_unite,
557
  "geographic_level": geo_level,
558
+ "geographic_code": geo_code or None,
559
+ "year": year_filter or None,
560
  "total_count": len(data_points),
561
+ "truncated": truncated,
562
+ "data": data_points,
563
+ "annees_disponibles": years_available,
564
+ "cube": cube_name,
565
+ }
566
+ if truncated:
567
+ payload["hint"] = (
568
+ f"Only the first {max_rows} rows are returned: filter with geographic_code and/or year, "
569
+ f"or raise limit (max {QUERY_MAX_LIMIT})."
570
+ )
571
+ if not data_points:
572
+ hints = []
573
+ if year_filter and years_available and year_filter not in years_available:
574
+ hints.append(f"Year {year_filter} is not available (available: {', '.join(years_available)}).")
575
+ if geo_code:
576
+ hints.append(
577
+ "Check the code format for this level (region: 2 digits, département: 2-3 chars, "
578
+ "EPCI: 9-digit SIREN, commune: 5-digit INSEE) or use find_territory(name, level)."
579
+ )
580
+ payload["hint"] = " ".join(hints) or "No data for these filters."
581
+ return _dump(payload)
582
 
583
 
584
  @log_tool_call
585
+ async def find_territory(name: str, geographic_level: str = "") -> str:
586
+ """Find the official code of a French territory from (part of) its name, e.g. "Lyon", "Bouches-du-Rhône", "Grand Paris".
587
+
588
+ Use it before query_indicator_data when the code is unknown (EPCI SIREN and commune
589
+ INSEE codes are hard to guess). Regions are resolved locally; other levels are looked
590
+ up in the indicators API.
591
+
592
  Args:
593
+ name: Territory name or fragment, accent-insensitive (e.g. "Métropole de Lyon", "Toulouse", "2A").
594
+ geographic_level: Optional level to restrict the search: "region", "departement", "epci" or "commune". Default: all levels.
595
+
 
 
596
  Returns:
597
+ JSON: name, total_count, territories [{geographic_level, geocode, libelle}] (max 20 per level).
 
 
 
 
 
 
 
 
598
  """
599
+ search = (name or "").strip()
600
+ if not search:
601
+ return _error("name is required.")
602
+
603
+ level = (geographic_level or "").strip().lower()
604
+ if level and level not in GEOGRAPHIC_LEVELS:
605
+ return _error(f"Invalid geographic level: {geographic_level}", valid_levels=GEOGRAPHIC_LEVELS)
606
+ levels = [level] if level else GEOGRAPHIC_LEVELS
607
+
608
+ found: list[dict[str, Any]] = []
609
+ warnings: list[str] = []
610
+ folded = fold_text(search)
611
+
612
+ if "region" in levels:
613
+ for code, label in REGION_CODES.items():
614
+ if folded in fold_text(label) or folded == code:
615
+ found.append({"geographic_level": "region", "geocode": code, "libelle": label})
616
+
617
+ other_levels = [lv for lv in levels if lv != "region"]
618
+ if other_levels:
619
+ err = await _ensure_cache_initialized()
620
+ if err:
621
+ return err
622
+ resolver = get_resolver()
623
+ client = get_client()
624
+ for lv in other_levels:
625
+ cube_name = resolver.find_cube_with_maille(lv)
626
+ if cube_name is None:
627
+ warnings.append(f"No data cube exposes the {lv} level.")
628
+ continue
629
+ patterns = GEO_DIMENSION_PATTERNS[lv]
630
+ try:
631
+ rows = await client.find_territories(
632
+ cube_name, patterns["geocode"], patterns["libelle"], search, limit=TERRITORY_MAX * 3
633
+ )
634
+ except CubeJsClientError as e:
635
+ warnings.append(f"{lv}: lookup failed ({e})")
636
+ continue
637
+ geocode_dim = f"{cube_name}.{patterns['geocode']}"
638
+ libelle_dim = f"{cube_name}.{patterns['libelle']}"
639
+ seen: set[str] = set()
640
+ for row in rows:
641
+ code = row.get(geocode_dim)
642
+ if not code or code in seen:
643
+ continue
644
+ seen.add(code)
645
+ found.append({"geographic_level": lv, "geocode": code, "libelle": row.get(libelle_dim)})
646
+ if len(seen) >= TERRITORY_MAX:
647
+ break
648
+
649
+ payload: dict[str, Any] = {"name": search, "total_count": len(found), "territories": found}
650
+ if warnings:
651
+ payload["warnings"] = warnings
652
+ if not found:
653
+ payload["hint"] = "No territory matches; try a shorter fragment or another spelling."
654
+ return _dump(payload)
655
 
656
 
657
  # Export all tools
658
  __all__ = [
659
  "list_indicators",
660
+ "search_indicators",
661
  "get_indicator_details",
662
  "query_indicator_data",
663
+ "find_territory",
664
  ]
tests/__init__.py ADDED
File without changes
tests/fake_api.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fake Cube.js client for offline tests.
2
+
3
+ Reproduces the behaviour of the real Indicateurs API observed on the live Space
4
+ (tests/live_capture.json): metadata cube, source cube whose dimensions do NOT
5
+ include `libelle`, data cubes named {theme}_{maille} with measures `id_{n}` and
6
+ geographic dimensions geocode_*/libelle_*, string-typed numeric values, `limit`,
7
+ `equals` and `contains` filters.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ from src.api_client import BadRequestError, CubeJsClient
17
+ from src.models import REGION_CODES
18
+
19
+ CAPTURE = json.loads((Path(__file__).parent / "live_capture.json").read_text(encoding="utf-8"))
20
+
21
+ META_DIMS = [
22
+ "id", "libelle", "unite", "description", "methode_calcul", "annees_disponibles",
23
+ "mailles_disponibles", "maille_mini_disponible", "couverture_geographique",
24
+ "completion_region", "completion_departement", "completion_epci", "completion_commune",
25
+ "thematique_fnv",
26
+ ]
27
+ # As on the real API: no `libelle` dimension on the source cube.
28
+ SOURCE_DIMS = [
29
+ "id_indicateur", "nom_source", "description", "producteur_source",
30
+ "distributeur_source", "license_source", "lien_page", "date_derniere_extraction",
31
+ ]
32
+ GEO_DIMS = {
33
+ "commune": ["geocode_commune", "libelle_commune"],
34
+ "epci": ["geocode_epci", "libelle_epci"],
35
+ "departement": ["geocode_departement", "libelle_departement"],
36
+ "region": ["geocode_region", "libelle_region"],
37
+ }
38
+ # cube -> (levels, indicator ids) — from the captured available_cubes
39
+ DATA_CUBES = {
40
+ "conso_enaf_com": (["commune", "epci", "departement", "region"], [611, 545]),
41
+ "stationnement_velo_habitant_com": (["commune", "epci", "departement", "region"], [94]),
42
+ "surfaces_agricoles_com": (["commune"], [23]),
43
+ "surface_bio_epci": (["epci", "region"], [23]),
44
+ "surface_bio_dpt": (["departement", "region"], [23, 42]),
45
+ "dechets_population_dpt": (["departement", "region"], [42]),
46
+ }
47
+ YEARS = ["2020", "2021", "2022"]
48
+
49
+ # Synthetic territories (enough to exercise truncation on communes)
50
+ TERRITORIES: dict[str, list[tuple[str, str]]] = {
51
+ "region": list(REGION_CODES.items()),
52
+ "departement": [(f"{i:02d}", f"Département {i:02d}") for i in range(1, 96) if i != 20]
53
+ + [("2A", "Corse-du-Sud"), ("2B", "Haute-Corse"), ("13", "Bouches-du-Rhône"), ("69", "Rhône")],
54
+ "epci": [
55
+ ("200046977", "Métropole de Lyon"),
56
+ ("200054781", "Métropole du Grand Paris"),
57
+ ("200054807", "Métropole d'Aix-Marseille-Provence"),
58
+ ("243100518", "Toulouse Métropole"),
59
+ ]
60
+ + [(f"2000{i:05d}", f"Communauté de communes n°{i}") for i in range(1, 60)],
61
+ "commune": [("75056", "Paris"), ("13055", "Marseille"), ("69123", "Lyon"), ("31555", "Toulouse")]
62
+ + [(f"{i:05d}", f"Commune {i}") for i in range(1000, 1700)],
63
+ }
64
+ TERRITORIES["departement"] = list(dict.fromkeys(TERRITORIES["departement"]))
65
+
66
+
67
+ def _indicator_rows() -> list[dict[str, Any]]:
68
+ """All indicators known from the capture, richest metadata when available."""
69
+ rows: dict[int, dict[str, Any]] = {}
70
+ for item in CAPTURE["list_all"]["indicators"]:
71
+ rows[item["id"]] = dict(item)
72
+ for key, det in CAPTURE["details"].items():
73
+ rows[int(key)].update(det["metadata"])
74
+ return [rows[k] for k in sorted(rows)]
75
+
76
+
77
+ class FakeCubeJsClient(CubeJsClient):
78
+ def __init__(self) -> None:
79
+ super().__init__(token="fake-token")
80
+ self.queries: list[dict[str, Any]] = []
81
+ self.fail_meta = False
82
+
83
+ async def get_meta(self) -> dict[str, Any]:
84
+ if self.fail_meta:
85
+ raise BadRequestError("meta unavailable")
86
+ cubes = [
87
+ {"name": "indicateur_metadata", "measures": [], "dimensions": [
88
+ {"name": f"indicateur_metadata.{d}"} for d in META_DIMS]},
89
+ {"name": "indicateur_x_source_metadata", "measures": [], "dimensions": [
90
+ {"name": f"indicateur_x_source_metadata.{d}"} for d in SOURCE_DIMS]},
91
+ ]
92
+ for cube, (levels, ids) in DATA_CUBES.items():
93
+ dims = ["annee"] + [d for lv in levels for d in GEO_DIMS[lv]]
94
+ cubes.append({
95
+ "name": cube,
96
+ "measures": [{"name": f"{cube}.id_{i}"} for i in ids],
97
+ "dimensions": [{"name": f"{cube}.{d}"} for d in dims],
98
+ })
99
+ return {"cubes": cubes}
100
+
101
+ async def load(self, query: dict[str, Any]) -> dict[str, Any]:
102
+ self.queries.append(query)
103
+ dims: list[str] = query.get("dimensions", [])
104
+ measures: list[str] = query.get("measures", [])
105
+ limit = int(query.get("limit", 10000))
106
+ filters = query.get("filters", [])
107
+ members = dims + measures
108
+ cube = members[0].split(".")[0] if members else ""
109
+
110
+ if cube == "indicateur_metadata":
111
+ rows = [{f"indicateur_metadata.{k}": v for k, v in r.items()} for r in _indicator_rows()]
112
+ elif cube == "indicateur_x_source_metadata":
113
+ for d in dims:
114
+ if d.split(".", 1)[1] not in SOURCE_DIMS:
115
+ raise BadRequestError(
116
+ f"Bad request to API. Details: {{'type': 'UserError', 'error': \"'{d.split('.', 1)[1]}' "
117
+ f"not found for path '{d}'\"}}"
118
+ )
119
+ rows = [{
120
+ "indicateur_x_source_metadata.id_indicateur": 611,
121
+ "indicateur_x_source_metadata.nom_source": "fichiers_fonciers",
122
+ "indicateur_x_source_metadata.description": "Fichiers fonciers (Cerema)",
123
+ "indicateur_x_source_metadata.producteur_source": "Cerema",
124
+ "indicateur_x_source_metadata.distributeur_source": "Cerema",
125
+ "indicateur_x_source_metadata.license_source": "Licence ouverte",
126
+ "indicateur_x_source_metadata.lien_page": "https://artificialisation.developpement-durable.gouv.fr",
127
+ "indicateur_x_source_metadata.date_derniere_extraction": "2024-06-01",
128
+ }]
129
+ elif cube in DATA_CUBES:
130
+ rows = self._data_rows(cube, dims, measures)
131
+ else:
132
+ raise BadRequestError(f"Unknown cube {cube}")
133
+
134
+ for f in filters:
135
+ member, op, values = f["member"], f["operator"], [str(v) for v in f["values"]]
136
+ if op == "equals":
137
+ rows = [r for r in rows if str(r.get(member)) in values]
138
+ elif op == "contains":
139
+ needle = values[0].lower()
140
+ rows = [r for r in rows if needle in str(r.get(member, "")).lower()]
141
+ if dims and not measures:
142
+ # Cube.js dedupes dimension-only queries
143
+ seen, uniq = set(), []
144
+ for r in rows:
145
+ key = tuple(r.get(d) for d in dims)
146
+ if key not in seen:
147
+ seen.add(key)
148
+ uniq.append({d: r.get(d) for d in dims})
149
+ rows = uniq
150
+ return {"data": rows[:limit]}
151
+
152
+ def _data_rows(self, cube: str, dims: list[str], measures: list[str]) -> list[dict[str, Any]]:
153
+ levels = [lv for lv in GEO_DIMS if f"{cube}.{GEO_DIMS[lv][0]}" in dims]
154
+ if not levels:
155
+ return []
156
+ level = levels[0]
157
+ real = CAPTURE["query_611_reg_93"]["data"] if (cube == "conso_enaf_com" and level == "region") else None
158
+ rows = []
159
+ for code, label in TERRITORIES[level]:
160
+ for year in YEARS:
161
+ row = {
162
+ f"{cube}.{GEO_DIMS[level][0]}": code,
163
+ f"{cube}.{GEO_DIMS[level][1]}": label,
164
+ f"{cube}.annee": year,
165
+ }
166
+ for m in measures:
167
+ value = f"{(hash((code, year, m)) % 100000) / 10:.4f}"
168
+ if real and code == "93":
169
+ match = next((r for r in real if r["annee"] == year), None)
170
+ if match:
171
+ value = match["valeur"]
172
+ row[m] = value
173
+ rows.append(row)
174
+ return rows
tests/live_capture.json ADDED
The diff for this file is too large to render. See raw diff
 
tests/run_fake_server.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Launch the Gradio/MCP app on the fake backend (no API token needed).
2
+
3
+ Usage: GRADIO_SERVER_PORT=7861 python tests/run_fake_server.py
4
+ """
5
+
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
10
+
11
+ import src.api_client as api_client # noqa: E402
12
+ from tests.fake_api import FakeCubeJsClient # noqa: E402
13
+
14
+ api_client._client_instance = FakeCubeJsClient()
15
+
16
+ import app # noqa: E402
17
+
18
+ if __name__ == "__main__":
19
+ app.demo.launch(mcp_server=True, server_name="127.0.0.1", server_port=int(__import__("os").environ.get("GRADIO_SERVER_PORT", "7861")))
tests/test_tools.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Offline tests of the MCP tools against the fake Cube.js backend.
2
+
3
+ Run: python -m unittest discover -s tests -v
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import sys
10
+ import unittest
11
+ from pathlib import Path
12
+
13
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
14
+
15
+ import src.api_client as api_client # noqa: E402
16
+ import src.cache as cache_mod # noqa: E402
17
+ import src.cube_resolver as resolver_mod # noqa: E402
18
+ from src.tools import ( # noqa: E402
19
+ find_territory,
20
+ get_indicator_details,
21
+ list_indicators,
22
+ query_indicator_data,
23
+ search_indicators,
24
+ )
25
+ from tests.fake_api import FakeCubeJsClient # noqa: E402
26
+
27
+
28
+ class ToolsTestCase(unittest.IsolatedAsyncioTestCase):
29
+ def setUp(self) -> None:
30
+ # Fresh singletons bound to the fake backend
31
+ api_client._client_instance = FakeCubeJsClient()
32
+ resolver_mod._resolver_instance = None
33
+ cache_mod._cache_instance = None
34
+
35
+ @property
36
+ def fake(self) -> FakeCubeJsClient:
37
+ return api_client._client_instance # type: ignore[return-value]
38
+
39
+ # ------------------------------------------------------------------ format
40
+ async def test_outputs_are_compact_json(self) -> None:
41
+ for raw in (
42
+ await list_indicators(),
43
+ await search_indicators("espace"),
44
+ await get_indicator_details("611"),
45
+ await query_indicator_data("611", "region", "93"),
46
+ ):
47
+ self.assertNotIn("\n", raw)
48
+ self.assertIsInstance(json.loads(raw), dict)
49
+
50
+ # ------------------------------------------------------------------ list
51
+ async def test_list_all(self) -> None:
52
+ payload = json.loads(await list_indicators())
53
+ self.assertEqual(payload["count"], 168)
54
+ self.assertEqual(len(payload["indicators"]), 168)
55
+ self.assertNotIn("truncated", payload)
56
+ item = next(i for i in payload["indicators"] if i["id"] == 611)
57
+ self.assertEqual(item["mailles"], ["commune", "epci", "departement", "region"])
58
+ self.assertIn("Mieux se déplacer", payload["themes"])
59
+
60
+ async def test_list_filters_accent_insensitive(self) -> None:
61
+ a = json.loads(await list_indicators(thematique="deplacer"))
62
+ b = json.loads(await list_indicators(thematique="Déplacer"))
63
+ self.assertEqual(a["count"], b["count"])
64
+ self.assertEqual(a["count"], 58)
65
+ c = json.loads(await list_indicators(thematique="déplacer", maille="commune"))
66
+ self.assertLess(c["count"], a["count"])
67
+ self.assertTrue(all("commune" in i["mailles"] for i in c["indicators"]))
68
+
69
+ async def test_list_invalid_maille(self) -> None:
70
+ payload = json.loads(await list_indicators(maille="pays"))
71
+ self.assertIn("error", payload)
72
+ self.assertIn("valid_levels", payload)
73
+
74
+ # ------------------------------------------------------------------ search
75
+ async def test_search_accents_and_plural(self) -> None:
76
+ with_acc = json.loads(await search_indicators("émissions gaz effet de serre"))
77
+ without = json.loads(await search_indicators("emission gaz effet serre"))
78
+ self.assertTrue(with_acc["indicators"])
79
+ self.assertEqual(
80
+ [i["id"] for i in with_acc["indicators"]], [i["id"] for i in without["indicators"]]
81
+ )
82
+
83
+ async def test_search_libelle_first(self) -> None:
84
+ payload = json.loads(await search_indicators("consommation espace"))
85
+ ids = [i["id"] for i in payload["indicators"]]
86
+ self.assertIn(611, ids[:2])
87
+ self.assertIn(545, ids[:2])
88
+
89
+ async def test_search_capped(self) -> None:
90
+ payload = json.loads(await search_indicators("de"))
91
+ self.assertLessEqual(len(payload["indicators"]), 30)
92
+ self.assertTrue(payload["truncated"])
93
+ self.assertGreater(payload["total_count"], 30)
94
+
95
+ async def test_search_no_match(self) -> None:
96
+ payload = json.loads(await search_indicators("blockchain"))
97
+ self.assertEqual(payload["total_count"], 0)
98
+ self.assertIn("hint", payload)
99
+
100
+ # ------------------------------------------------------------------ details
101
+ async def test_details_sources_use_existing_dimensions(self) -> None:
102
+ payload = json.loads(await get_indicator_details("611"))
103
+ self.assertNotIn("sources_warning", payload)
104
+ self.assertEqual(payload["sources"][0]["producteur_source"], "Cerema")
105
+ self.assertNotIn("id_indicateur", payload["sources"][0])
106
+ self.assertEqual(payload["metadata"]["annees_disponibles"][0], "2009")
107
+ self.assertEqual(payload["available_cubes"]["commune"], "conso_enaf_com")
108
+ self.assertAlmostEqual(payload["metadata"]["completion"]["region"], 0.8947)
109
+ # the source query never asked for the non-existent `libelle` dimension
110
+ src_queries = [q for q in self.fake.queries if q["dimensions"][0].startswith("indicateur_x_source")]
111
+ self.assertTrue(src_queries)
112
+ self.assertNotIn("indicateur_x_source_metadata.libelle", src_queries[0]["dimensions"])
113
+
114
+ async def test_details_unknown_and_invalid(self) -> None:
115
+ self.assertIn("error", json.loads(await get_indicator_details("999999")))
116
+ self.assertIn("error", json.loads(await get_indicator_details("abc")))
117
+
118
+ # ------------------------------------------------------------------ query
119
+ async def test_query_one_territory(self) -> None:
120
+ payload = json.loads(await query_indicator_data("611", "region", "93"))
121
+ self.assertEqual(payload["unite"], "ha")
122
+ self.assertFalse(payload["truncated"])
123
+ self.assertEqual(payload["total_count"], 3)
124
+ row = payload["data"][0]
125
+ self.assertEqual(row["geocode"], "93")
126
+ self.assertIsInstance(row["valeur"], float) # converted from string
127
+ self.assertEqual(payload["annees_disponibles"][-1], "2023")
128
+
129
+ async def test_query_truncation_and_limit(self) -> None:
130
+ payload = json.loads(await query_indicator_data("611", "commune", year="2021"))
131
+ self.assertEqual(payload["total_count"], 100)
132
+ self.assertTrue(payload["truncated"])
133
+ self.assertIn("hint", payload)
134
+ big = json.loads(await query_indicator_data("611", "commune", year="2021", limit=500))
135
+ self.assertEqual(big["total_count"], 500)
136
+ self.assertTrue(big["truncated"])
137
+ small = json.loads(await query_indicator_data("611", "region", year="2021", limit=5))
138
+ self.assertEqual(small["total_count"], 5)
139
+ self.assertTrue(small["truncated"])
140
+ # limit is clamped, never rejected
141
+ clamped = json.loads(await query_indicator_data("611", "region", year="2021", limit=9999))
142
+ self.assertEqual(clamped["total_count"], 13)
143
+ self.assertFalse(clamped["truncated"])
144
+
145
+ async def test_query_wrong_level_and_hints(self) -> None:
146
+ payload = json.loads(await query_indicator_data("42", "commune"))
147
+ self.assertIn("error", payload)
148
+ self.assertEqual(payload["available_levels"], ["departement", "region"])
149
+ empty = json.loads(await query_indicator_data("611", "region", "93", year="1999"))
150
+ self.assertEqual(empty["total_count"], 0)
151
+ self.assertIn("1999 is not available", empty["hint"])
152
+ bad_code = json.loads(await query_indicator_data("611", "departement", "Rhône"))
153
+ self.assertIn("find_territory", bad_code["hint"])
154
+
155
+ # ------------------------------------------------------------------ territory
156
+ async def test_find_territory_region_local(self) -> None:
157
+ payload = json.loads(await find_territory("provence", "region"))
158
+ self.assertEqual(payload["territories"][0]["geocode"], "93")
159
+ self.assertFalse(self.fake.queries) # regions resolved without the API
160
+
161
+ async def test_find_territory_epci_and_commune(self) -> None:
162
+ payload = json.loads(await find_territory("Lyon"))
163
+ levels = {t["geographic_level"]: t for t in payload["territories"]}
164
+ self.assertEqual(levels["epci"]["geocode"], "200046977")
165
+ self.assertEqual(levels["commune"]["geocode"], "69123")
166
+ self.assertNotIn("departement", levels)
167
+ dpt = json.loads(await find_territory("rhône", "departement"))
168
+ self.assertEqual({t["geocode"] for t in dpt["territories"]}, {"13", "69"})
169
+
170
+ async def test_find_territory_invalid(self) -> None:
171
+ self.assertIn("error", json.loads(await find_territory("", "epci")))
172
+ self.assertIn("error", json.loads(await find_territory("Lyon", "pays")))
173
+
174
+ # ------------------------------------------------------------------ resilience
175
+ async def test_api_down_before_first_load(self) -> None:
176
+ self.fake.fail_meta = True
177
+ payload = json.loads(await search_indicators("espace"))
178
+ self.assertIn("error", payload)
179
+ self.assertIn("hint", payload)
180
+
181
+
182
+ if __name__ == "__main__":
183
+ unittest.main()