# Statistics Finland (StatFin) MCP (`nectia/statfin-mcp`) Actor

Search Statistics Finland's StatFin database (3,000+ tables), inspect table variables, and query clean flattened statistics on population, economy, labour and regions.

- **URL**: https://apify.com/nectia/statfin-mcp.md
- **Developed by:** [Anton Aouat](https://apify.com/nectia) (community)
- **Categories:** MCP servers
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 search statistical tables

This Actor is paid per event and usage. You are charged both the fixed price for specific events and for Apify platform usage.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-event

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## Statistics Finland (StatFin) MCP

An MCP server that gives an AI agent clean, queryable access to **Statistics Finland's
StatFin database** — 3,000+ official statistical tables on population, economy, labour,
housing, prices, and regions. The server does the hard part: it turns StatFin's
dimensional **json-stat2** cubes into flat, labelled rows an agent can read directly.

Data © Statistics Finland, StatFin database, licensed **CC BY 4.0**.

### Tools

| Tool | What it does |
|------|--------------|
| `search_tables` | Find tables by keyword. Returns a ready-to-use `table` path (e.g. `vaerak/11rb.px`), title, and publication date. |
| `get_table_metadata` | List a table's variables (dimensions) and their value codes + labels — the codes you need to query. Flags `time` and `eliminable` variables. |
| `get_data` | Query a table and get **flattened, labelled rows** (json-stat2 decoded for you). Oversize selections (>100,000 cells) are refused with a hint to narrow. |

Agents chain them: **search → metadata (learn the codes) → data**.

Every tool takes an optional `database` (default `StatFin`; also `Kuntien_avainluvut`,
`Postinumeroalueittainen_avoin_tieto`, `StatFin_Passiivi`) and `language` (`en`/`fi`/`sv`).

### Example

> "What was Finland's population at the end of 2024 and 2025, by sex?"

1. `search_tables({ query: "population" })` → finds `vaerak/11rb.px`.
2. `get_table_metadata({ table: "vaerak/11rb.px" })` → variables `timeperiod_y` (Year),
   `sukupuoli_9_20180101` (Sex, values `SSS`/`1`/`2`), `contentscode`.
3. `get_data({ table: "vaerak/11rb.px", selections: { timeperiod_y: ["2024","2025"],
   sukupuoli_9_20180101: ["SSS","1","2"], contentscode: ["vaerak-vaesto"] } })` →

```json
{
  "label": "Population 31.12. by Year, Sex and Information",
  "source": "Statistics Finland, population structure",
  "rowCount": 6,
  "dimensions": [
    { "code": "timeperiod_y", "label": "Year", "size": 2 },
    { "code": "sukupuoli_9_20180101", "label": "Sex", "size": 3 },
    { "code": "contentscode", "label": "Information", "size": 1 }
  ],
  "rows": [
    { "Year": "2024", "Sex": "Total", "Information": "Population 31 Dec", "value": 5635971 },
    { "Year": "2024", "Sex": "Males", "Information": "Population 31 Dec", "value": 2790772 },
    { "Year": "2024", "Sex": "Females", "Information": "Population 31 Dec", "value": 2845199 }
  ]
}
```

### Local use (stdio)

```bash
npm install
npm run build
```

Claude Desktop config:

```json
{
  "mcpServers": {
    "statfin": {
      "command": "node",
      "args": ["/absolute/path/to/servers/statfin/dist/server.js"]
    }
  }
}
```

No API key is required — StatFin is open data.

### Development

```bash
npm run typecheck   # tsc --noEmit
npm test            # vitest — unit tests vs recorded real fixtures (offline)
npm run smoke       # live: boots the server, real MCP handshake + real StatFin calls
npm run build       # produces dist/
```

Windows note: this repo lives under a path with spaces, which breaks npm's `.bin`
shims. Run tools directly (`node ./node_modules/vitest/vitest.mjs run`,
`node ./node_modules/typescript/bin/tsc`) or run the npm scripts from PowerShell.

### Design

- `src/statfin/client.ts` — HTTP only (GET search + metadata, POST data). Throttle
  (~1 req/1.5 s, under the 40 req/60 s limit) + short TTL cache. Typed `StatFinApiError`.
- `src/statfin/normalize.ts` — the product: tidy search hits, flatten metadata, and
  **decode json-stat2 cubes into flat rows**.
- `src/statfin/query.ts` — build a PxWeb query from a simple `{ code: values[] }`
  selection; validate codes, expand `*`, aggregate eliminable variables, and guard the
  cell limit before hitting the network.
- `src/tools.ts` — the 3 MCP tools + Pay-Per-Event billing hook.
- `src/server.ts` (stdio) / `src/standby.ts` (Apify HTTP) — both call one factory.

# Actor input Schema

## Actor input object example

```json
{}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("nectia/statfin-mcp").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("nectia/statfin-mcp").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call nectia/statfin-mcp --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=nectia/statfin-mcp",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/UX5C2hQJxTtMw4cSC/builds/9Or0lOfgmej8jCnQz/openapi.json
