Skip to main content
Glama
census-cbp-mcp

census-cbp-mcp

README.md
# census-cbp-mcp

Secure, multi-user MCP access to the official U.S. Census Bureau County Business Patterns (CBP) and ZIP Code Business Patterns (ZBP) APIs for every vintage documented by Census from 1986 through 2023. The repository is a standalone adaptation of the public `LesterAJohn/skeleton-mcp` reference application.

## Source and provenance

- Upstream: <https://github.com/LesterAJohn/skeleton-mcp>
- Copied skeleton source commit: `bfbf26a6939a3c3c387a34bd2461f1bb5d0b8eec`
- Adaptation: `census-cbp-mcp` / `LesterAJohn/census-cbp-mcp`
- This standalone repository has a fresh Git history; it is not a fork.

The preserved source documents are in [API-DOCS.md](API-DOCS.md) and [docs/](docs/). They are retained unchanged. Official live metadata snapshots were added separately under [inventory/sources](inventory/sources).

## Capabilities

- MCP stdio, HTTP, or both through the existing skeleton transport processes.
- Modern and legacy MCP protocol compatibility.
- HTTP bearer-token, OAuth2 introspection, or combined authentication.
- Vault-backed multi-user token index, default-principal fallback, bearer/OAuth seeding, and Vault token lifecycle tools.
- Vault Agent file, listener, or both runtime modes, including Postgres-backed non-secret pointers.
- Multi-tenant user/account identity with default scope fallback and cross-scope checks.
- Optional trusted Apify/MCPize caller identity and per-user initialization.
- Postgres configuration, agent config, tasks, memory, schedules, grants, audit data, and checkpoints.
- Mandatory agent/A2A and dedicated pg-boss worker infrastructure in supported Compose flows.
- Vault Raft persistence, managed unseal-key init ordering, and external Vault/Postgres deployment support.
- Plaintext HTTP by default for loopback or trusted internal reverse-proxy use; optional native HTTPS remains supported.

`MCP_SERVER_NAME=census-cbp-mcp` is the single naming source. Current Postgres objects use the `census_cbp_mcp_` prefix, LangGraph uses `census_cbp_mcp_langgraph`, pg-boss uses `census_cbp_mcp_pgboss`, and Vault paths begin with `census-cbp-mcp/`. `APP_NAME` is only a legacy migration source. Changing `MCP_SERVER_NAME` changes these namespaces and requires an explicit migration plan.

## Honest API coverage

The Census API does not expose an OpenAPI document for this catalog, so the inventory is generated from official year-specific Census metadata:

```bash
npm run inventory:generate
npm run inventory:check
```

Outputs:

- [inventory/census-api-inventory.json](inventory/census-api-inventory.json)
- [inventory/COVERAGE.md](inventory/COVERAGE.md)
- committed normalized official catalog snapshots: [inventory/sources/cbp-catalog-snapshots.json](inventory/sources/cbp-catalog-snapshots.json)

Selection rule: available official catalog records whose `c_dataset` path is `cbp` or `zbp`, for the 38 vintages listed by the local CBP documentation. The committed inventory contains **63 callable datasets**:

| Dataset | Vintages | Endpoints |
| --- | --- | ---: |
| CBP | 1986-2023 | 38 |
| ZBP | 1994-2018 | 25 |

Every selected dataset has a dedicated generated MCP query tool. Dataset field names, predicates, geographies, and responses are not invented; callers first use the official metadata tools and then submit query strings to the Census API. Records outside the documented CBP/ZBP rule are not mislabeled as operations. All data calls are public read-only `GET` operations; credential administration is the only service-specific mutating surface.

## Census MCP tools

Every inventory row maps to:

```text
census_<year>_<normalized_dataset_path>_query
```

For example, `census_2023_cbp_query` queries `GET /2023/cbp`.

Shared discovery and query tools:

| Tool | Classification | Purpose |
| --- | --- | --- |
| `census_list_datasets` | read-only | List/filter the committed dataset inventory and generated names |
| `census_query_dataset` | read-only | Query any inventoried dataset by year and dataset path |
| `census_dataset_variables` | read-only | Fetch the official `variables.json` |
| `census_dataset_geography` | read-only | Fetch official geography metadata |
| `census_dataset_groups` | read-only | Fetch official group metadata |
| `census_dataset_examples` | read-only | Fetch official example metadata |
| `service_api_request` | read-only | Allowlisted GET compatibility for inventoried paths |
| `service_list_endpoints` | read-only | List all generated endpoint mappings |
| `service_health_check` | read-only | Check the official Census catalog endpoint |
| `service_query_suggestion` | read-only | Suggest metadata/query tool sequences and expose schemas |

Credential tools:

| Tool | Classification | Protection |
| --- | --- | --- |
| `census_credential_info` | read-only | Returns path, scope, fingerprint, and rotation time only |
| `census_credential_set` | high-risk mutation | `authorizationKey` / admin scope; stores key in Vault |
| `census_credential_rotate` | high-risk mutation | `authorizationKey` / admin scope; replaces Vault key |
| `census_credential_delete` | high-risk mutation | `authorizationKey` / admin scope; deletes scoped key |

A Census API key is required for data calls and is provisioned as a scoped Vault secret. It is stored at:

```text
census-cbp-mcp/tenants/<tenant>/<users|accounts>/<principal>/credentials/census/api-key
```

The key is never placed in Postgres, task state, schedules, logs, query output, URL output, or agent memory. The adapter resolves it for each outbound request to `https://api.census.gov`, then returns no URL containing it. Calls fail with an actionable prerequisite error if no key is configured. Set/rotate requires a configured `MCP_ADMIN_AUTH_KEY` in key mode or `mcp:admin` in scope mode.

## Preserved infrastructure tools

The skeleton's tool surface remains available:

- Config: `config_list`, `config_get`, `config_set`, `config_delete`, `token_rotation_config`
- Vault access: `vault_seed_http_token`, `vault_seed_oauth_token`, `vault_agent_token_read`
- Vault lifecycle: `token_lookup_self`, `token_renew_self`, `token_create`, `token_revoke`, `token_revoke_self`
- Tenancy: `tenancy_tenant_*`, `tenancy_user_*`, `tenancy_account_*`
- Agent: `agent_config_*`, `agent_goal`, `agent_task_*`, `agent_composition_run`, composition/memory tools
- Schedules/grants/runs: the complete `agent_schedule_*` catalog
- pg-boss: complete read and guarded administrative/job-management catalog

All mutating infrastructure tools retain the skeleton's admin checks. Query and config paths derive identity from authenticated context; caller identity cannot silently switch tenant/user/account.

## Quick start

Node.js 22 or newer is required.

```bash
cp .env.example .env
npm ci
npm run inventory:check
npm test
```

For stdio:

```bash
MCP_TRANSPORT_MODE=stdio npm run start:stdio
```

For HTTP/A2A:

1. Start `npm run start:http` with the default `MCP_HTTP_TLS_ENABLED=false`.
2. Keep the listener on loopback (`MCP_HTTP_HOST=127.0.0.1`) or behind a trusted internal TLS-terminating reverse proxy. Do not expose plaintext HTTP directly to the public internet.

The default MCP endpoint is `http://127.0.0.1:3000/mcp`; health is `/healthz`; A2A is `/a2a`; the public Agent Card is `/.well-known/agent-card.json`.

To use native TLS instead, set `MCP_HTTP_TLS_ENABLED=true`, `MCP_HTTP_TLS_CERT_PATH`, and `MCP_HTTP_TLS_KEY_PATH` to externally provisioned files. Optional passphrase and minimum-version settings remain supported. No production certificate or private key is generated, committed, or required for the default HTTP path.

Start both transports with `npm run start:both`. The supported worker is a separate process:

```bash
MCP_AGENT_WORKER_ENABLED=true PGBOSS_ENABLED=true npm run start:agent-worker
```

Inference is intentionally not preconfigured. A fresh installation can start MCP/A2A and report readiness, but inference-dependent execution returns an actionable prerequisite error until an operator uses the preserved `agent_config_*` and credential tools.

### MCP client example

```json
{
  "mcpServers": {
    "census-cbp-mcp": {
      "command": "npm",
      "args": ["run", "start:stdio"],
      "cwd": "/absolute/path/to/census-cbp-mcp"
    }
  }
}
```

For default loopback HTTP use `http://127.0.0.1:3000/mcp`. For a trusted internal deployment, clients may use the proxy's internal HTTP endpoint; a public or remote client should use an HTTPS reverse-proxy URL or a native-TLS endpoint. Always use a Vault-index or OAuth bearer token, and do not put bearer tokens in committed client configuration.

## Environment variables

Core:

- `MCP_SERVER_NAME` (default `census-cbp-mcp`)
- `MCP_SERVER_VERSION`
- `MCP_TRANSPORT_MODE=stdio|http|both`
- `MCP_ADMIN_AUTH_KEY`, `MCP_AUTHZ_MODE=auto|admin-key|oauth-scopes`
- `MCP_ALLOW_SENSITIVE_OUTPUT` (keep `false`)
- `CENSUS_API_BASE_URL=https://api.census.gov/data` (official origin enforced)
- `CENSUS_API_TIMEOUT_MS`

Postgres/pg-boss:

- `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`
- optional `POSTGRES_CONNECTION_STRING`
- `PGBOSS_ENABLED`, `PGBOSS_SUPERVISE`, `PGBOSS_MIGRATE`, `PGBOSS_CREATE_SCHEMA`, `PGBOSS_CONNECTION_STRING`
- `MCP_CONFIG_DEFAULT_TENANT_ID`, `MCP_CONFIG_DEFAULT_PRINCIPAL_TYPE`, `MCP_CONFIG_DEFAULT_USER_ID`, `MCP_CONFIG_DEFAULT_ACCOUNT_ID`

Vault:

- `VAULT_ADDR`, `VAULT_TOKEN`, `VAULT_KV_MOUNT`
- `VAULT_AGENT_ENABLED`, `VAULT_AGENT_AUTH_MODE=none|file|listener|both`
- `VAULT_AGENT_TOKEN_FILE_PATH`, `VAULT_AGENT_LISTENER_ENABLED`, `VAULT_AGENT_LISTENER_ADDR`
- `VAULT_UNSEAL_KEY` or managed `src/config/vault.unseal.key.json`
- Vault retry variables from [.env.example](.env.example)

HTTP/auth:

- `MCP_HTTP_HOST`, `MCP_HTTP_PORT`, `MCP_HTTP_PATH`, `MCP_HTTP_HEALTH_PATH`
- `MCP_HTTP_AUTH_MODE=token|oauth2|both`, `MCP_HTTP_TOKEN_SOURCE`
- optional `MCP_HTTP_APIFY_PROXY_TOKEN` and `MCP_HTTP_MCPIZE_PROXY_TOKEN`
- static/Vault token, scope, audience, OAuth provider/introspection settings
- body/rate/IP/origin limits
- `MCP_HTTP_PUBLISH_HOST` (Compose host publication default `127.0.0.1`)
- `MCP_HTTP_TLS_ENABLED` (default `false`)
- `MCP_HTTP_TLS_CERT_PATH`, `MCP_HTTP_TLS_KEY_PATH` (required only when native TLS is enabled)
- optional `MCP_HTTP_TLS_KEY_PASSPHRASE`, `MCP_HTTP_TLS_MIN_VERSION`

### OAuth2 scopes

OAuth2 introspection can require scopes from the identity provider and map provider-specific scopes to the MCP scopes used for authorization. The accepted MCP scopes are:

| MCP scope | Required authentication mode | Permitted capability classes | Classification |
| --- | --- | --- | --- |
| `mcp:invoke` | OAuth, Vault-token, or static bearer token; also the default Vault-token admission requirement | General MCP access plus agent/A2A execution | read/execution |
| `mcp:agent` | OAuth/Vault bearer when explicitly granted | Alternative admission scope for agent/A2A execution only | read/execution |
| `mcp:read` | Optional provider or token scope; granted by token-seeding defaults | Read-only MCP discovery and query capabilities; most read tools do not require a separate per-tool check | read-only |
| `mcp:write` | `MCP_AUTHZ_MODE=oauth-scopes`, or `auto` for OAuth callers | General scoped mutations, schedules/grants, and mutating agent/composition capabilities | mutating |
| `mcp:admin` | OAuth scope mode only; global substitute for the more specific admin scopes | High-risk Vault/token, pg-boss, credential, configuration, and agent administration | admin-only |
| `mcp:tenancy:admin` | OAuth scope mode; `mcp:admin` also satisfies it | Tenant, user, and account administration | admin-only |
| `mcp:proxy:initialize` | Trusted Apify/MCPize bootstrap identity | `proxy_user_initialize` only | mutating |
| `mcp:agent-config:admin` | OAuth scope mode; `mcp:admin` also satisfies it | Agent configuration create/update/delete and credential-reference administration | admin-only |

The upstream Census API does not use OAuth for these datasets. Its required API key is a Vault-managed query parameter, not an OAuth access token or MCP scope. HTTP OAuth clients must request the provider scopes that their configured `SCOPE_MAP` maps to the exact MCP scopes above. Mutating callers use `mcp:write` or the applicable admin scope in scope mode; `MCP_ADMIN_AUTH_KEY` is the additional legacy admin gate in key mode.

With named providers, `REQUIRED_SCOPES` lists provider scopes that must be present in the introspected token. `SCOPE_MAP` maps those provider scopes to MCP scopes. For example:

```dotenv
MCP_HTTP_AUTH_MODE=oauth2
MCP_AUTHZ_MODE=auto
MCP_HTTP_OAUTH2_PROVIDERS=okta
MCP_HTTP_OAUTH2_OKTA_INTROSPECTION_URL=https://id.example.com/oauth2/default/v1/introspect
MCP_HTTP_OAUTH2_OKTA_CLIENT_ID=
MCP_HTTP_OAUTH2_OKTA_CLIENT_SECRET=
MCP_HTTP_OAUTH2_OKTA_REQUIRED_SCOPES=api.invoke
MCP_HTTP_OAUTH2_OKTA_SCOPE_MAP=api.invoke:mcp:invoke,api.read:mcp:read,api.write:mcp:write,api.admin:mcp:admin
```

In `auto` authorization mode, OAuth2 requests use scope authorization. `oauth-scopes` forces scope authorization; `admin-key` uses the legacy admin-key checks instead. A provider scope not included in `SCOPE_MAP` is not available as an MCP authorization scope. See [.env.example](.env.example) for additional provider settings.

Agent/A2A/schedules:

- `MCP_AGENT_WORKER_ENABLED`, `MCP_AGENT_MAX_GOAL_BYTES`, `MCP_AGENT_MAX_TASK_RUN_TIME_MS`
- `MCP_AGENT_SCHEDULE_RECONCILE_MS`, `MCP_AGENT_SCHEDULE_RETENTION_DAYS`
- `MCP_A2A_PATH`, `MCP_A2A_CARD_PATH`, `MCP_A2A_PUBLIC_URL`

See [.env.example](.env.example) for complete values.

## Deployment and TLS

[docker-compose.yml](docker-compose.yml) starts Raft-backed Vault (after `vault-unseal-key-init`), Postgres, MCP HTTP, and the dedicated agent worker. The default Compose publication is `127.0.0.1:3000` and the MCP process serves plaintext HTTP. This is suitable for loopback or an internal trusted-proxy topology only, never direct public exposure.

Native TLS remains available by setting `MCP_HTTP_TLS_ENABLED=true` and supplying external certificate/key paths (with the `certs/` mount available read-only for Compose). There is no generated, committed, or fallback production certificate/key. TLS startup fails if the requested externally provisioned files are absent or unreadable; it does not silently downgrade to HTTP.

### External Services Mode

Use [docker-compose.external.yml](docker-compose.external.yml) for an app-only deployment against existing Vault/Postgres. Set `VAULT_*` and `POSTGRES_*`, the same `MCP_SERVER_NAME`, and use one Postgres database for application and pg-boss state. Production Vault should use TLS and least-privilege AppRole/token policy rather than the development root token.

A trusted reverse proxy uses the default `MCP_HTTP_TLS_ENABLED=false` together with an explicitly configured `MCP_HTTP_TRUST_PROXY=true`; keep the app-to-proxy HTTP path internal. For native TLS, enable it explicitly and configure cert/key/passphrase/min-version settings. Rotation of native TLS material requires a process restart. Certificate provisioning, renewal, Vault Raft backup/restore, and Vault hardening are operator responsibilities documented in [vault-production/README.md](vault-production/README.md).

### Hosted MCP proxies

The standalone [Apify proxy](apify/DEPLOYMENT.md) and [MCPize proxy](mcpize/DEPLOYMENT.md) are alternatives. Both require a reachable HTTPS upstream and use a publisher-managed bearer token; neither refreshes that token. Local loopback is not reachable from the hosted platform, so use a trusted HTTPS reverse proxy or tunnel. Keep deployments private until verified.

By default all callers share the upstream token's principal. To enable per-caller scope:

1. Configure separate random `MCP_HTTP_APIFY_PROXY_TOKEN` and/or `MCP_HTTP_MCPIZE_PROXY_TOKEN` secrets on the upstream. Set the matching platform proxy's `UPSTREAM_PROXY_BOOTSTRAP_TOKEN`; never expose these secrets to callers.
2. Give the upstream bearer token `mcp:proxy:initialize` and any other strictly necessary scopes. In Vault-token mode the default HTTP admission also requires `mcp:invoke`; OAuth scope maps must include the provider's corresponding scopes.
3. Ensure the platform gateway authenticates callers and supplies trusted user IDs, strips any client-supplied identity headers, and cannot be bypassed. Each caller invokes `proxy_user_initialize` before other tools. This idempotently creates/verifies its principal under the fixed `apify` or `mcpize` tenant and accepts optional non-secret configuration.

Platform IDs are mapped to deterministic SHA-256-based principal IDs so distinct IDs cannot collide in normalized Census Vault paths. The returned principal ID is therefore not the raw platform user ID. Disabled tenants or principals are not re-enabled. Only enable this integration for trusted proxies: the publisher token's scopes are inherited by every caller. In particular, do not give marketplace users `mcp:admin` or an admin key merely to set Census credentials; use a separately authorized provisioning workflow. With bootstrap secrets unset, existing shared-principal behavior is unchanged.

## Agent and A2A

Agent configuration remains deployment-time MCP configuration:

1. Discover configuration/capability schema.
2. Provision inference credentials in scoped Vault storage.
3. Validate and save non-secret Postgres configuration.
4. Explicitly test the inference endpoint.
5. Submit a read-only verification goal and inspect task status.
6. Rotate credentials or delete config as needed.

The agent worker restores authenticated tenant/principal and scopes for tool calls, rechecks schedule grants, and persists LangGraph checkpoints. pg-boss dispatch and app records share one database so submission is transactional. Disabling a schedule does not cancel previously submitted tasks. A2A uses the same HTTP auth, origin/IP, body, and rate controls as MCP.

See [agent/playbooks/service-onboarding.md](agent/playbooks/service-onboarding.md) and [agent/templates/service-spec.md](agent/templates/service-spec.md).

## Security and persistence

- Secrets: Vault only.
- Non-secret configuration: Postgres only.
- Multi-user scope: tenant plus user/account principal on config, credentials, tasks, memory, schedules, and grants.
- API origin: adapter refuses non-`https://api.census.gov` origins.
- Output: secret-bearing values are redacted; raw Vault lifecycle tokens are disabled unless explicitly and admin-guarded.
- HTTP: bearer/OAuth auth, origins, IP allowlist, body limit, rate limit, TLS, bounded timeout.
- Reliability: no automatic retries for Census queries (safe to call again because query operations are read-only).
- Upstream Census API behavior, throttling, and API-key issuance remain Census-controlled.

## Tests and CI

Run:

```bash
npm run inventory:check
npm test
```

`tests/census-service.test.js` checks all 63 mappings, required API-key behavior, non-JSON upstream errors, redaction, scoped Vault paths, allowlisting, and read-only behavior. `tests/server.integration.test.js` covers generated tool registration, admin failures, redaction, and suggestions. Existing tests retain stdio/HTTP, the plaintext TLS-disabled default, opt-in native TLS validation and HTTPS behavior, OAuth, Vault token fallback/lifecycle, Vault Agent listener/both modes, agent/A2A, pg-boss, schedules, rotation, namespace collision, and production-Vault behavior.

Live Postgres agent/scheduling tests are opt-in with `MCP_AGENT_TEST_DATABASE_URL` and are reported as skipped when not configured. The base suite uses deterministic mocks/fixtures for Census and controlled scheduling.

[.github/workflows/inventory-and-tests.yml](.github/workflows/inventory-and-tests.yml) generates/checks inventory, uploads a repository artifact, installs with `npm ci`, and runs `npm test`.

Install the local pre-push guard with:

```bash
npm run hooks:install
```

It runs inventory and tests before a normal push.

## License and attribution

MIT licensed; see [LICENSE](LICENSE). Skeleton architecture, reusable package contracts, and deployment assets originate from `LesterAJohn/skeleton-mcp`. Census metadata and API behavior originate from the U.S. Census Bureau.