# US Census Bureau Intelligence MCP — ACS Demographics (`andrew_avina/census-mcp`) Actor

An Apify actor that exposes the US Census Bureau ACS (American Community Survey) API as a Model Context Protocol (MCP) server. AI assistants and developer tools can call four structured tools to retrieve state demographics, county demographics, ZIP code profiles, and side-by-s...

- **URL**: https://apify.com/andrew\_avina/census-mcp.md
- **Developed by:** [Andrew Avina](https://apify.com/andrew_avina) (community)
- **Categories:** MCP servers, Business
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$3.00 / 1,000 result item returneds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#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

## US Census Bureau Data Intelligence MCP Server

An Apify actor that exposes the **US Census Bureau ACS (American Community Survey) API** as a Model Context Protocol (MCP) server. AI assistants and developer tools can call four structured tools to retrieve state demographics, county demographics, ZIP code profiles, and side-by-side geography comparisons — all powered by the definitive source for US demographic data.

No API key is required for standard use. An optional Census API key enables higher rate limits.

***

### What This Actor Does

The Census Bureau's American Community Survey is the most comprehensive ongoing statistical program in the United States, collecting information from over 3.5 million households annually. The 5-year ACS estimates provide the most detailed and statistically reliable demographic data available at the local level.

This actor parses the Census Bureau's unusual 2D-array response format (first row = column headers) into clean, normalized dicts and exposes them via MCP. The result: any AI agent can answer demographic questions about any location in the US with a single tool call.

**Supported data:** Population, income, age, housing, education attainment, race/ethnicity, immigration status, and employment.

***

### ACS Variables Available

The following variables are available via friendly names or raw ACS codes:

| Friendly Name | ACS Code | Description |
|---------------|----------|-------------|
| `total_population` | B01001\_001E | Total population |
| `median_household_income` | B19013\_001E | Median household income (dollars) |
| `median_age` | B01002\_001E | Median age (years) |
| `housing_units` | B25001\_001E | Total housing units |
| `median_home_value` | B25077\_001E | Median owner-occupied home value |
| `unemployment` | B23025\_005E | Unemployed persons in labor force |
| `poverty_count` | B17001\_002E | Persons below poverty level |
| `bachelor_degree` | B15003\_022E | Persons with bachelor's degree |
| `white_alone` | B02001\_002E | White alone (race) |
| `black_alone` | B02001\_003E | Black or African American alone |
| `hispanic` | B03003\_003E | Hispanic or Latino |
| `foreign_born` | B05002\_013E | Foreign-born population |
| `limited_english` | B16004\_023E | Speak English less than "very well" |

Pass any subset as `variables: ["total_population", "median_household_income"]`, or omit to get all.

***

### MCP Tools Available

Point your MCP client at `http://<actor-run-url>:4321` after setting `serveMcp: true`.

#### 1. `get_state_demographics`

Retrieve ACS 5-year estimates for one or all US states.

**Parameters:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `state_fips` | string | No | 2-digit FIPS code or `*` for all states (default `*`) |
| `year` | integer | No | Survey year (default 2022) |
| `variables` | array | No | Variable names/codes. Empty = all |
| `api_key` | string | No | Census API key |
| `limit` | integer | No | Max states returned (default 60) |

**Returns:** List of state records with `state_name`, `state_fips`, all requested variables, `year`, `source`.

**Example:**

```json
{
  "name": "get_state_demographics",
  "arguments": {
    "state_fips": "*",
    "variables": ["total_population", "median_household_income", "median_age"],
    "year": 2022
  }
}
```

**Common state FIPS codes:** Alabama=01, Alaska=02, Arizona=04, Arkansas=05, California=06, Colorado=08, Connecticut=09, Delaware=10, Florida=12, Georgia=13, Hawaii=15, Idaho=16, Illinois=17, Indiana=18, Iowa=19, Kansas=20, Kentucky=21, Louisiana=22, Maine=23, Maryland=24, Massachusetts=25, Michigan=26, Minnesota=27, Mississippi=28, Missouri=29, Montana=30, Nebraska=31, Nevada=32, New Hampshire=33, New Jersey=34, New Mexico=35, New York=36, North Carolina=37, North Dakota=38, Ohio=39, Oklahoma=40, Oregon=41, Pennsylvania=42, Rhode Island=44, South Carolina=45, South Dakota=46, Tennessee=47, Texas=48, Utah=49, Vermont=50, Virginia=51, Washington=53, West Virginia=54, Wisconsin=55, Wyoming=56, DC=11

***

#### 2. `get_county_demographics`

Retrieve ACS 5-year estimates for counties within a state.

**Parameters:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `state_fips` | string | Yes | 2-digit state FIPS code |
| `county_fips` | string | No | 3-digit county FIPS or `*` for all counties (default `*`) |
| `year` | integer | No | Survey year (default 2022) |
| `variables` | array | No | Variable names/codes |
| `api_key` | string | No | Census API key |
| `limit` | integer | No | Max counties (default 100) |

**Returns:** List of county records with `county_name`, `state_fips`, `county_fips`, all variables, `year`, `source`.

**Example:**

```json
{
  "name": "get_county_demographics",
  "arguments": {
    "state_fips": "06",
    "variables": ["total_population", "median_household_income"],
    "year": 2022
  }
}
```

***

#### 3. `get_zip_demographics`

Retrieve ACS 5-year estimates for a single ZIP Code Tabulation Area (ZCTA).

**Parameters:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `zip_code` | string | Yes | 5-digit ZIP code |
| `year` | integer | No | Survey year (default 2022) |
| `variables` | array | No | Variable names/codes |
| `api_key` | string | No | Census API key |

**Returns:** Record with `zip_code`, all variables, `year`, `source`.

**Note:** Not all ZIPs are ZCTAs. PO Box-only ZIPs and some rural ZIPs may not have ACS coverage and will return a graceful fallback.

**Example:**

```json
{
  "name": "get_zip_demographics",
  "arguments": {
    "zip_code": "10001",
    "variables": ["total_population", "median_household_income", "foreign_born"]
  }
}
```

***

#### 4. `compare_geographies`

Compare demographic data across multiple geographies side by side. Supports states, counties, or ZIP codes.

**Parameters:**
| Name | Type | Required | Description |
|------|------|----------|-------------|
| `geo_type` | string | Yes | `state`, `county`, or `zip` |
| `geo_ids` | array | Yes | List of FIPS codes, `STATE:COUNTY` pairs, or ZIP codes |
| `variables` | array | No | Variable names/codes |
| `year` | integer | No | Survey year (default 2022) |
| `api_key` | string | No | Census API key |

**Returns:** List of records, one per geography, with `geo_id`, `geo_name`, all variables, `year`, `source`.

**Examples:**

Compare three states:

```json
{
  "name": "compare_geographies",
  "arguments": {
    "geo_type": "state",
    "geo_ids": ["06", "48", "36"],
    "variables": ["total_population", "median_household_income", "median_home_value"]
  }
}
```

Compare ZIP codes:

```json
{
  "name": "compare_geographies",
  "arguments": {
    "geo_type": "zip",
    "geo_ids": ["90210", "10001", "60601"],
    "variables": ["total_population", "median_household_income"]
  }
}
```

Compare counties (California):

```json
{
  "name": "compare_geographies",
  "arguments": {
    "geo_type": "county",
    "geo_ids": ["06:037", "06:073", "06:001"],
    "variables": ["total_population", "median_household_income"]
  }
}
```

***

### Running Modes

#### Batch Mode (default)

Set `serveMcp: false` (default). The actor fetches demographic data for the specified geography and pushes results to the dataset.

**State batch (default):**

```json
{
  "geoType": "state",
  "stateFips": "*",
  "year": 2022,
  "limit": 55
}
```

**County batch:**

```json
{
  "geoType": "county",
  "stateFips": "06",
  "year": 2022
}
```

**ZIP batch:**

```json
{
  "geoType": "zip",
  "zipCode": "90210",
  "year": 2022
}
```

#### MCP Server Mode

Set `serveMcp: true`. The actor starts an HTTP server on port 4321 and stays alive for up to 24 hours.

```json
{
  "serveMcp": true,
  "year": 2022
}
```

***

### MCP Endpoint Reference

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/` | GET | Health check |
| `/health` | GET | Health check |
| `/mcp/tools` | GET | List all 4 tools with schemas |
| `/mcp/call` | POST | Call a tool |

***

### Census API Response Format

The Census Bureau returns data as a 2D JSON array:

```json
[
  ["NAME", "B01001_001E", "B19013_001E", "state"],
  ["California", "39538223", "84097", "06"],
  ["Texas", "29145505", "63826", "48"]
]
```

This actor's `_parse_census_response()` function automatically converts this into a list of dicts using the first row as keys, then maps raw ACS codes to friendly names. The value `-666666666` (Census suppression sentinel) is converted to `None`.

***

### Use Cases

#### Market Research and Site Selection

Query county or ZIP demographics to evaluate potential business locations: population density, income levels, age distribution, and housing market characteristics.

#### Real Estate Analysis

Combine `median_home_value`, `median_household_income`, and `total_population` for any geography to assess affordability and market conditions.

#### Public Policy and Grant Writing

Provide demographic evidence for grant applications. Query poverty counts, unemployment figures, and limited English proficiency by county or ZIP.

#### AI Agent Integration

Connect to Claude as an MCP server. The agent can answer: "What is the median household income in the 10 largest counties in Texas?" by calling `get_county_demographics` with state\_fips=48 and filtering by population.

#### Competitive Intelligence

Compare demographics across markets your competitors operate in vs. untapped markets. Use `compare_geographies` for direct side-by-side output.

#### Academic and Journalistic Research

Journalists and researchers can query all 50 states at once for any variable, enabling data-driven stories about economic inequality, demographic shifts, or housing affordability.

#### Diversity and Inclusion Reporting

Pull race/ethnicity variables (`white_alone`, `black_alone`, `hispanic`, `foreign_born`) for any geography to support DEI reporting and workforce analysis.

***

### Error Handling

All tools return graceful fallbacks on any error:

```json
[{"_meta": {"error": "description", "fallback_tried": true}}]
```

The Census API returns HTTP 400 for invalid FIPS codes or unsupported year/variable combinations. These errors are caught and returned in the `_meta` structure — the actor never crashes.

***

### Output Dataset Fields (State Mode)

| Field | Type | Description |
|-------|------|-------------|
| `state_name` | string | Full state name (from Census NAME field) |
| `state_fips` | string | 2-digit FIPS code |
| `total_population` | integer | ACS total population estimate |
| `median_household_income` | integer | Median household income in dollars |
| `median_age` | integer | Median age in years |
| `housing_units` | integer | Total housing units |
| `median_home_value` | integer | Median owner-occupied home value |
| `unemployment` | integer | Number unemployed in labor force |
| `poverty_count` | integer | Number below poverty level |
| `bachelor_degree` | integer | Number with bachelor's degree |
| `white_alone` | integer | White alone population |
| `black_alone` | integer | Black or African American alone |
| `hispanic` | integer | Hispanic or Latino population |
| `foreign_born` | integer | Foreign-born population |
| `limited_english` | integer | Speak English less than "very well" |
| `year` | integer | ACS survey year |
| `source` | string | Always `census.gov` |

***

### Getting a Census API Key (Optional)

Free registration at: <https://api.census.gov/data/key_signup.html>

Without a key: 500 requests per IP per day limit.
With a key: Higher limits suitable for production use.

Pass via `apiKey` in actor input or directly in tool arguments as `api_key`.

***

### Technical Details

- **Runtime**: Python 3.11+
- **Framework**: Apify SDK v2+
- **HTTP client**: httpx (async)
- **MCP server**: asyncio raw TCP, HTTP/1.1
- **Port**: 4321
- **Max server lifetime**: 24 hours
- **Dataset**: ACS 5-year (most reliable for small geographies)
- **Timeout per call**: 30 seconds

***

### Connecting via Claude Desktop

```json
{
  "mcpServers": {
    "census": {
      "url": "http://<your-actor-run-url>:4321"
    }
  }
}
```

***

### License

US Census Bureau data is US government public domain. This actor code is MIT licensed.

# Actor input Schema

## `serveMcp` (type: `boolean`):

If true, starts the MCP HTTP server on port 4321. Leave false for one-shot batch state demographics fetch.

## `geoType` (type: `string`):

Type of geography to query in batch mode: 'state', 'county', or 'zip'.

## `stateFips` (type: `string`):

2-digit state FIPS code (e.g. '06' for California). Use '*' for all states. Default '*'.

## `year` (type: `integer`):

ACS 5-year survey year to query (e.g. 2022). Must have published ACS data.

## `apiKey` (type: `string`):

Optional Census Bureau API key for higher rate limits. Free at https://api.census.gov/data/key\_signup.html

## `limit` (type: `integer`):

Maximum number of records to return (default 60, covers all states + DC + territories).

## `zipCode` (type: `string`):

5-digit ZIP code for batch ZIP demographic lookup (only used when geoType='zip').

## Actor input object example

```json
{
  "serveMcp": false,
  "geoType": "state",
  "stateFips": "*",
  "year": 2022,
  "limit": 60
}
```

# 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("andrew_avina/census-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("andrew_avina/census-mcp").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).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 andrew_avina/census-mcp --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,andrew_avina/census-mcp"
        }
    }
}

```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

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