MapleStatsMCP

Statistics Canada · Notes from the code

How MapleStats works with Statistics Canada

Statistics Canada publishes its data through several separate services. In this post I explain how MapleStats brings them together for an agent, and what I learned by calling them.

One way in

StatCan's data do not come from one place. Tables and time series come from one service. Classifications such as NAICS, the 2021 Census Profile, the public use microdata files and The Daily each come from another. Each service has its own identifiers and its own ways of failing. Someone asking about prices should not need to know any of this, and neither should the agent working for them.

MapleStats wraps these services in 94 tools, and the agent never sees them as a long list. It describes what it needs in plain words, and a search returns the few tools that fit:

Requestsearch_tools
{
  "query": "search StatCan tables"
}
Response: names onlyranked when this page was built
[
  "statcan_daily_get_release_tables",
  "statcan_reference_search_data",
  "wds_search_cubes",
  "rdaas_search_concordances",
  "statcan_daily_get_article"
]

The search on the home page runs the same index in your browser, so you can try your own query there.

Finding a table

Every StatCan table has a number, such as 18-10-0004 for the Consumer Price Index. The table search finds a table by its number, or by matching every word of a query against the English and French titles, ignoring accents and case. That is how "consumer price index" finds the CPI tables.

Title matching has a limit. A word such as a province's name is usually inside a table, not in its title. When no title holds every word, the tool returns the closest matches and says how many words each one matched. The agent can then look inside a table or search again in StatCan's own terms.

Getting the numbers

A table holds many series. The CPI table crosses 30 geographies with 100 products, and StatCan publishes 2,139 of the 3,000 combinations. Each series has a stable ID, its vector. With the vector, the agent asks for the latest 84 months:

Requestcall_tool
{
  "name": "wds_get_data_from_vectors",
  "arguments": {"vector_ids": [41690973], "latest_n": 84}
}
Response, trimmedstatcan.wds.VectorDataSet
[
  {
    "product_id": 18100004,
    "coordinate": "2.2.0.0.0.0.0.0.0.0",
    "vector_id": 41690973,
    "observations": [
      // 83 earlier months
      {
        "ref_period": "2026-09-01",
        "value": 170.0,
        "decimals": 1,
        "scalar_factor_code": 0,
        "scale_multiplier": 1,
        "symbol_code": 0,
        "status_code": 0,
        "security_level_code": 0,
        "release_time": "2026-10-19T12:30:00Z",
        "symbol": "none",
        "status": "normal",
        "security_level": "public"
      }
    ],
    "provenance": {
      "url": "https://www150.statcan.gc.ca/t1/wds/rest/getDataFromVectorsAndLatestNPeriods"
      // + 13 more fields
    }
  }
]

One rule matters more to me than the others: the server never rescales a value. Some tables publish figures in thousands or millions, and StatCan sends a code with each value that says which. MapleStats passes the value on exactly as StatCan sent it, with that code beside it. Scaling takes one multiplication, and I would rather it happen where the person using the number can see it.

A handful of series come back in the response itself. For a whole table, or hundreds of series, the server returns a link to the table's CSV file instead. For a slice of a large table, such as every detailed geography, it uses StatCan's SDMX service, which does the filtering on StatCan's side.

The data and the documentation

Every series comes back with what a reader needs to cite it: the table and vector, the reference period, the release date, the unit and scale, the geography and a link to the table's page on statcan.gc.ca. StatCan's own status and symbol codes stay on each value, so "use with caution" (E), "too unreliable to be published" (F), preliminary and revised are spelled out rather than dropped. A request for a period StatCan has not released gets no value, only the periods the series does cover; a date range that stops before the newest data gets a note that newer data exist.

A number is only half of what StatCan publishes. The documentation that says what it measures is reachable too: definitions, data sources and methods, and analytical articles through the reference catalogue (statcan_reference_; StatCan has answered scripts there with a captcha since November 2026, so these are for now read in a browser); the survey directory and each survey's IMDB metadata, along with the RDC and RTRA holdings (statcan_surveys_); the codebooks and user guides of the public use microdata files (statcan_pumf_); The Daily's articles and the tables of each release (statcan_daily_); and classifications such as NAICS with their concordances (rdaas_). An agent can read how the Labour Force Survey defines unemployment, in the survey's IMDB metadata, before it reports the rate.

Survey microdata

Tables are aggregates. A public use microdata file holds the survey records themselves, one row per respondent, with weights that scale the sample up to the population. MapleStats can find these files through ODESI on Borealis (StatCan's own catalogue has answered scripts with a captcha since November 2026), read a file's codebook before downloading it, and tabulate the file with its weights. It reads files in CSV or fixed-width text and, when a file comes only as SAS, SPSS or Stata data (Canada's Core Public Infrastructure Survey, for one), those formats too. The tabulation downloads whole files: the first call on a file can time out while it downloads, and a retry uses the saved copy, on the hosted server as on a local install.

This is the call behind the bachelor's degree chart on the demos page: the 2021 Census individuals file, adults aged 25 to 64, and the share holding each highest credential in each province.

Requestcall_tool
{
  "name": "statcan_pumf_tabulate",
  "arguments": {
    "url": "https://www150.statcan.gc.ca/n1/pub/98m0001x/2023001/cen21_ind_98m0001x_part_rec21.zip",
    "rows": [
      "PR",
      "HDGREE"
    ],
    "statistic": "share",
    "filters": {
      "AGEGRP": ["9", "10", "11", "12", "13", "14", "15", "16"],
      "HDGREE": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
    }
  }
}
Response, trimmedstatcan_pumf.WeightedTable
{
  "data_file": "data_donnees_2021_ind_v2.csv",
  "statistic": "share",
  "weight": "WEIGHT",
  "unweighted_n": 525504,
  "weighted_total": 19463104.065443654,
  "cells": [
    {
      "groups": [
        {"variable": "PR", "code": "10", "label": "newfoundland and labrador"},
        {"variable": "HDGREE", "code": "9", "label": "bachelor's degree"}
      ],
      "estimate": 13.305555555555555,
      "standard_error": 0.42801216439501577,
      "cv": 0.03216792884805964,
      "quality": null,
      "unweighted_n": 958,
      "low_count": false
    }
    // 142 more cells
  ]
  // + url, value_variable, filters, truncated, variance_method, notes, provenance
}
The bachelor's degree cells for the first 5 provinces in the response, rounded.
Provinceestimatestandard_errorcvunweighted_nlow_count
Newfoundland and Labrador13.310.430.032958false
Prince Edward Island18.151.000.055366false
Nova Scotia20.080.340.0172,721false
New Brunswick16.670.330.0201,779false
Quebec18.150.110.00621,670false

Two things decide whether a table like this is right. The first is the weight. The tool uses the codebook's main weight, and it checks labels as well as names, because names can mislead: in one survey file, a variable called WTQ_05 is a question about working at night. The second is the sample behind each cell. Every cell carries its unweighted count, and cells with fewer than 30 respondents are flagged.

Standard errors take more care. I add a survey's variance method only after reading its user guide, and I cite the section. 4 files have one so far, the 2021 Census among them. The Labour Force Survey ships no bootstrap weights, so the server builds the calibrated Poisson bootstrap its user guide prescribes (section 6) and returns a standard error, a CV and a quality flag (acceptable, marginal or unacceptable, from the guide's CV bands) for every cell. For any other file, the result gives no standard error and says why. Two demos use the Census file: bachelor's degrees by province and low income across immigrant generations.

What the live services taught me

I found most of StatCan's quirks by calling the live services, not by reading documentation. Four of them shaped the code.

The overnight lock. From midnight to 8:30 a.m. Eastern, while StatCan updates its data, some requests are refused. Retrying does not help, so the server stops and says to try again after 8:30 on a release day.

The connection that hung. Plain connections to statcan.gc.ca timed out with no useful error. Something on StatCan's network blocks connections set up the way a common Python library sets them up by default. One setting fixes it, and the Python scripts MapleStats writes include it too.

The search that ignored its keyword. StatCan's catalogue search returned the whole reference catalogue, 2,031 documents, unless the session had first visited the catalogue's main page. The server now visits that page first. If a search still comes back unfiltered, it raises an error rather than present the whole catalogue as a match.

Testing against the real API. The first version of the StatCan module called only 2 of its 32 tools against the real API before I called it done. Calling all 32 later found 9 more bugs. Tests on made-up data had missed them, because the made-up data shared the code's wrong assumptions. Now no module counts as done until every function has been called against the real service.

Checking an answer

Before the answer reaches you, the agent can send it to check_answer, which re-reads every StatCan and Bank of Canada figure the answer cites and reports only the problems: a wrong value or scale, a stale period, the wrong geography, an unadjusted series given as the headline, an estimate StatCan flags as unreliable or to use with caution.

An agent's answer is only as good as the check someone can run without the agent. After a call, reproduce_code writes an R, Python, Stata or Julia script, or an Excel Power Query, that fetches the same data directly from StatCan. For the CPI call above, the R script is a single call to the cansim package. The scripts keep each value as StatCan sent it and put the scaled number in a separate column. For someone who works in Excel, reproduce_workbook returns the rows as a formatted workbook, with a sheet that records the call, the source and the licence.

The other services

The other StatCan tools cover classifications such as NAICS, the 2021 Census Profile and the older profiles, census geography and the data behind StatCan's maps, open databases of hospitals, schools and addresses, The Daily, the tables of each Daily release as first published, the release calendar, revised data, trade by commodity, headline indicators, the Sustainable Development Goals and the survey directory. Here is the full list, counted from the registry when this page was built:

Tables and time series

Census

Microdata

Geography and open databases

Classifications

Indicators

Releases, catalogues and methods

Where to go next