Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | 4x 4x 4x 4x 9x 9x 9x 1x 1x 1x 1x 1x 1x 1x 3x 25x 30x 6x 5x 5x 6x 3x 3x 1x 2x 5x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 4x 3x 1x 3x | /**
* @module SCB/Client
* @description TypeScript client for Statistics Sweden (SCB) data via MCP server.
* Provides typed access to SCB statistical tables for enriching political
* intelligence with official Swedish statistics.
*
* Works with the SCB MCP server (https://scb-mcp.onrender.com/mcp) which
* exposes the PxWebAPI 2.0 for programmatic access to SCB's statistical database.
*
* @author Hack23 AB
* @license Apache-2.0
* @see https://www.scb.se/en/services/open-data-api/api-for-the-statistical-database/
*/
import type { SCBIndicator } from './data-transformers/types.js';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/** Configuration for the SCB MCP client */
export interface SCBClientConfig {
/** SCB MCP server URL (default: https://scb-mcp.onrender.com/mcp) */
readonly serverUrl?: string;
/** Request timeout in ms (default: 15000) */
readonly timeout?: number;
/** Max retry attempts (default: 2) */
readonly maxRetries?: number;
}
/** A raw table search result from SCB */
export interface SCBTableInfo {
readonly tableId: string;
readonly label: string;
readonly category: string;
readonly updated: string;
}
/** Raw data point from an SCB table */
export interface SCBDataPoint {
readonly tableId: string;
readonly label: string;
readonly value: number;
readonly unit: string;
readonly period: string;
}
/** SCB policy domain definition with query and table mappings */
export interface SCBDomainConfig {
readonly domain: string;
readonly query: string;
readonly tables: readonly string[];
readonly indicators: readonly string[];
}
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DEFAULT_SERVER_URL = 'https://scb-mcp.onrender.com/mcp';
const DEFAULT_TIMEOUT = 15_000;
const DEFAULT_MAX_RETRIES = 2;
/**
* SCB domain table mappings connecting policy domains to SCB table IDs.
* Each domain has search query terms, known table IDs, and key indicators.
*/
export const SCB_DOMAINS: readonly SCBDomainConfig[] = [
{
domain: 'fiscal',
query: 'skatter statsbudget offentliga finanser',
tables: ['TAB1291', 'TAB1292'],
indicators: ['Government revenue', 'Government expenditure', 'Budget balance'],
},
{
domain: 'defence',
query: 'försvar militär offentliga utgifter',
tables: [],
indicators: ['Defence spending % GDP'],
},
{
domain: 'environment',
query: 'växthusgaser utsläpp miljö',
tables: ['TAB5404', 'TAB5407'],
indicators: ['GHG emissions', 'Renewable energy share'],
},
{
domain: 'education',
query: 'utbildning studenter skola',
tables: ['TAB4787', 'TAB4790'],
indicators: ['Student enrollment', 'Graduation rates'],
},
{
domain: 'healthcare',
query: 'hälsa sjukvård vård',
tables: [],
indicators: ['Healthcare spending', 'Hospital beds'],
},
{
domain: 'migration',
query: 'invandring utvandring migration befolkning',
tables: ['TAB637', 'TAB4230'],
indicators: ['Immigration', 'Emigration', 'Net migration'],
},
{
domain: 'eu-foreign',
query: 'utrikeshandel export import',
tables: ['TAB2661'],
indicators: ['Export value', 'Import value', 'Trade balance'],
},
{
domain: 'justice',
query: 'brott lagföringar kriminalstatistik',
tables: ['TAB1172'],
indicators: ['Reported crimes', 'Conviction rate'],
},
{
domain: 'labour',
query: 'sysselsättning arbetslöshet arbetsmarknad',
tables: ['TAB5765', 'TAB5616'],
indicators: ['Unemployment rate', 'Employment rate'],
},
{
domain: 'housing',
query: 'bostäder nybyggnation hyror',
tables: ['TAB2052', 'TAB4709'],
indicators: ['Housing starts', 'Price index'],
},
{
domain: 'transport',
query: 'trafik transport infrastruktur',
tables: [],
indicators: ['Road traffic', 'Transit ridership'],
},
{
domain: 'trade',
query: 'näringsliv företag BNP',
tables: ['TAB5802', 'TAB5803'],
indicators: ['GDP growth', 'Business starts', 'Industrial production'],
},
{
domain: 'taxation',
query: 'skatter inkomstskatt moms skatteintäkter',
tables: ['TAB1291'],
indicators: ['Tax revenue', 'Income tax', 'VAT revenue'],
},
{
domain: 'culture',
query: 'kultur fritid idrott bibliotek',
tables: ['TAB5195'],
indicators: ['Cultural expenditure', 'Library visits', 'Cultural participation'],
},
{
domain: 'governance',
query: 'demokrati valdeltagande riksdag',
tables: [],
indicators: ['Voter turnout', 'Parliamentary transparency'],
},
] as const;
// ---------------------------------------------------------------------------
// SCBClient class
// ---------------------------------------------------------------------------
/**
* Client for accessing Statistics Sweden (SCB) data via MCP server.
* Provides domain-based queries and indicator lookups.
*/
export class SCBClient {
readonly serverUrl: string;
readonly timeout: number;
readonly maxRetries: number;
constructor(config: SCBClientConfig = {}) {
this.serverUrl = config.serverUrl ?? DEFAULT_SERVER_URL;
this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
}
/**
* Search SCB tables by query string.
*
* @param query - Search terms (e.g., 'arbetslöshet sysselsättning')
* @param limit - Maximum number of results (default: 5)
* @returns Array of matching table info
*/
async searchTables(query: string, limit = 5): Promise<SCBTableInfo[]> {
const params = { query, limit };
const result = await this.callTool<SCBTableInfo[]>('search_tables', params);
return result ?? [];
}
/**
* Fetch data from a specific SCB table.
*
* @param tableId - SCB table identifier (e.g., 'TAB5765')
* @param selection - Optional selection filters (e.g., { Tid: ['TOP(4)'] })
* @returns Array of data points
*/
async getTableData(
tableId: string,
selection?: Record<string, string[]>,
): Promise<SCBDataPoint[]> {
const params: Record<string, unknown> = { tableId };
Iif (selection) {
params.selection = selection;
}
const result = await this.callTool<SCBDataPoint[]>('get_table_data', params);
return result ?? [];
}
/**
* Find SCB domain configuration for a policy area.
*
* @param domain - Policy domain key (e.g., 'labour', 'fiscal')
* @returns Domain config or undefined
*/
findDomain(domain: string): SCBDomainConfig | undefined {
return SCB_DOMAINS.find(
(d) => d.domain.toLowerCase() === domain.toLowerCase(),
);
}
/**
* Get all domains that have known table IDs for direct data access.
*
* @returns Domains with pre-configured table IDs
*/
getDomainsWithTables(): readonly SCBDomainConfig[] {
return SCB_DOMAINS.filter((d) => d.tables.length > 0);
}
/**
* Build an SCBIndicator from raw data points.
* Computes trend by comparing latest two values.
*
* @param label - Human-readable indicator label
* @param dataPoints - Raw data points sorted by period descending
* @param tableId - Source SCB table ID
* @returns SCBIndicator or null if no data
*/
buildIndicator(
label: string,
dataPoints: readonly SCBDataPoint[],
tableId: string,
): SCBIndicator | null {
if (dataPoints.length === 0) return null;
const latest = dataPoints[0];
const previous = dataPoints.length > 1 ? dataPoints[1] : undefined;
let trend: 'up' | 'down' | 'stable' | undefined;
if (previous) {
const diff = latest.value - previous.value;
if (Math.abs(diff) < 0.001) {
trend = 'stable';
} else {
trend = diff > 0 ? 'up' : 'down';
}
}
return {
label,
value: latest.value,
unit: latest.unit || 'units',
period: latest.period,
tableId,
trend,
previousValue: previous?.value,
};
}
// -----------------------------------------------------------------------
// Internal helpers
// -----------------------------------------------------------------------
private async callTool<T>(toolName: string, params: Record<string, unknown>): Promise<T | null> {
try {
const response = await this.fetchWithRetry(toolName, params);
return response as T;
} catch (error) {
// Log for debugging MCP connection issues; return null as graceful fallback
console.warn(`SCB MCP call to ${toolName} failed:`, error instanceof Error ? error.message : error);
return null;
}
}
private async fetchWithRetry(
toolName: string,
params: Record<string, unknown>,
attempt = 0,
): Promise<unknown> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
try {
const response = await fetch(this.serverUrl, {
method: 'POST',
signal: controller.signal,
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
method: 'tools/call',
params: { name: toolName, arguments: params },
id: Date.now(),
}),
});
if (!response.ok) {
throw new Error(`SCB MCP error: ${response.status} ${response.statusText}`);
}
const json = (await response.json()) as { result?: { content?: Array<{ text?: string }> }; error?: unknown };
if (json.error) {
throw new Error(`SCB MCP tool error: ${JSON.stringify(json.error)}`);
}
// MCP responses wrap content in result.content[].text
const text = json.result?.content?.[0]?.text;
Iif (text) {
try {
return JSON.parse(text);
} catch {
console.warn(`SCB MCP response for ${toolName} was not valid JSON; treating as error`);
throw new Error(`SCB MCP response for ${toolName} was not valid JSON`);
}
}
return json.result ?? null;
} catch (error) {
Iif (attempt < this.maxRetries) {
const delay = 1000 * (attempt + 1);
await new Promise((resolve) => setTimeout(resolve, delay));
return this.fetchWithRetry(toolName, params, attempt + 1);
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}
}
// ---------------------------------------------------------------------------
// Singleton
// ---------------------------------------------------------------------------
let defaultSCBClient: SCBClient | null = null;
/** Get or create the default singleton SCBClient */
export function getDefaultSCBClient(): SCBClient {
if (!defaultSCBClient) {
defaultSCBClient = new SCBClient();
}
return defaultSCBClient;
}
|