Skip to main content
Glama
malkreide

swiss-housing-mcp

by malkreide

swiss-housing-mcp

Parte del Swiss Public Data MCP Portfolio — servidores MCP de código abierto que conectan agentes de IA con datos públicos suizos. Proyecto privado, independiente de cualquier empleador o afiliación institucional.

Version License: MIT Python MCP

Servidor MCP para el Registro Federal Suizo de Edificios y Viviendas (GWR/RegBL) — edificios, viviendas y el pipeline de construcción

🇩🇪 Versión alemana


🎯 Consulta de demostración ancla

«¿Cuántas viviendas se construyeron nuevas en la ciudad de Zúrich desde 2020, cuántas con 4+ habitaciones — y cuántas están actualmente en construcción?»

Verificado contra el volcado en vivo el 2026-07-24: 16'164 viviendas nuevas desde 2020 (27.4% con 4+ habitaciones — el proxy de vivienda familiar), y 7'287 viviendas actualmente en construcción. Las viviendas en construcción hoy son hogares en 1–3 años: el indicador temprano para la planificación de espacio escolar.

Demo

Demo: Claude usando new_construction y construction_pipeline


Related MCP server: swiss-statistics-mcp

Resumen

El GWR/RegBL es para los edificios lo que Zefix es para las empresas: no una fuente de datos entre muchas, sino el registro federal cuyos identificadores (EGID para edificios, EWID para viviendas) sirven como claves de unión entre los datos administrativos suizos. Este servidor expone el extracto público del registro a través de herramientas MCP — búsquedas de edificios, geocodificación de direcciones, estadísticas de construcción por municipio, análisis de cajas delimitadoras sub-municipales y el pipeline de planificación/construcción.

address_to_egid es el enchufe que hace que otras fuentes de datos sean compatibles con EGID: dirección de entrada, identificador federal y coordenadas LV95 de salida.

Decisión de arquitectura

Este servidor utiliza Arquitectura B (Híbrida: volcado primero, API como respaldo).

Racional (verificado en vivo el 2026-07-24):

  • El volcado cantonal público (public.madd.bfs.admin.ch/{canton}.zip) se actualiza diariamente (~05:30 CET) e incluye un data.sqlite listo con las tablas building (399'830 filas para ZH), entrance, dwelling (894'631 filas para ZH) y code. Sin análisis de CSV, sin autenticación.

  • api3.geo.admin.ch (find / identify / SearchServer) funciona de manera confiable sin autenticación para búsquedas de entidades individuales y geocodificación, pero no escala a agregaciones de área amplia (límites de resultados).

  • Un endpoint REST de MADD probado en /api/buildings/{egid} devolvió 404; se excluye hasta que se aclaren la ruta y el estado de autenticación — no es un bloqueador, ya que todas las herramientas de la Fase 1 funcionan sin él.

Consecuencias:

  • Los volcados cantonales se almacenan en caché en disco con un TTL de 24 h (configurable mediante SWISS_HOUSING_DUMP_TTL_HOURS).

  • Las agregaciones y consultas espaciales se ejecutan como SQL de solo lectura contra el SQLite en caché; las búsquedas individuales y la geocodificación acceden a la API en vivo.

  • Cada respuesta lleva source (atribución) y provenance (daily_dump | live_api | cached).

Hallazgos de la sonda en vivo (2026-07-24)

Endpoint

HTTP

Estado

Nota

api3.geo.admin.ch …/find (búsqueda EGID)

200

✅ funciona

conjunto completo de atributos, sin autenticación

api3.geo.admin.ch …/identify (coordenadas)

200

✅ funciona

77 atributos incl. EGID/EWID

…/SearchServer (dirección → EGID)

200

✅ funciona

featureId = {EGID}_{EDID}; intercambio de ejes: y=este, x=norte

public.madd.bfs.admin.ch/zh.zip

200

✅ funciona

121 MB, actualización diaria, contiene data.sqlite

madd.bfs.admin.ch/api/buildings/{egid}

404

❌ excluido

ruta/autenticación poco claras

EGID inválido en find

200

⚠️ error suave

array results vacío — no es un error HTTP

Características

  • lookup_building(egid) — edificio individual por identificador federal (API en vivo)

  • address_to_egid(address) — geocodifica cualquier dirección suiza a EGID/EDID + LV95

  • lookup_dwellings(egid) — todas las viviendas de un edificio con habitaciones, área, planta

  • new_construction(municipality_bfs, since_year) — nueva construcción anual incl. cuota de vivienda familiar de 4+ habitaciones

  • construction_pipeline(municipality_bfs) — proyectado / aprobado / en construcción

  • buildings_in_bbox(e_min, n_min, e_max, n_max) — análisis sub-municipal (p. ej. distritos escolares)

  • municipality_housing_stats(municipality_bfs) — stock de viviendas y mezcla de tamaños de habitaciones

  • explain_code(attribute, code) — decodifica códigos GWR mediante la tabla de códigos oficial DE/FR/IT

  • dump_status() — frescura de la caché, punto de entrada de degradación elegante

Requisitos previos

  • Python 3.10+

  • ~130 MB de disco por volcado cantonal en caché (ZH)

  • Sin claves API — la Fase 1 no requiere autenticación

Instalación

uvx swiss-housing-mcp        # once published on PyPI

# or from source
pip install -e .

Uso / Inicio rápido

Claude Desktop (claude_desktop_config.json):

{
  "mcpServers": {
    "swiss-housing": {
      "command": "uvx",
      "args": ["swiss-housing-mcp"]
    }
  }
}

Nube (Render/Railway):

SWISS_HOUSING_TRANSPORT=streamable-http PORT=8000 swiss-housing-mcp

Configuración

Variable

Default

Propósito

SWISS_HOUSING_TRANSPORT

stdio

stdio | streamable-http | sse

SWISS_HOUSING_CACHE

~/.cache/swiss-housing-mcp

Directorio de caché de volcados

SWISS_HOUSING_DUMP_TTL_HOURS

24

Ventana de frescura del volcado

Versión del protocolo MCP

Este servidor habla dos eras de protocolo sobre el mismo endpoint. La primera solicitud de un cliente en una conexión decide cuál se aplica; una reclamación posterior de la otra era se rechaza.

Era

Revisión

Quién la alcanza

Handshake initialize

2024-11-052025-11-25

Lo que hablan los clientes actuales. El servidor responde con la revisión solicitada, o con el techo 2025-11-25 cuando la solicitud pide algo más nuevo.

Envoltura por solicitud

2026-07-28

Una solicitud que lleva la envoltura _meta de 2026-07-28 abre una conexión moderna.

Ambas revisiones están fijadas en tests/test_protocol_version.py y se verifican contra el SDK instalado, de modo que un aumento de Dependabot de mcp no pueda mover ninguna de las dos en silencio. Este servidor no construye una aplicación ASGI para enviar un initialize a través de ella, por lo que la compuerta verifica las constantes del SDK en lugar de una respuesta medida — la forma más débil, nombrada en lugar de no mencionada.

Tenga en cuenta que LATEST_PROTOCOL_VERSION del SDK es un alias de la era moderna, no de la era de handshake — fijarse solo en ella dejaría libre a la deriva la era que los clientes actuales realmente negocian.

Política de actualización. Cuando la compuerta falle, no edite la constante a ciegas: lea el changelog de la especificación entre las dos revisiones, verifique que el servidor siga comportándose correctamente, luego mueva la constante, esta sección, README.de.md y CHANGELOG.md juntos.

Pruebas

PYTHONPATH=src pytest tests/ -m "not live"   # CI-safe
PYTHONPATH=src pytest tests/ -m live         # against real upstream

Estructura del proyecto

swiss-housing-mcp/
├── src/swiss_housing_mcp/
│   ├── server.py      # FastMCP tools (9)
│   ├── gwr.py         # Dump store + geo.admin.ch client + retry
│   ├── models.py      # Pydantic v2 envelopes (source + provenance)
│   └── __main__.py    # Dual-transport entry point
├── tests/             # respx-mocked + @pytest.mark.live
└── .github/workflows/ # CI + OIDC PyPI publish

Limitaciones conocidas

  • El extracto público omite atributos relacionados con personas y algunos sensibles del GWR completo; las entregas oficiales de datos a las autoridades pasan por el canal BFS/MADD.

  • Las coordenadas son puntos de referencia de edificios (LV95), no polígonos de huella — las uniones de polígonos (p. ej. límites exactos de distritos escolares) necesitan geometrías externas; buildings_in_bbox cubre la aproximación rectangular.

  • GBAUJ (año de construcción) falta en una parte de los edificios antiguos; los códigos de período (GBAUP) existen como respaldo pero aún no se exponen.

  • La resolución municipio→cantón está sembrada para casos comunes; pase canton explícitamente para otros.

  • Los índices del mercado inmobiliario (IMPI, índice de precios de construcción, tasa de vacancia) viven deliberadamente en swiss-statistics-mcp — este servidor es la capa de registro, no la capa de estadísticas.

Changelog

Ver CHANGELOG.md

Contribuciones

Las contribuciones son bienvenidas — ver CONTRIBUTING.md (Deutsch).

Seguridad

Solo lectura, sin PII, sin autenticación — un registro federal público accedido a través de un conjunto fijo de endpoints. Ver SECURITY.md (Deutsch) para la postura completa y cómo reportar una vulnerabilidad.

Licencia

Licencia MIT — ver LICENSE. Datos: GWR/RegBL, Oficina Federal de Estadística de Suiza (BFS), datos de gobierno abierto con atribución.

Autor

Hayal Oezkan · github.com/malkreide

Créditos y proyectos relacionados

Available Tools

5 tools
construction_pipelineB
Read-only

Buildings and dwellings in the planning/construction pipeline of a municipality.

Breaks down by status: projected (GSTAT 1001), approved (1002), under construction (1003). Dwellings under construction today are households in 1-3 years — the early indicator for school-space planning.

ParametersJSON Schema
NameRequiredDescriptionDefault
cantonNo
municipality_bfsYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
noteNo
sourceNo
pipelineYes
provenanceYes
municipalityYes
municipality_bfsYes

TDQS

B3.4/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, so the description's additional information about status breakdowns and the interpretation of 'under construction' as an early indicator adds useful behavioral context. However, it does not disclose potential limitations like data availability by municipality or time-range constraints.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is three concise sentences: the first states the core purpose, the second details the status categories, and the third explains the practical implication. Every sentence adds value, and the content is front-loaded with the most critical information.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the presence of an output schema and the tool's moderate complexity, the description covers the data meaning and use case. However, it omits parameter semantics and does not specify what the output contains or how to interpret the status codes fully (though codes are listed). The description is adequate but not comprehensive.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 0% description coverage for its two parameters (canton, municipality_bfs). The description does not mention these parameters or provide any guidance on their values, formats, or roles. With no schema descriptions and no parameter information in the description, the agent receives no help beyond the schema structure.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly specifies the tool retrieves buildings and dwellings in the planning/construction pipeline of a municipality, with explicit breakdowns by status codes. This verb-resource combination is distinct from sibling tools like lookup_dwellings (likely existing dwelling data) and new_construction (new building registrations). The context of early indicator for school-space planning further differentiates its use case.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for getting pipeline data for a municipality and hints at its value for school-space planning, but it does not explicitly state when to prefer this tool over siblings or when not to use it. No exclusions or alternative recommendations are provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

dump_statusA
Read-only

Cache status of the cantonal GWR dumps (graceful-degradation entry point).

Always returns an evaluable status — never silently empty records. If a source is unreachable, this tool tells you when data was last refreshed.

ParametersJSON Schema
NameRequiredDescriptionDefault

No parameters

Output Schema

ParametersJSON Schema
NameRequiredDescription
noteYes
dumpsYes
sourceNo
ttl_hoursYes
provenanceYes

TDQS

A3.9/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true. The description adds value by stating the tool never returns empty records and reports last refresh time, which is beyond what annotations provide. No contradictions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two sentences, no wasted words. The key information is front-loaded and every sentence contributes meaning.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given zero parameters and the existence of an output schema, the description adequately covers the tool's behavior and return value. It is sufficient for the agent to understand what to expect, though it doesn't detail the output structure.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

No parameters exist, so the baseline is 4. The description correctly adds no parameter information since none are needed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool shows cache status of GWR dumps with graceful degradation. It is distinct from sibling tools like lookup_dwellings which retrieve data. No explicit differentiation from siblings, but the purpose is clear.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for checking cache health even when sources are unreachable, but does not explicitly state when to use it over alternatives. It provides context but no exclusions or direct guidance.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

explain_codeA
Read-only

Decode a GWR code value (e.g. GSTAT=1004, GKAT=1020) into human-readable labels.

Uses the official code table shipped with the dump (DE/FR/IT).

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYes
cantonNozh
attributeYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
sourceNo
provenanceYes
explanationsYes

TDQS

A3.7/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true, so the read-only nature is clear. The description adds value by specifying the source of the labels (official code table) and the supported languages (DE/FR/IT), going beyond what annotations provide.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is very concise at two sentences, but the second sentence could be more structured or broken into bullet points for clarity. No superfluous information, but room for slight improvement.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (3 params, no enums) and the presence of an output schema, the description adequately covers the main purpose. However, it lacks explanation for the optional parameter and does not mention the output schema's structure, resulting in moderate completeness.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 0% schema description coverage, the description bears the full burden of explaining parameters. It includes an example of 'attribute' and 'code' but does not describe the optional 'canton' parameter at all, leaving a gap in understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool decodes GWR code values into human-readable labels, with a specific verb and resource. It provides an example of inputs (GSTAT=1004) and distinguishes itself from sibling tools that handle different tasks.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies use for decoding codes from a specific code table, but does not explicitly state when to use this tool vs alternatives, nor does it mention any prerequisites or when not to use it. Sibling tools have different purposes, so some implicit differentiation exists.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

lookup_dwellingsA
Read-only

List all dwellings (EWID) of a building from the daily cantonal dump.

Includes rooms, floor area, floor and status per dwelling.

ParametersJSON Schema
NameRequiredDescriptionDefault
egidYes
cantonNozh

Output Schema

ParametersJSON Schema
NameRequiredDescription
egidYes
countYes
sourceNo
dwellingsYes
provenanceYes

TDQS

A3.5/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already declare readOnlyHint=true. The description adds context (data source 'daily cantonal dump' and included fields) but does not disclose behavior beyond that, such as error handling or permissions. No contradiction with annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (two sentences) and front-loaded with the core action. However, it could be slightly more structured with bullet points for clarity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a read-only list tool with an output schema, the description adequately mentions included fields but omits explanation of the required 'egid' parameter and the default value for 'canton'. The data source reference is vague.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, so the description should explain parameters. However, it does not mention 'egid' as building ID or 'canton''s role. It only references 'a building' implicitly, leaving parameter semantics unclear.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: 'List all dwellings (EWID) of a building' and specifies included attributes (rooms, floor area, floor, status). This distinguishes it from sibling tools like new_construction or dump_status.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Usage is implied but not explicit. The description does not mention when to use this tool versus alternatives, nor does it provide conditions for appropriate use.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

new_constructionB
Read-only

New residential construction per year for a municipality (existing buildings).

Returns buildings, dwellings and 4+ room dwellings per year — the 4+ room share is a proxy for family housing and thus for future pupil numbers. Municipality is identified by its BFS number (e.g. 261 = City of Zurich).

ParametersJSON Schema
NameRequiredDescriptionDefault
cantonNo
since_yearNo
municipality_bfsYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
sourceNo
per_yearYes
provenanceYes
since_yearYes
municipalityYes
total_dwellingsYes
family_share_pctYesShare of 4+ room dwellings — proxy for family housing
municipality_bfsYes
total_dwellings_4plus_roomsYes

TDQS

B3/5.0
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Annotations already indicate readOnlyHint=true. Description adds context about the 4+ room share being a proxy for family housing, but does not disclose any additional behavioral traits such as data source, update frequency, or limitations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Description is two sentences, efficiently conveying core purpose and a key interpretation note. No redundancy or fluff.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

With an output schema present, return value explanation is not needed. However, the description lacks usage context and does not fully cover parameters. Adequate but with gaps.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%. Description only explains municipality_bfs with an example. Parameters canton and since_year are not described at all, leaving their semantics unclear.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

Description clearly states it returns annual new residential construction data for a municipality, including buildings, dwellings, and 4+ room dwellings. However, phrasing 'existing buildings' may cause confusion about whether it covers new construction or existing stock.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus siblings like lookup_dwellings or construction_pipeline. Does not mention alternatives or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 5 tool updatesv0.1.0
    • First observedconstruction_pipeline
    • First observeddump_status
    • First observedexplain_code
    • First observedlookup_dwellings
    • First observednew_construction

TDQS

A3.6/5.0

Scored across 5 tools

Disambiguation5/5

Each tool targets a distinct aspect: listing dwellings, historical construction, pipeline, code explanation, and cache status. There is no overlap or ambiguity in their purposes.

Naming Consistency3/5

Tool names mix patterns: verb_noun (lookup_dwellings, explain_code), adjective_noun (new_construction), and noun_noun (construction_pipeline, dump_status). While readable, the lack of a uniform pattern reduces consistency.

Tool Count5/5

Five tools is well-scoped for a niche domain like Swiss housing data. Each tool serves a clear function without excess or deficiency.

Completeness4/5

The tools cover current dwelling data, historical construction, future pipeline, code decoding, and system status. A minor gap is the lack of a dedicated building-level query beyond dwellings, but the set supports the stated planning use case.

Maintenance

ActivityActive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • F
    license
    Not graded
    quality
    C
    maintenance
    Exposes ATTOM's real estate API as MCP tools, enabling property details, valuations, assessments, sales, and area data via natural language.
    2
    -
  • A
    license
    A
    quality
    A
    maintenance
    Provides AI-native access to Swiss Federal Statistical Office datasets through 9 tools for querying education, population, and cross-cantonal comparisons without authentication.
    15
    2
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    MCP server for Switzerland's national metadata catalogue, enabling AI agents to discover datasets, APIs, public services, and publishers through free-text search and structured queries.
    13
    MIT