Statistics Canada MCP Server

io.github.Aryan-Jhaveri由 GitHub 帳號 Aryan-Jhaveri 發布v0.19.0更新於 Nov 7, 2026

Access Statistics Canada data via the Web Data Services API

已驗證Streamable HTTP可網頁執行網頁搜尋與抓取資料與分析

概覽

AI 產生的概覽

讓助理存取加拿大統計局資料:尋找統計表、檢視維度、取得篩選後的觀測值,並在伺服器端完成計算。

可以做什麼
  • 依標題關鍵字搜尋加拿大統計局統計表,取得產品編號、日期範圍與頻率
  • 檢視統計表依 SDMX 鍵順序排列的維度與代碼,並解析序列中繼資料如向量編號、計量單位與頻率
  • 依統計表加鍵或單一向量取得篩選後的觀測值,資料量大時依序列彙總
  • 在伺服器端對已取得的資料列執行唯讀 SQL,計算成長率、平均值或排名
  • 查詢加拿大統計局在指定日期發布了哪些內容,或某序列今天有哪些資料點更新
適用情境
適合需要加拿大經濟或社會統計資料(勞動力、CPI、貿易、排放等)的情境:讓助理找到正確的統計表、只取所需的資料切片,並做簡單分析,而不必把原始資料列塞進對話。
執行需求
可使用託管的遠端端點(無需安裝),或透過 uvx 從 PyPI 套件 statcan-mcp-server 在本機執行。未宣告需要帳號、API 金鑰或環境變數。需要能連線至加拿大統計局服務的網路。本機資料庫工具需本機設定並指定資料庫路徑。
安裝前請注意
README 提醒語言模型可能編造資料,重要數字應與加拿大統計局官方來源核對。本機模式可建立、附加和刪除本機 SQLite 資料庫中的資料表,請指向你願意修改的路徑。將 STATCAN_VERIFY_SSL 設為 false 會關閉憑證驗證。

安裝

在 SourceWeft 中

  1. 開啟 儀表板中的 Statistics Canada MCP Server,將其新增到工作區。
  2. 為需要使用其工具的對話啟用該服務。

Web executable,透過 Streamable HTTP。 遠端服務在工作區中設定後即可從網頁執行環境執行。

交給代理程式安裝

把這段提示詞貼上到 Claude Code、Codex、Cursor 等代理程式,或 SourceWeft 對話中。代理程式會讀取該伺服器的安裝指南,先向你展示發布者、端點和登入方式,經你同意後再把它新增到你的客戶端。金鑰不會寫進任何命令。

閱讀 https://sourceweft.com/mcp/io.github.Aryan-Jhaveri%2Fmcp-statcan/install.md,並按其中說明把這個 MCP 伺服器接入我的客戶端。修改任何設定之前,先告訴我它的發布者、端點和登入方式,等我確認。不要把 API 金鑰寫進命令或我會提交的檔案;問我金鑰應從哪裡取得。

檢視代理程式所依據的安裝指南

其他 MCP 客戶端

把它新增到你客戶端的 mcpServers 設定中。

{
  "mcpServers": {
    "statistics-canada": {
      "type": "http",
      "url": "https://mcp-statcan.com/mcp"
    }
  }
}

README

[Statistics Canada MCP Server]

Statistics Canada MCP Server

[Python 3.10+] [License: MIT] [MCP] [GitHub] [SafeSkill 93/100]

MCP server and CLI for Statistics Canada's Web Data Service (WDS) and SDMX REST API. Gives any MCP client — Claude, Cursor, VS Code Copilot, Gemini — structured access to Canadian statistical data. Includes a standalone statcan CLI for direct downloads without an LLM.

Hosted on Render — no install required for most users. See Quick Start.

⚠️ LLMs may fabricate data. Always verify important figures against official Statistics Canada sources.

[Terminal recording: statcan search, statcan metadata and statcan download for the Consumer Price Index table]

The statcan CLI searching, inspecting and downloading a table. See statcan CLI.


Table of Contents


Quick Start

Pick the option that fits you. You don't need to install anything for Option 1.

Option 1 — Use the hosted server (recommended)

Connect directly to the public server on Render. No uv, no terminal, no local setup.

Claude Desktop / Claude.ai

  1. Open Settings → Connectors → Add Custom Connector
  2. Name: mcp-statcan
  3. URL: https://mcp-statcan.com/mcp
  4. Save and restart

Claude Code

bash
claude mcp add statcan --transport http https://mcp-statcan.com/mcp --scope global

The hosted server provides all WDS + SDMX tools. Database tools (SQLite) require local setup (Option 3) — they are intentionally excluded from the shared server.


Option 2 — Self-host HTTP (WDS + SDMX, no DB)

Run a local server with the same tools as the hosted version.

Step 1 — Install uv:

bash
# macOS / Linuxcurl -LsSf https://astral.sh/uv/install.sh | sh
# Windows (PowerShell)powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

Step 2 — Start the server:

bash
uvx statcan-mcp-server --transport http# Listening at http://localhost:8000

Step 3 — Connect your client to http://localhost:8000/mcp.


Option 3 — Full local setup (WDS + SDMX + SQLite)

Everything from Option 2, plus database tools for storing and querying data with SQL. Runs via stdio.

Step 1 — Install uv (same as above).

Step 2 — Configure your client with the stdio snippets in Setup by Client below.

uvx downloads and runs the server automatically on first use.


Option 4 — statcan CLI (no LLM needed)

Download StatCan data directly from the terminal. See statcan CLI.

bash
uvx statcan-mcp-server        # installs the packagestatcan search "labour force"statcan metadata 14-10-0287-01                                    # run first to find dimension IDsstatcan download 14-10-0287-01 --key "1.1.1" --last 12 --output lfs.csv  # run `statcan metadata <pid>` first to find real dimension IDsstatcan describe                                                  # machine-readable command reference for agents

Examples

Chat examples

DatasetQueryDemoSource
Canada's Greenhouse Gas Emissions"Create a simple visualization for greenhouse emissions for Canada as a whole over the last 4 years"ChatTable 38-10-0097-01
Canada's International Trade in Services"Create a quick analysis for international trade in services for the last 6 months with a visualization"ChatTable 12-10-0144-01
Ontario Building Construction Price Index"Generate a visualization for Ontario's Building Price index from Q4 2023 to Q4 2024"ChatTable 18-10-0289-01
Canadian Unemployment Dashboard"Create a Canadian Unemployment Dashboard using statcan mcp"ChatTable 14-10-0287-01

Dashboard examples

TitleLinkSource
Canada's Critical Minerals EconomyDashboardTable 36-10-0708-01
Price of Everything: CPI Dashboard 2015–2026DashboardTable 18-10-0004-01
Canada's Biomedical & Biotech IndustriesDashboardTable 27-10-0297-01

Setup by Client

Hosted server (Option 1)

Claude Desktop — Settings → Connectors → Add Custom Connector

  • Name: mcp-statcan
  • URL: https://mcp-statcan.com/mcp

Claude Code

bash
claude mcp add statcan --transport http https://mcp-statcan.com/mcp --scope global

Cursor — .cursor/mcp.json (project) or ~/.cursor/mcp.json (global):

json
{  "mcpServers": {    "statcan": {      "url": "https://mcp-statcan.com/mcp"    }  }}

VS Code (GitHub Copilot) — .vscode/mcp.json:

json
{  "servers": {    "statcan": {      "type": "http",      "url": "https://mcp-statcan.com/mcp"    }  }}

Self-hosted HTTP (Option 2)

Start uvx statcan-mcp-server --transport http first, then configure your client.

Most clients need mcp-proxy to bridge stdio ↔ HTTP. Claude Code connects natively.

Claude Desktop — Settings → Developer → Edit Config:

json
{  "mcpServers": {    "statcan": {      "command": "uvx",      "args": ["mcp-proxy", "--transport", "streamablehttp", "http://localhost:8000/mcp"]    }  }}

Claude Code

bash
claude mcp add statcan --transport http http://localhost:8000/mcp --scope global

Cursor / VS Code / Gemini — same mcp-proxy wrapper, pointing to http://localhost:8000/mcp.


Full local / stdio (Option 3)

Claude Desktop — Settings → Developer → Edit Config:

json
{  "mcpServers": {    "statcan": {      "command": "uvx",      "args": ["statcan-mcp-server", "--db-path", "/Users/<you>/.statcan-mcp/statcan_data.db"]    }  }}

Pass --db-path with an absolute path. Claude Desktop overrides the subprocess HOME env var, which can break default path resolution.

Claude Code

bash
claude mcp add statcan --scope global -- uvx statcan-mcp-server

Cursor / VS Code / Gemini — use uvx statcan-mcp-server as the stdio command.


How Claude.ai Uses This Server

Claude.ai (web) has no bash, and its code sandbox can't reach StatCan, so all data comes through the connector's MCP tools.

The pattern:

1. Discovery (small payloads):   search_cubes_by_title("labour force")  → productId + key_template   get_sdmx_structure(productId=..., search="Ontario;Employment")  → codes by label
2. Answers: get_sdmx_data(..., sql="SELECT ...")  → only the result comes back3. Files: get_sdmx_data(..., format="csv")        → copy the CSV verbatim into a file

Use sql for rankings, growth and averages; use format="csv" only when the rows need to go into a file.

After a server update, disconnect and reconnect the connector in claude.ai to refresh the tool list.

Claude Code (bash sandbox) uses the statcan CLI instead:

bash
statcan search "labour force"statcan metadata 14-10-0287-01  # run first to find dimension IDsstatcan download 14-10-0287-01 --key "1.1.1" --last 12 --output ./lfs.csv  # run `statcan metadata <pid>` first to find real dimension IDsawk -F',' 'NR>1 && $1=="Canada"' ./lfs.csv | sort -t',' -rn -k5 | head -10

MCP Prompts

The server ships five prompts accessible as slash commands in supported clients. Each has two sets of instructions: Claude Code (the statcan CLI in bash) and Claude.ai web (the MCP tools, with sql and format="csv" to keep rows out of context).

PromptWhat it teaches
/statcan-data-lookupEnd-to-end: search → structure → build key → fetch (CLI to a file, or MCP tools with sql) → analyze
/sdmx-key-builderSDMX key syntax: wildcards, OR keys, time parameters, download URL format
/statcan-downloadDownload a specific table: CLI commands, or the MCP tools on Claude.ai
/statcan-exploreSample before committing: 3-period fetch, column layout, size estimate
/statcan-vector-pipelineMulti-series download and cross-series comparison

The tool calls in the prompts follow the active toolset.

Usage in Claude Code:

/statcan-data-lookup topic="consumer price index" analysis_goal="trend last 5 years"/statcan-download product_id=18100004 last_n=24

statcan CLI

A standalone CLI for downloading StatCan data without an LLM. Outputs pipe-friendly CSV/JSON to stdout; progress and errors go to stderr.

Exploring a table (search, then metadata, then download): see the recording at the top of this page.

Agent mode (--json envelopes, typed exit codes, statcan describe):

[Terminal recording: statcan --json download writes a CSV and prints a summary envelope; a missing product returns a JSON error with exit code 3; statcan describe lists exit codes]

Recordings are generated from the scripts in assets/tapes/ with VHS: vhs assets/tapes/cli-agent.tape.

Install:

bash
pip install statcan-mcp-server   # or: uvx statcan-mcp-server (no install)

Commands:

statcan search <term>            Search tables by keywordstatcan metadata <product-id>    Show table structure (dimensions + members)statcan download <product-id>    Download observations via SDMXstatcan vector <vector-id>...    Download one or more vector seriesstatcan codeset                  Show StatCan code definitions (UOM, frequency, etc.)statcan describe                 Commands, options, exit codes and JSON envelopes as JSON

Common usage:

bash
# Find a tablestatcan search "consumer price index"statcan search "labour force" --max-results 10 --format json
# Inspect structure before downloadingstatcan metadata 18-10-0004-01statcan metadata 18100004 --full        # show all dimension members
# Download data (run `statcan metadata <pid>` first to find real dimension IDs)statcan download 18-10-0004-01 --key "1.1.1" --last 12 --output cpi.csvstatcan download 18-10-0004-01 --key "1.1.1" --start 2020-01 --end 2024-12statcan download 18-10-0004-01 --key "1.1.1" --last 5 --dry-run   # preview SDMX URL
# Download by vector IDstatcan vector v41690973 --last 24 --output series.csvstatcan vector v41690973 v41690974 --last 12 --output multi.csv
# Decode numeric codesstatcan codeset --type uomstatcan codeset --type frequency --format json

Output formats: csv (default for download/vector), table (default for search/metadata/codeset), json, ndjson

For agents and scripts: put --json before the subcommand (or set STATCAN_OUTPUT=json) to get one JSON envelope on stdout, JSON errors with a hint on stderr, and stable exit codes (0 ok, 2 usage, 3 not found, 4 rejected, 5 retryable, 6 empty). With --output, the envelope summarizes the file (rows, columns, period range, series count) so it never has to be read back. Details: machine-readable mode.

Pipe patterns:

bash
# Top 10 by value (run `statcan metadata <pid>` first to find real dimension IDs)statcan download 14-10-0287-01 --key "1.1.1" --last 1 --format csv \  | awk -F',' 'NR>1' | sort -t',' -k5 -rn | head -10
# Extract unique geographies (run `statcan metadata <pid>` first to find real dimension IDs)statcan download 14-10-0287-01 --key "1.1.1" --last 1 --format csv \  | awk -F',' 'NR>1 {print $1}' | sort -u
# Chain search → download (run `statcan metadata <pid>` first to find real dimension IDs)PID=$(statcan search "CPI" --format json | python3 -c "import sys,json; print(json.load(sys.stdin)[0]['Product ID'])")statcan download $PID --key "1.1.1" --last 12 --output cpi.csv

For the complete CLI reference see src/cli/README.md.


Features & Tools

Tools

Five tools, in the default core toolset:

ToolDescription
search_cubes_by_titleFind tables by title keywords (English or French; all must appear). Paged (offset, max_results, default 10); every result includes key_template, the dimension order of the SDMX key.
get_sdmx_structureA table's dimensions in key order with their codes (id, name, parent). search="Ontario;Employment" finds codes by label across all dimensions; dimension=<position> lists one full dimension plus its leaf_key (lowest-level codes as a + OR).
get_sdmx_dataObservations for productId + key, or one vectorId. Over 100 observations you get a per-series summary unless full=true (max 500 rows). Pass sql to run one read-only SELECT over the table data server-side (growth, averages, rankings) and get back only the result. format="csv" returns compact CSV instead of JSON (see below).
get_series_infoproductId + coordinates, or vectorIds: decoded frequency, unit and scalar, English and French title, and the SDMX key.
get_changesTables released on a date (default today), or the new data points for one series (vectorId, or productId + coordinate).

CSV output: get_sdmx_data(format="csv") returns one row per series and one column per period, with fields shared by every series written once as # name: value lines. It always returns the rows (ignores full, max 500 observations) and works with sql. It is about 3x smaller than full=true JSON (table 15100032, key 7...: 7,892 to 2,637 characters; 18100004, key .2, last 12: 13,247 to 3,630).

get_sdmx_data(productId=18100004, key=".2", lastNObservations=12, format="csv")

Key syntax (passed to get_sdmx_data):

  • "1.2.1" — Geography=1, Gender=2, Age=1
  • ".2.1" — all geographies (wildcard), Gender=2, Age=1
  • "1+2.2.1" — Geography 1 or 2, Gender=2, Age=1

Note: Wildcard (.) returns every member of the dimension, including totals and parent aggregates. For sums or rankings use the leaf_key from get_sdmx_structure(productId, dimension=N), and pass sql to compute over large result sets.

Toolsets

The server publishes one of two toolsets, chosen at startup. core is the default; legacy is the previous 17-tool set (hosted).

bash
STATCAN_TOOLSET=legacy uvx statcan-mcp-server      # or: uvx statcan-mcp-server --toolset legacy

Smaller tool lists leave more of the context window for data. Sizes of the tools/list response, including outputSchema (o200k tokens):

Transportlegacycore
Hosted (HTTP)17 tools, about 8,044 tokens5 tools, about 939 tokens
stdio (adds the database tools)26 tools, about 11,407 tokens14 tools, about 4,302 tokens

Legacy tool to core replacement:

LegacyCore
get_all_cubes_list, get_all_cubes_list_litesearch_cubes_by_title (paged)
get_cube_metadataget_sdmx_structure (search, dimension)
get_code_setsdecoded in get_series_info output
get_sdmx_key_for_dimensionget_sdmx_structure(dimension=N) returns leaf_key
get_sdmx_vector_dataget_sdmx_data(vectorId=...)
query_sdmxget_sdmx_data(..., sql=...)
get_series_info_from_vectorget_series_info(vectorIds=[...])
get_bulk_vector_data_by_rangeget_sdmx_data(vectorId=..., startPeriod=..., endPeriod=...) per series
get_changed_cube_list, get_changed_series_listget_changes(date=...)
get_changed_series_data_from_vector, get_changed_series_data_from_cube_pid_coordget_changes(vectorId=...) or get_changes(productId=..., coordinate=...)

Composite & Database Tools (local/stdio mode only, both toolsets)

These tools are not available on the hosted Render server — SQLite is per-process and not shared across users.

ToolDescription
fetch_sdmx_to_databaseFetch SDMX observations (productId + key) into the observation store — no row cap, rows stay out of context. table_name becomes a view.
fetch_vectors_to_databaseFetch vectors by reference period range into the same store. table_name becomes a view.
store_cube_metadataFetch full cube metadata into SQLite — browse all members and vectorIds with SQL.
query_databaseRead-only SQL against the local SQLite database.
create_table_from_data / insert_dataCreate or append to a table of your own data.
list_tables / get_table_schema / drop_tableDatabase utilities (tables and views; list_tables also reports store size).

Observation store. Both fetch tools upsert into two shared tables, so data accumulates instead of being copied into a new table per call:

TableOne row perKey columns
_statcan_seriesseriesseries_id (<productId>:<SDMX key>, e.g. 18100004:2.2), product_id, vector_id, dims_json (labels), uom
_statcan_observationsseries × periodseries_id, ref_date (period start), period (2026, 2026-Q2, 2026-08), value, status, source, fetched_at, release_time
  • Re-fetching updates values in place; each fetch reports how many observations were new, revised or unchanged.
  • An SDMX and a WDS fetch of the same series share rows (WDS coordinates map to the same SDMX key).
  • table_name is a view over the series and periods that call fetched, with the same columns as before (dimension labels, period, value, VECTOR_ID, UOM, ...).
  • Cross-table analysis needs no schema discovery:
sql
-- Seasonal component: CPI not seasonally adjusted (18100004) minus seasonally adjusted (18100006)SELECT nsa.period, ROUND(nsa.value - sa.value, 2) AS seasonalFROM _statcan_observations nsa JOIN _statcan_observations sa USING (ref_date)WHERE nsa.series_id = '18100004:2.2' AND sa.series_id = '18100006:1.1'ORDER BY ref_date DESC;

Typical workflow

Claude.ai web (hosted server):

1. search_cubes_by_title("unemployment rate")   → productId e.g. 14100287
2. get_sdmx_structure(productId=14100287)   → dimension positions + sample codes
3. get_sdmx_structure(productId=14100287, search="Ontario;Employment")   → ids of the codes you want, by label
4. get_sdmx_data(productId=14100287, key=".2.1", lastNObservations=24,                 sql="SELECT ... FROM data")   → server-side SQL: only the result comes back (omit sql for the observations)

Claude Code (bash sandbox):

bash
statcan search "unemployment rate"statcan metadata 14100287statcan download 14-10-0287-01 --key "1.1.1" --last 24 --output ./lfs.csv  # run `statcan metadata <pid>` first to find real dimension IDsawk -F',' 'NR>1 && $1=="Canada"' ./lfs.csv | sort -t',' -rn -k5 | head -10

Project Structure

src/├── api/│   ├── core/│   │   └── tools.py             # core toolset (default): the five merged tools│   ├── cube/                    # legacy toolset: search/list cubes, metadata, series, change detection│   ├── vector/│   │   └── vector_tools.py      # legacy toolset: vector series, bulk range fetch│   ├── sdmx/│   │   └── sdmx_tools.py        # legacy toolset: SDMX structure/data/query_sdmx; shared fetch helpers│   ├── composite_tools.py       # fetch_sdmx_to_database, fetch_vectors_to_database, store_cube_metadata (stdio only)│   └── metadata_tools.py        # get_code_sets (legacy toolset)├── cli/│   ├── main.py                  # statcan CLI entry point (Typer app)│   ├── output.py                # write_output, format helpers│   └── commands/│       ├── search.py            # statcan search│       ├── metadata.py          # statcan metadata│       ├── download.py          # statcan download│       ├── vector.py            # statcan vector│       └── codeset.py           # statcan codeset├── db/                          # SQLite: observation store (store.py), per-request SQL for get_sdmx_data(sql=) (ephemeral.py), schema, queries├── models/                      # Pydantic input models├── util/│   ├── registry.py              # ToolRegistry — @decorator → MCP Tool schema│   ├── truncation.py            # Response truncation + pagination guidance│   ├── sdmx_xml.py              # SDMX-ML (structure-specific XML) → labelled tabular rows│   └── cache.py                 # 1-hour TTL cache for cube list├── config.py                    # BASE_URL, SDMX_BASE_URL, RENDER_BASE_URL, TRANSPORT, PORT├── toolset.py                   # resolve_toolset(): STATCAN_TOOLSET / --toolset└── server.py                    # create_server(), MCP Prompts, resources, HTTP transport, CLI

Known Issues

IssueStatusWorkaround
"Unable to open database file" on Claude DesktopActivePass --db-path /Users/<you>/.statcan-mcp/statcan_data.db in your config
SSL verification on broken trust storesConfigurableVerification is on by default; set STATCAN_VERIFY_SSL=false only if your system can't validate StatCan's certificate
lastNObservations + startPeriod/endPeriod → 406ActiveUse one or the other, not both
Wildcard/OR rows missing or mislabelled; wrong VECTOR_ID/UOMFixed in v0.12.0Caused by StatCan's SDMX-JSON index encoding; data is now read as structure-specific XML (#90)
Context overflow may cause data fabricationMitigatedUse get_sdmx_data with sql (hosted) or fetch_sdmx_to_database (local) so raw rows never enter context; get_sdmx_data caps inline rows at 500
Slow or stalled StatCan requestsMitigatedStalled requests retry after about 10 s. An incomplete SDMX structure isn't cached, and labels fall back to WDS metadata (the result's _message says so)

Contributors

Thanks to everyone who has contributed code, fixes and bug reports:

  • @dannyward630: fixed get_changed_series_list to use StatCan's undated endpoint (#130)

Want to help? See CONTRIBUTING.md.


Made with ❤️❤️❤️ for Statistics Canada

來源:README.md,提交 74458fb

工具

5

search_cubes_by_title

Find StatCan tables by title keywords. Returns productId, title, dates and frequency; each includes key_template, the dimension order of the SDMX key.

輸入參數offsetmax_resultssearch_term必填

get_sdmx_structure

A table's dimensions in key order with their codes (id, name, parent). Use search to find the codes for labels like 'Ontario' instead of guessing.

輸入參數searchdimensionproductId必填

get_sdmx_data

Observations for productId + key, or one vectorId. Over 100 observations you get a per-series summary. Pass sql to compute over every row (growth, averages, ranking) server-side. Cite _sdmx_url.

輸入參數keysqlfullformatvectorIdendPeriodproductIdstartPeriodlastNObservations

get_series_info

Series metadata for productId + coordinates, or vectorIds: vectorId, key, title, frequency, unit of measure and scalar (decoded), decimals.

輸入參數productIdvectorIdscoordinates

get_changes

What StatCan released: tables updated on a date (default today), or today's new data points for one series (vectorId, or productId + coordinate).

輸入參數datelimitoffsetvectorIdproductIdcoordinate

版本歷史

7
  1. v0.19.0最新Nov 7, 2026
  2. v0.17.0Oct 26, 2026
  3. v0.16.0Oct 26, 2026
  4. v0.15.0Oct 26, 2026
  5. v0.12.0Oct 25, 2026
  6. v0.7.17Sep 19, 2026
  7. v0.7.15Sep 16, 2026

評分

已滿足適用檢查項的 100%

該評分衡量此收錄條目的完整程度,依據註冊中心條目、端點與公開來源計算得出。它不是對伺服器本身的評價,也不表示伺服器安全或目前可用:可連通性是帶日期的檢查結果,評分也不包含安裝量或使用者評價。

  • 近 30 天內可連通必需25 分
  • 已宣告認證方式必需10 分
  • 已列出工具必需15 分
  • 描述必需15 分
  • 圖示10 分
  • 文件15 分
  • 授權條款10 分