swiss-statistics-mcp
This server provides AI-native access to Swiss Federal Statistical Office (BFS) data via the STAT-TAB PxWeb API, covering 682 datasets across 21 thematic areas — no authentication required. It offers 9 tools:
Browse statistical themes – List all 21 BFS thematic areas (e.g., Population, Education, Health, Transport) with dataset counts.
Discover datasets by theme – Retrieve all available tables for a specific theme using its 2-digit code.
Search the full catalogue – Full-text keyword search across all 682+ BFS table titles, optionally filtered by theme.
Inspect table structure – Get detailed metadata for any table: variables, dimension codes, and available filter values.
Query statistical data – Fetch actual data from any BFS table with optional dimension filters, language selection, and a configurable row limit (up to 5,000).
Education statistics – Convenience tool for teachers, students, enrollment scenarios, and scholarships, optionally filtered by canton.
Population statistics – Query Swiss resident population by region/canton, year, age, or gender.
Compare cantons – Compare any statistical indicator side-by-side across multiple Swiss cantons simultaneously.
Featured datasets – A curated shortlist of high-value datasets for education planning and public administration.
Key characteristics:
Supports 4 languages: German, French, Italian, and English
All operations are read-only, accessing Open Government Data (OGD)
Includes built-in retry logic, metadata caching (1-hour TTL), and concurrency controls
Supports stdio (Claude Desktop) and Streamable HTTP (cloud) transports
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@swiss-statistics-mcpWhat is the population of Zurich in 2023?"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
🇨🇭 Part of the Swiss Public Data MCP Portfolio
📊 swiss-statistics-mcp
MCP Server for Swiss Federal Statistical Office (BFS) data via STAT-TAB PxWeb API — 682 datasets across 21 themes, no authentication required
Demo
Maturity
This server is Alpha (0.x) as per the PyPI classifier. Until 1.0:
Tool names, input schemas, and output JSON keys MAY change between minor versions
Pin cloud deployments to a specific git tag, not
mainProduction use is acceptable for read-only Open Data scenarios; consider it experimental for anything user-facing
See CHANGELOG.md for breaking changes.
Related MCP server: Swiss Truth MCP
Overview
swiss-statistics-mcp provides AI-native access to the Swiss Federal Statistical Office (BFS) via the STAT-TAB PxWeb API, without authentication:
Property | Details |
API | STAT-TAB PxWeb API v1 |
Endpoint |
|
Provider | Swiss Federal Statistical Office (BFS) |
Datasets | 682 tables across 21 thematic areas |
Languages | German ( |
Licence | Open Government Data (OGD) — BFS Terms of Use |
Authentication | None — fully public |
Anchor demo query: "How many students attended lower secondary schools in the canton of Zurich in 2024?" — real BFS figures, no hallucination.
Features
📊 15 tools: 8 across 21 statistical themes (682 datasets) + a 4-tool commune/historical reference layer + 2 construction/real-estate tools + a price-index tool
🔍 Full-text search across the entire BFS data catalogue
🎓 Convenience tools for education statistics and population data
🏗️ Construction statistics — new buildings/dwellings and building investment incl. the Arbeitsvorrat leading indicator
🏠 Price indices — construction price index (Baupreisindex, parsed series) and residential property price index (IMPI) via the BFS DAM/CKAN sources
🏔️ Cross-cantonal comparison for any table and variable
🔓 No API key required — all data under open licences
☁️ Dual transport — stdio (Claude Desktop) + Streamable HTTP (cloud)
Prerequisites
Python 3.11+
uv (recommended) or pip
Installation
# Clone the repository
git clone https://github.com/malkreide/swiss-statistics-mcp.git
cd swiss-statistics-mcp
# Install
pip install -e .
# or with uv:
uv pip install -e .Or with uvx (no permanent installation):
uvx swiss-statistics-mcpQuickstart
# stdio (for Claude Desktop)
python -m swiss_statistics_mcp.server
# Streamable HTTP, loopback only (default: host=127.0.0.1, port=8000)
python -m swiss_statistics_mcp.server --http --port 8000
# Streamable HTTP, all interfaces (only behind a reverse proxy with access control)
MCP_HOST=0.0.0.0 python -m swiss_statistics_mcp.server --http --port 8000
# or
python -m swiss_statistics_mcp.server --http --host 0.0.0.0 --port 8000Try it immediately in Claude Desktop:
"How many teachers worked in the canton of Zurich in 2023?" "What is the population of canton Bern broken down by age?" "Compare the social assistance rate across all cantons for 2022."
Configuration
Claude Desktop
Edit ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) or %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"swiss-statistics": {
"command": "python",
"args": ["-m", "swiss_statistics_mcp.server"]
}
}
}Or with uvx:
{
"mcpServers": {
"swiss-statistics": {
"command": "uvx",
"args": ["swiss-statistics-mcp"]
}
}
}Config file locations:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
Cursor / Windsurf / VS Code + Continue
The configuration syntax is identical to Claude Desktop. The file name depends on the client:
Cursor:
.cursor/mcp.jsonin the project folder, or~/.cursor/mcp.jsongloballyWindsurf:
~/.codeium/windsurf/mcp_config.jsonVS Code + Continue:
.continue/config.json
Cloud Deployment (SSE for browser access)
For use via claude.ai in the browser (e.g. on managed workstations without local software).
⚠️ Security note — this server has no authentication. A public URL turns it into an open proxy to the BFS API on your deployment's IP. Any client with the URL can drive the tools, consume your platform quota, and attribute traffic to your IP. Two mitigations, in order of preference:
Put it behind access control — Render's «Private Service», Cloudflare Access, or a reverse proxy with Basic-Auth / IP allowlist in front of the container.
Accept it as a public open-data proxy — only acceptable because all data is BFS OGD (Public Open Data) and tools are read-only.
The server binds to
127.0.0.1by default. To expose it on a container port you must explicitly setMCP_HOST=0.0.0.0(e.g. as a Render env var) or pass--host 0.0.0.0. Do not do this without one of the mitigations above.
Render.com:
Push/fork the repository to GitHub
On render.com: New Web Service → connect GitHub repo
Set environment variable:
MCP_HOST=0.0.0.0Set start command:
python -m swiss_statistics_mcp.server --http --port 8000In claude.ai under Settings → MCP Servers, add:
https://your-app.onrender.com/sse
💡 "stdio for the developer laptop, SSE for the browser."
Output Schema
Since v0.2.0, every tool returns a typed Pydantic model rather than a JSON
string. FastMCP serializes these as structured content so MCP clients can
read fields directly.
# Old (pre-0.2.0)
result = await bfs_get_data(...) # str
data = json.loads(result) # dict
print(data["rows_total"])
# New (>= 0.2.0)
result = await bfs_get_data(...) # DataTableResult
print(result.rows_total) # 1000
print(result.truncated) # TrueEvery result carries error: str | None and hint: str | None at the top
level — result.error is None means success. Data-returning tools
(bfs_get_data, bfs_education_stats, bfs_population,
bfs_compare_cantons) additionally expose truncated: bool,
rows_total: int, and rows_returned: int for machine-readable cap
detection.
Tool | Result type |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Reference-layer results additionally carry source (attribution) and provenance (live_api | cached); SearchHistoricalSeriesResult also carries licence_note with the mandatory HSSO NonCommercial notice. The construction and price-index results carry source + provenance on the same envelope pattern.
Available Tools
Tool | Description |
| Curated list of highly relevant datasets (focus on education and demographics) |
| Browse the catalogue: all 21 themes (no |
| Full-text search across the entire data catalogue (682 datasets) |
| Variables, values and metadata for a specific table |
| Data retrieval with optional filters by dimensions and values |
| Convenience tool: teachers, pupils, demographic scenarios, scholarships |
| Resident population by canton, year, age structure or sex |
| Cross-cantonal comparison for any table and any variable |
| Resolve a commune by name or BFS number as of a given date (canton, validity, LINDAS URI) |
| Map a historical BFS number onto today's number(s) — re-key old statistics across fusions |
| List all communes of a canton as of a given date |
| Search long-run time series in Historical Statistics of Switzerland (HSSO) |
| New buildings & dwellings per commune (yearly), incl. dwelling room-size mix |
| Building investment & Arbeitsvorrat (leading indicator) by region/canton/commune |
| Construction price index (Baupreisindex, parsed series) / residential property price index (IMPI, source links) |
Four of these tools form the reference layer of the portfolio (see Join Keys): they turn official BFS commune numbers into a reliable join key and let you re-key statistics that predate a municipal merger. The two bfs_construction_* tools cover STAT-TAB theme 09 (Bau- und Wohnungswesen) — see Construction sources. bfs_price_index covers price indices that are not in STAT-TAB — see Price-index sources.
Construction sources
Cube ID | Title | Coverage | Used by |
| Neu erstellte Gebäude mit Wohnungen nach Gemeinde, Gebäudetyp | 2013– |
|
| Neu erstellte Wohnungen nach Gemeinde, Anzahl Zimmer | 2013– |
|
| Bauinvestitionen und Arbeitsvorrat nach Grossregion/Kanton/Gemeinde | 1994– |
|
The pre-2013 Gemeinde-level building series lives in the discontinued cubes
px-x-0904030000_101/_104(1995–2012), which use a different geo coding and are not queried by these tools. Building/dwelling figures are the consolidated official yearly statistics — for up-to-date register states and the construction pipeline, cross-validate againstswiss-housing-mcp(deliberate redundancy).
Price-index sources
bfs_price_index covers two indices that are not published via STAT-TAB. Their datasets live on opendata.swiss (CKAN); the data files themselves are BFS DAM assets.
Index | Source | Returns |
| opendata.swiss dataset Schweizerischer Baupreisindex (Multibasen) → DAM XLSX asset | Parsed national semi-annual index series (Schweiz, Baugewerbe Total), with the base period |
| opendata.swiss dataset Schweizerischer Wohnimmobilienpreisindex (IMPI) → DAM PDF/HTML assets | Official source links only — BFS does not publish a machine-readable IMPI series |
Two quirks are handled for you:
ckan.opendata.swissreturns HTTP 403 to default User-Agents, so every call sends a customswiss-statistics-mcp/<version>User-Agent; and DAM assets mix formats, so the XLSX is selected by verifying the responsecontent-type(PDFs are skipped). Results are cached for 24 h.
Example Use Cases
Query | Tool |
"How many teachers worked in Zurich in 2023?" |
|
"How will upper secondary enrolment develop until 2031?" |
|
"What is the population of canton Zurich by age?" |
|
"Compare the social assistance rate across all cantons" |
|
"Is there data on school buildings?" |
|
"Which Zurich communes have merged since 2000, and onto which of today's BFS numbers must I re-key old statistics?" |
|
"List all communes of canton Glarus today" |
|
"Find long-run series on population in HSSO" |
|
"How many new dwellings were built in Winterthur since 2018, by room size?" |
|
"What is the building investment and Arbeitsvorrat for canton Zurich?" |
|
"How has the construction price index moved since 2015?" |
|
→ More use cases by audience →
Themes
Code | Theme | Code | Theme |
01 | Population | 12 | Money, banks, insurance |
02 | Territory and environment | 13 | Social security |
03 | Work and income | 14 | Health |
04 | National economy | 15 | Education and science |
05 | Prices | 16 | Culture, media, information society |
06 | Industry and services | 17 | Politics |
07 | Agriculture and forestry | 18 | General government |
08 | Energy | 19 | Crime and criminal justice |
09 | Construction and housing | 20 | Economic and social situation |
10 | Tourism | 21 | Sustainable development |
11 | Mobility and transport |
Architecture
┌─────────────────┐ ┌──────────────────────────────┐ ┌──────────────────────────┐
│ Claude / AI │────▶│ Swiss Statistics MCP │────▶│ BFS STAT-TAB │
│ (MCP Host) │◀────│ (MCP Server) │◀────│ PxWeb API v1 │
└─────────────────┘ │ │ └──────────────────────────┘
│ 15 Tools │
│ + commune/historical ref │
│ + construction (theme 09) │
│ + price indices (DAM/CKAN) │
│ Stdio | Streamable HTTP │
│ │
│ No authentication required │
└──────────────────────────────┘Data Source Characteristics
Source | Protocol | Coverage | Auth | Licence |
BFS STAT-TAB | PxWeb REST API | 682 tables, 21 themes | None | OGD |
BFS AGVCH (commune register) | REST (CSV/XLSX) | Snapshots, mutations, correspondances | None | OGD |
HSSO (historical statistics) | Static XLSX dumps | ~750 long-run tables | None | CC BY-NC-SA 3.0 |
BFS DAM + opendata.swiss (CKAN) | CKAN metadata + DAM XLSX/PDF | Baupreisindex, IMPI | None (custom UA required) | OGD |
Architecture decision
AGVCH commune register → Architecture A (live-API-only). The official REST service (
snapshot/correspondances/mutations/levels) is a clean, versioned, no-auth API — verified live on 2026-07-19 — so the commune tools query it directly with a 24 h in-memory cache and the shared retry policy. No dump fallback is needed. Finding: the live snapshot CSV header usesInscription,Radiation,Rec_Type_fr(not theEinschreibung,Streichungnames printed in the API PDF), andHistoricalCodeis not globally unique across levels — theParentlink is disambiguated by tier when deriving a commune's canton.HSSO → Architecture C (dump-only). HSSO offers no API, only static per-table XLSX at stable URLs (
/get/{CHAPTER}.{NN}{suffix}.xlsx).search_historical_seriesbuilds a cached title index from the chapter pages and returns the stable download URL. HSSO is licensed CC BY-NC-SA 3.0 (NonCommercial) — different from this server's OGD baseline — so every HSSO response carries an explicit NonCommercial notice inlicence_note.
Join Keys
The reference layer exists so that data from different servers in the Swiss Public Data MCP Portfolio can be joined reliably. Three identifiers are the portfolio-wide keys:
Key | What it identifies | Canonical form | Notes |
BFS commune number ( | A political commune | integer, e.g. | The primary join key across statistics, geo, education and health data. Stable LINDAS/Linked-Data URI: |
EGID | A single building (Eidg. Gebäudeidentifikator) | 9-digit integer | The join key for building/dwelling-level data (GWR, energy, addresses). A commune contains many EGIDs; |
Canton abbreviation | A canton | two letters, e.g. | The coarsest geographic key. Derivable from any commune via its |
Why re-keying matters. BFS commune numbers change whenever communes merge, split, or move canton. Statistics published before a merger use the old number; joining them to today's data without re-keying silently drops or misattributes rows. resolve_historical_commune(bfs_number, from_date, to_date) returns the resolves_to set — the current number(s) old figures must be aggregated onto — plus the mutation_path (the fusions/renamings, with dates). Other portfolio servers are meant to mirror this contract conceptually so the same key resolves the same way everywhere.
Example (anchor query). "Which Zurich communes have merged since 2000?" — e.g. old 132 Hirzel and 133 Horgen both re-key onto today's 295 Horgen; 134/140/142 onto 293 Wädenswil.
Project Structure
swiss-statistics-mcp/
├── src/swiss_statistics_mcp/
│ ├── __init__.py # Package
│ └── server.py # 15 tools
├── tests/
│ └── test_server.py # Unit + integration tests (mocked HTTP)
├── .github/workflows/ci.yml # GitHub Actions (Python 3.11/3.12/3.13)
├── pyproject.toml
├── CHANGELOG.md
├── CONTRIBUTING.md # English
├── CONTRIBUTING.de.md # German version
├── SECURITY.md # English
├── SECURITY.de.md # German version
├── LICENSE
├── README.md # This file (English)
└── README.de.md # German versionObservability
The server emits one JSON log line per tool call on stderr:
{"ts": "2026-05-20T04:02:28", "level": "INFO", "logger": "swiss_statistics_mcp",
"event": "tool_start", "tool": "bfs_browse_catalog", "rid": "1091cb73", "params_keys": ["theme_code", "lang", "limit"]}
{"ts": "2026-05-20T04:02:28", "level": "INFO", "logger": "swiss_statistics_mcp",
"event": "tool_end", "tool": "bfs_browse_catalog", "rid": "1091cb73", "status": "ok", "duration_ms": 303}rid— 8-char correlation id linkingtool_startandtool_endfor the same callparams_keys— sorted list of input field names (no values, no PII)duration_ms— per-call latency on thetool_endeventstatus—"ok"or"error";error_typeis added when a tool raises
Render and other cloud platforms can index these directly for per-tool latency
dashboards and error-rate alerts. Set MCP_LOG_LEVEL=DEBUG for verbose output
or WARNING to suppress per-call events.
ℹ️ Logs go to stderr so they never collide with the MCP protocol on stdio transport (which uses stdout).
Resilience
The server absorbs transient BFS-API hiccups before they reach the LLM:
Retries —
5xx,429, and network errors are retried up to 3 times with exponential backoff (0.5s → 4s).4xxerrors surface immediately so client bugs aren't masked. Tunable viaMCP_RETRY_MAX_ATTEMPTS,MCP_RETRY_WAIT_INITIAL,MCP_RETRY_WAIT_MAXenv vars.Metadata cache — Table metadata (variables, value domains, last_updated) is cached in-memory per
(table_id, lang)for 1h. Cold list/detail flows warm the cache; subsequent calls return instantly.Concurrency cap — Fan-out metadata fetches in
bfs_browse_catalog(theme mode) run in parallel bounded byFANOUT_CONCURRENCY = 5. Forlimit=20this cuts wall-clock from ~20s sequential to ~4s, without overwhelming the upstream API.
Known Limitations
PxWeb API: Rate limiting may apply for rapid successive queries; the server uses a 1-hour cache for the catalogue index and a 1-hour cache for table metadata
Language: Dataset titles and dimension values are in German by default; French, Italian and English coverage varies by table
JSON-STAT2: Some complex cross-tabulations may return large result sets; use dimension filters to narrow queries
Commune register (AGVCH): Live snapshot CSV headers use
Inscription/Radiation/Rec_Type_fr(not theEinschreibung/Streichungnames in the API PDF);HistoricalCodeis not globally unique across levels, so the canton is derived by walking theParentchain one tier at a time. Snapshots/mutations are cached for 24 h.HSSO: Licensed CC BY-NC-SA 3.0 (NonCommercial) — attribution required, no commercial use; every response carries this in
licence_note. HSSO exposes no per-table period filter, sosearch_historical_series'speriodargument is an informational hint only — verify the actual span in the XLSX.search_historical_seriesreturns the stable XLSX download URL, not the parsed series values.PxWeb commune codes are not consistent across cubes. In
px-x-0904030000_106/_107the value code IS the zero-padded BFS number (0261); inpx-x-0904030000_105it is an opaque sequential id (160) and the BFS number appears only in the label (......0261 Zürich).bfs_construction_activityresolves each cube against its own live dimension values by matching the label-embedded BFS number, never by guessing the code.Construction coverage: the current Gemeinde-level building series starts in 2013;
bfs_construction_activitytherefore acceptssince_year >= 2013. Values are the consolidated official yearly statistics. Building investment values (bfs_construction_investment) are in 1000 CHF; theArbeitsvorratis the following year's building volume (a monetary leading indicator).Price indices (
bfs_price_index): the IMPI (residential property price index) is published by BFS only as PDF/HTML — there is no machine-readable series — soindex="impi"returns the official source links plus an explicit limitation, not values. The Baupreisindex XLSX is parsed to the national semi-annual series (Schweiz, Baugewerbe Total); regional/object-type breakdowns exist in the source XLSX but are not returned. The DAM asset ids are resolved live from CKAN metadata (never hard-coded), because they change on republish; if the upstream XLSX structure changes, the tool degrades to a clear error rather than returning wrong values.
Testing
# Unit tests (no API key required)
PYTHONPATH=src pytest tests/ -m "not live"
# Integration tests (live API calls)
pytest tests/ -m "live"Safety & Limits
Read-only: All tools perform HTTP GET requests only — no data is written, modified, or deleted.
No personal data: STAT-TAB returns aggregated statistical datasets. No personally identifiable information (PII) is processed or stored by this server.
Rate limits: The PxWeb API is a public endpoint without documented rate limits; avoid tight loops over the full 682-table catalogue. The server enforces a 30s timeout per request and caches the catalogue index for 1 hour.
Data freshness: BFS publishes updated figures periodically (not real-time). Figures reflect the state of the upstream database at query time.
Terms of service: Data is subject to the BFS Terms of Use (OGD). All STAT-TAB data is published as Open Government Data and may be freely used with attribution.
No guarantees: This server is a community project, not affiliated with the Swiss Federal Statistical Office. Availability depends on the upstream BFS API.
Changelog
See CHANGELOG.md
Contributing
See CONTRIBUTING.md
Security
Read-only, no PII, no authentication, single fixed BFS endpoint. See SECURITY.md for the full security posture and accepted-risk decisions.
License
MIT License — see LICENSE
Author
Hayal Oezkan · malkreide
Credits & Related Projects
BFS: www.bfs.admin.ch — Swiss Federal Statistical Office
STAT-TAB: www.pxweb.bfs.admin.ch — PxWeb database interface
Protocol: Model Context Protocol — Anthropic / Linux Foundation
Related: swiss-cultural-heritage-mcp — SIK-ISEA, Nationalmuseum, Nationalbibliothek
Related: fedlex-mcp — Swiss federal law via Fedlex SPARQL
Related: zurich-opendata-mcp — CKAN, weather, air quality, City of Zurich
Related: swiss-transport-mcp — OJP journey planning, SIRI-SX disruptions
Related: global-education-mcp — UNESCO UIS and OECD Education at a Glance
Portfolio: Swiss Public Data MCP Portfolio
Installation
Run via uv's uvx — no clone or manual install needed. Add to your MCP client config (mcpServers for Claude Desktop, Cursor and Windsurf; use a top-level servers key for VS Code in .vscode/mcp.json):
{
"mcpServers": {
"swiss-statistics-mcp": {
"command": "uvx",
"args": [
"swiss-statistics-mcp"
]
}
}
}Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseBqualityDmaintenanceProvides AI assistants access to 1.6 million Swiss health insurance premium records from 55 insurers across 11 years (2016-2026), enabling price comparisons, historical analysis, and finding the cheapest insurance options based on location, age, and coverage preferences.4501MIT
- Alicense-qualityDmaintenanceVerified knowledge base for AI agents. Stop hallucinations with certified, source-backed facts. Covers Swiss law, health, finance, climate, AI/ML, and more. 8 tools, no API key needed, public and free.MIT
- AlicenseAqualityAmaintenanceEnables AI models to query Swiss National Bank data including exchange rates, balance sheet, interest rates, SARON, monetary aggregates, banking statistics, and balance of payments via the SNB public API.11MIT
- FlicenseAqualityCmaintenanceEnables LLMs to query structured statistical data from the Swiss Federal Archives' Linked Data platform (LINDAS) by translating natural language questions into SPARQL queries against RDF data cubes.8
Related MCP Connectors
Swiss weather data for AI assistants — forecasts, measurements, stations, pollen.
Gateway between LLM agents and world data through eight tools and a bundled endpoint catalog.
Macro data for AI agents: GDP, inflation, unemployment & trade, any country. No API keys.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/malkreide/swiss-statistics-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server