eurostat-sbs-mcp
by LesterAJohn
README.md
# eurostat-sbs-mcp
A complete Node.js MCP server for the public, read-only **Eurostat dissemination API**, with a Structural Business Statistics (SBS) focus — built on tenant/principal-scoped Vault/Postgres persistence, multi-provider OAuth authorization, and optional durable agent execution.
- **Service coverage:** dedicated MCP tools for all 30 documented Eurostat dissemination API operations (SDMX 2.1, SDMX 3.0, STATISTICS, CATALOGUE, ASYNC) plus SBS dataset discovery, grounded in the committed official OpenAPI snapshot ([inventory/COVERAGE.md](inventory/COVERAGE.md)).
- **MCP transports:** stdio and HTTP, with modern and legacy protocol compatibility.
- **Persistence:** Vault for secrets; MCP-namespaced Postgres tables for configuration, agent state, memories, schedules, and audit events.
- **Authorization:** multiple OAuth2 introspection providers and scope mapping; OAuth callers can use scopes instead of an admin key.
- **Agent capabilities:** LangGraph tool execution, Postgres checkpoints, scoped memories, declarative compositions, and an authenticated A2A JSON-RPC endpoint.
- **Durable automation:** pg-boss task dispatch, cron/one-shot schedules, revocable capability grants, and a dedicated supervised worker.
- **Reuse without a hidden framework:** small npm workspace contracts plus visible application bootstrap, adapters, tools, and deployment examples.
> The Eurostat dissemination API is public and requires no upstream credentials; every documented operation is read-only. Vault still protects this server's own secrets (HTTP bearer-token index, inference credentials) and Postgres stores all non-secret configuration.
## Provenance
- Built from the skeleton at <https://github.com/LesterAJohn/skeleton-mcp>, commit `bfbf26a6939a3c3c387a34bd2461f1bb5d0b8eec` (standalone repository; no git-level relationship to the skeleton).
- API grounding: official Eurostat consolidated OpenAPI specification snapshot in [inventory/openapi/sdmx-rest.yaml](inventory/openapi/sdmx-rest.yaml) — see [inventory/openapi/PROVENANCE.md](inventory/openapi/PROVENANCE.md) and the documentation snapshots in [API-DOCS.md](API-DOCS.md) and [docs/](docs/).
### Repository name versus MCP_SERVER_NAME
- `eurostat-sbs-mcp` (repository name) identifies this codebase on GitHub; it has no runtime meaning.
- `MCP_SERVER_NAME` (default `eurostat-sbs-mcp`) is the runtime server identity and the **single namespace source** for all application-owned persistence: Postgres tables/schemas (config, agent state, pg-boss, LangGraph checkpoints), Vault paths, queue names, and scheduling structures.
- Changing `MCP_SERVER_NAME` changes the persistence namespace: existing data stays under the old namespace and the server starts empty under the new one. Never rename it silently; plan an explicit migration (`npm run vault:migrate-namespace` plus the documented legacy `APP_NAME` Postgres copy) before changing it.
## Start Here
- [API coverage and reproducible inventory](#api-coverage-and-inventory)
- [Capabilities at a glance](#capabilities-at-a-glance)
- [Reference application and reusable packages](#reference-application-and-reusable-packages)
- [Architecture and process boundaries](#architecture)
- [Quick start](#quick-start), [external services](#external-services-mode), and [production deployment](#production-deployment)
- [Hosted MCP proxies](#hosted-mcp-proxies) for Apify and MCPize deployment
- [MCP client registration](#registering-the-mcp-server) and [tool catalog](#tool-catalog)
- [Connect Codex, Claude, and VS Code to the agent via A2A](#connect-codex-claude-and-vs-code-to-the-agent-via-a2a)
- [OAuth authorization and accepted scopes](#oauth-providers-and-authorization-capabilities)
- [LangGraph agent and A2A](#langgraph-agent-and-a2a) and [durable scheduling](#durable-agent-scheduling)
- [Environment variables](#environment-variables) and [test coverage](#test-coverage)
## Purpose
This repository exposes the Eurostat dissemination API — focused on Structural Business Statistics — through secure MCP tools, and provides:
- Multi-user support (tenant/principal identity on every scoped operation).
- Secret reads and writes through Vault (server-owned secrets only; the upstream API needs none).
- Config reads and writes through Postgres.
- Tool-level authorization for mutating operations (all mutations are server administration; the upstream API is read-only).
- Redacted tool output by default.
- Basic reliability controls: bounded retries, timeouts, and response size limits for upstream reads.
Design requirements:
- Secrets are persistent in Vault.
- Configuration is persistent in Postgres.
- Tenant-scoped behavior is mandatory, with tenant/user or tenant/account identity required where supported.
## API Coverage And Inventory
The Eurostat dissemination API is grounded in the committed official OpenAPI snapshot ([inventory/openapi/sdmx-rest.yaml](inventory/openapi/sdmx-rest.yaml)); all **30 documented operations are read-only public HTTP GETs covered by 23 dedicated `eurostat_*` tools** (optional-path-segment variants such as `/{version}` share one tool). There are no approved exclusions, callbacks, or deprecated operations.
| API family | Operations | Tools |
| --- | --- | --- |
| SDMX 2.1 data + structures | 9 | `eurostat_sdmx21_data`, `eurostat_sdmx21_dataflow`, `eurostat_sdmx21_datastructure`, `eurostat_sdmx21_codelist`, `eurostat_sdmx21_conceptscheme`, `eurostat_sdmx21_contentconstraint`, `eurostat_sdmx21_categoryscheme`, `eurostat_sdmx21_categorisation` |
| SDMX 3.0 data + structures | 12 | `eurostat_sdmx30_data`, `eurostat_sdmx30_dataflow`, `eurostat_sdmx30_dataconstraint`, `eurostat_sdmx30_datastructure`, `eurostat_sdmx30_conceptscheme`, `eurostat_sdmx30_codelist` |
| STATISTICS 1.0 (JSON-stat) | 1 | `eurostat_statistics_data` |
| CATALOGUE | 6 | `eurostat_catalogue_toc_txt`, `eurostat_catalogue_toc_xml`, `eurostat_catalogue_toc_schema`, `eurostat_catalogue_dcat`, `eurostat_catalogue_metabase`, `eurostat_catalogue_rss` |
| ASYNC 1.0 | 2 | `eurostat_async_status`, `eurostat_async_data` |
Convenience discovery (additive, does not replace endpoint coverage): `eurostat_sbs_datasets` filters the catalogue table of contents on SBS dataset code prefixes.
Reproducible inventory commands:
```bash
npm run inventory:generate # regenerate inventory/api-inventory.json + inventory/COVERAGE.md
npm run inventory:check # fail on stale output, missing/duplicate mappings, or uncovered operations
```
Both commands use only committed files (no live documentation downloads), keeping CI reproducible. The machine-readable inventory lives at [inventory/api-inventory.json](inventory/api-inventory.json) and the human-readable coverage report at [inventory/COVERAGE.md](inventory/COVERAGE.md).
Supported API servers: `main` (`https://ec.europa.eu/eurostat/api/dissemination`) and `comext` (`https://ec.europa.eu/eurostat/api/comext/dissemination`, for DS-prefixed Comext/Prodcom datasets). Every service tool accepts an optional `server` argument; destinations are validated and arbitrary hosts are rejected.
## Capabilities At A Glance
| Area | Included capabilities | Configuration / boundary |
| --- | --- | --- |
| Service integration | Eurostat dissemination API adapter, dedicated `eurostat_*` tools for every documented operation, SBS dataset discovery, generic read-only requests, endpoint discovery, connection metadata, and suggested tool workflows | Adapter: [src/services/eurostatService.js](src/services/eurostatService.js); endpoint mapping: [src/services/eurostatEndpoints.js](src/services/eurostatEndpoints.js); [tool registration](src/mcp/server.js). |
| MCP access | Stdio, HTTP `/mcp`, protocol-era negotiation, HTTP health checks, access logs, body/rate limits, and IP/origin restrictions | `npm run start:both` starts two transport processes; it does not start an agent worker. |
| OAuth and tool authorization | Named introspection providers, issuer/audience/scope checks, per-provider scope mapping, bounded expiry-aware token caches | `MCP_AUTHZ_MODE=auto` uses scopes for OAuth-authenticated callers and preserves key authorization for stdio/static/Vault-index-token callers. Explicit `admin-key` and `oauth-scopes` modes are available. |
| Data and secrets | Scoped config tools, Vault token seeding/lifecycle/sink inspection, rotation-interval resolution, and redacted outputs | `MCP_SERVER_NAME` derives Postgres/Vault namespaces; configuration is not a secret store. |
| Queue operations | pg-boss queue/job management, scheduling, lifecycle controls, and status tools | Generic `pgboss_*` operations are infrastructure tools, not automatically tenant-isolated application queues. |
| Optional agent | Revisioned config, OpenAI-compatible inference with Vault credentials, bounded tool execution, Postgres checkpoints, scoped memories, and learned declarative compositions | Requires an enabled principal-specific agent config and a running dedicated worker for durable tasks. |
| A2A | Authenticated JSON-RPC goal/task access at `/a2a`, with a public Agent Card at `/.well-known/agent-card.json` | Shares HTTP authentication and request controls; the card's availability does not mean inference is configured. |
| Durable agent schedules | Cron/timezone and future one-shot runs, history, manual triggers, overlap skipping, revocable owner/capability grants, and reconciliation | Schedule tools remain discoverable without enabled inference. Execution requires enabled config, active grant, and the supervised worker. |
| Reusable contracts | Namespace/scope/context/redaction primitives, worker prerequisite validation, and conformance assertions | Workspace packages do not replace the app's service clients, persistence implementations, tools, or agent engine. |
### What Changed In This Architecture
Inherited from the skeleton, this architecture goes beyond a Vault/Postgres-backed collection of API tools:
1. **A reference application plus reusable contracts:** common primitives are extracted into workspace packages while the complete integration remains visible in the root application.
2. **MCP-name-derived persistence:** configuration and agent data use versioned, namespaced Postgres objects; Vault paths use the MCP name prefix. Legacy `APP_NAME` is a migration source, not the current namespace setting.
3. **Durable execution separated from request handling:** MCP/A2A submit tasks; a dedicated pg-boss worker restores authority and runs LangGraph tools. Schedules create fresh tasks through transactional dispatch rather than running inference inside an HTTP request.
4. **OAuth scopes instead of per-call admin secrets:** verified OAuth callers use `mcp:write` for regular mutations and `mcp:admin` for administration in the default `auto` mode. Provider scope maps and durable authentication provenance keep this policy consistent across direct tools, compositions, and workers.
5. **Delegated administration instead of one global admin:** `mcp:tenancy:admin` manages tenants, tenant users/accounts, and token seeding, while `mcp:agent-config:admin` manages other users' agent configurations — each bounded to the caller's authenticated tenant or token-declared `allowedTenantIds`, with atomic actor/target audit records. `mcp:admin` remains the global compatibility super-scope.
## Reference Application And Reusable Packages
This repository remains a complete, executable model for an MCP server. The root application owns the visible bootstrap, Eurostat service adapter, tool registration, stdio and HTTP transports, Vault/Postgres wiring, LangGraph worker, A2A endpoint, deployment examples, and integration tests.
Stable service-independent contracts are also extracted into npm workspace packages so other MCP repositories can reuse tested behavior without copying it. These are local workspace dependencies in this repository; publishing to an npm registry is a separate release action, not implied by the package names.
| Package | Reusable contract | What remains visible in the root model |
| --- | --- | --- |
| `@fortisai/mcp-runtime` | namespace derivation, tenant/principal scope, authenticated context, redaction | service bootstrap, tools, transports, Vault/Postgres services |
| `@fortisai/mcp-agent-runtime` | explicit worker activation and queue/checkpoint/scheduling prerequisites | LangGraph engine, A2A handler, pg-boss worker, scheduling implementation |
| `@fortisai/mcp-conformance` | portable assertions for required package contracts | full protocol, security, persistence, and integration test suites |
The compatibility modules under `src/config`, `src/auth`, and `src/services` preserve the documented source layout for repositories derived from earlier skeleton revisions. New implementations may import the packages directly. This design deliberately avoids hiding the reference implementation behind a framework.
Run package and application validation together with:
```bash
npm test
```
Run them independently with `npm run test:packages` or `npm run test:app`.
## Architecture
```mermaid
flowchart TD
MCP[MCP clients] --> STDIO[Stdio process]
MCP --> HTTP[HTTP process: /mcp]
A2A[A2A clients] --> HTTP
HTTP --> AUTH[Static or Vault-index token / OAuth introspection]
AUTH --> TOOLS[Authenticated context and tool authorization]
STDIO --> TOOLS
TOOLS --> REGISTRY[MCP tools and executable registry]
REGISTRY --> API[Eurostat dissemination API]
REGISTRY --> PG[(Postgres: config, tasks, memories, schedules, grants)]
REGISTRY --> VAULT[(Vault: secrets and inference credentials)]
REGISTRY --> QUEUE[(pg-boss: task and schedule-trigger queues)]
QUEUE --> WORKER[Dedicated supervised worker]
WORKER --> GRANTS[Schedule reconciliation and grant checks]
GRANTS --> PG
WORKER --> ENGINE[LangGraph engine]
ENGINE --> PG
ENGINE --> VAULT
ENGINE --> MODEL[OpenAI-compatible inference endpoint]
ENGINE --> REGISTRY
```
### Process Boundaries
| Process | Entry point | Responsibility |
| --- | --- | --- |
| MCP stdio | [src/index.js](src/index.js), `npm run start:stdio` | Serve MCP tools using local/default principal context. The entry point also honors `MCP_TRANSPORT_MODE` for dispatch to HTTP/both. |
| MCP HTTP + A2A | [src/http/index.js](src/http/index.js), `npm run start:http` | Authenticate inbound bearer requests, establish verified identity/scopes, serve tools, and submit durable goals. Serve public health and Agent Card endpoints. |
| Combined transport launcher | [src/start-both.js](src/start-both.js), `npm run start:both` | Launch stdio and HTTP as separate child processes, not a worker or a single shared in-memory server. |
| Agent worker + scheduler | [src/agent/worker.js](src/agent/worker.js), `npm run start:agent-worker` | Require explicit worker enablement and pg-boss; consume task/trigger queues, supervise cron/maintenance, reconcile schedules/unqueued tasks, and drain on shutdown. |
The worker constructs its own instance of the same tool registry and services. Configure the server and worker with the same `MCP_SERVER_NAME`, authorization mode, Eurostat settings, Vault access, and application database. Agent task insertion/resume and pg-boss dispatch require the **same Postgres database** so they can commit atomically.
### Shared Services And Authority
- [src/config/env.js](src/config/env.js) validates environment settings; [src/services/runtime.js](src/services/runtime.js) wires Postgres, Vault, pg-boss, and the Eurostat service client.
- [packages/runtime](packages/runtime) supplies namespace, scope, authenticated-context, and redaction primitives. [src/services/configStore.js](src/services/configStore.js) implements the application's migrations and scoped persistence.
- [src/http/oauth2.js](src/http/oauth2.js) verifies provider access tokens; [src/auth/authorization.js](src/auth/authorization.js) selects scope/key authorization; [src/mcp/server.js](src/mcp/server.js) applies that policy to direct tool calls.
- [src/agent/toolRegistry.js](src/agent/toolRegistry.js) validates agent/composition inputs and limits runnable capabilities; [src/agent/engine.js](src/agent/engine.js) restores the task's tenant/principal, authentication method, and granted scopes before invoking tools.
- [src/services/vault.js](src/services/vault.js) resolves secrets and serializes/retries secret writes; [src/services/security.js](src/services/security.js) preserves redacted output behavior.
- [packages/agent-runtime](packages/agent-runtime) validates worker prerequisites; it does not contain the root application's LangGraph, A2A, or scheduling implementation.
For `MCP_SERVER_NAME=eurostat-sbs-mcp`, application tables use the `eurostat_sbs_mcp_` prefix, checkpoint and queue schemas are `eurostat_sbs_mcp_langgraph` and `eurostat_sbs_mcp_pgboss`, and Vault paths begin with `eurostat-sbs-mcp/`. Config, tasks, memories, schedules, and grants carry tenant/principal ownership; namespace separation alone is not a substitute for tool-level authorization.
Local infrastructure:
- [docker-compose.yml](docker-compose.yml) runs Postgres, Raft-backed Vault, the managed unseal-key helper, the MCP HTTP process, and the dedicated agent worker for local development.
- [docker-compose.external.yml](docker-compose.external.yml) runs the MCP HTTP process and dedicated agent worker against externally managed Postgres and Vault.
- [initdb/001_config.sh](initdb/001_config.sh) creates and seeds the MCP-namespaced tenant/principal-scoped config table.
### Operational Boundaries
- OAuth support is **access-token introspection**, not a login/authorization server, token issuer, or JWT/JWKS verifier. Opaque-token fallback may send a token to multiple configured providers; all must be trusted recipients.
- Agent inference supports **OpenAI-compatible endpoints only**, with credentials resolved from Vault. No inference endpoint or credential is supplied automatically.
- Durable schedules support minute-or-coarser five-field cron and future one-shot runs; missed occurrences use **skip**, not catch-up/backfill.
- Transactional dispatch and replay protection do **not** guarantee exactly-once external API side effects after a crash. Use idempotent service operations.
- Rate limits and verification caches are process-local. Production deployment requires appropriate TLS termination, credentials/policies, and any cross-instance controls; see [Production Deployment](#production-deployment).
## Hosted MCP Proxies
This repository contains two standalone, production-oriented HTTP proxies for
publishing an existing remote MCP server without moving the target server into
this server's Vault/Postgres architecture:
| Package | Platform behavior | Upstream OAuth | Billing |
| --- | --- | --- | --- |
| [apify/](apify) | Apify Server Actor with Streamable HTTP `/mcp` and Actor readiness on `/` | Publisher-managed bearer token stored as an Apify secret | Proxy calls Apify's charge API with custom PPE events selected from the called tool name |
| [mcpize/](mcpize) | MCPize container HTTP service with `/mcp` and `/health` | Publisher-managed bearer token stored with `mcpize secrets set` | MCPize gateway manages subscriptions/usage; optional x402 per-tool pricing belongs in `mcpize.yaml` |
Both proxies:
- require an absolute HTTPS upstream URL;
- replace the caller's platform authorization header with the configured
upstream OAuth bearer token;
- preserve MCP session, protocol-version, content-type, and streaming headers;
- reject redirects to prevent OAuth-token forwarding to another host;
- limit request size and use a bounded upstream timeout;
- keep token values out of committed files and process logs;
- remain isolated from the root Vault, Postgres, pg-boss, A2A, and agent worker;
- can opt into trusted per-caller scoping without exposing caller platform
authorization tokens.
For this upstream, set `MCP_HTTP_APIFY_PROXY_TOKEN` and/or
`MCP_HTTP_MCPIZE_PROXY_TOKEN` to independent random secrets. Configure the same
secret in the corresponding proxy as `UPSTREAM_PROXY_BOOTSTRAP_TOKEN`. The
proxy converts its platform-supplied caller ID into a trusted request identity.
The caller then invokes `proxy_user_initialize` once (it is idempotent) to
create/verify the `apify` or `mcpize` tenant, the caller principal, and any
optional non-secret Postgres configuration. A publisher OAuth token needs
`mcp:proxy:initialize`; later scoped calls use the initialized caller. With
these secrets unset, no proxy identity is interpreted and existing behavior is
unchanged.
Choose Apify when Actor-native PPE events and an Actor runtime are preferred.
Choose MCPize when gateway-managed subscriptions/usage, marketplace discovery,
or x402 per-tool billing is preferred. The proxies are alternatives, not
services that must be deployed together.
Detailed setup:
- [Apify proxy setup and deployment](apify/DEPLOYMENT.md)
- [MCPize proxy setup and deployment](mcpize/DEPLOYMENT.md)
Neither proxy performs an OAuth authorization-code or refresh-token flow.
Provision a valid access token externally and rotate it in the platform secret
store before expiry. Upstream credentials required by individual subscribers
need a separate identity/credential design and are not implemented by these
shared-token templates.
## Registering The MCP Server
This repository can be registered with MCP clients in either stdio mode or HTTP mode.
These registrations expose MCP tools, not an A2A connection. To delegate to the durable agent through `/a2a`, use the [A2A connection guide](#connect-codex-claude-and-vs-code-to-the-agent-via-a2a). Never configure `/a2a` as an MCP server URL.
For local development, stdio is the simplest option:
```json
{
"mcpServers": {
"eurostat-sbs-mcp": {
"command": "npm",
"args": ["run", "start:stdio"],
"cwd": "/absolute/path/to/eurostat-sbs-mcp"
}
}
}
```
For HTTP-capable clients, use `npm run start:http` and point the client at the `/mcp` endpoint.
### MCP Protocol Compatibility
The server uses MCP SDK v2 and serves both protocol eras over the same stdio connection or HTTP endpoint:
- The modern 2026-07-28 protocol is available over stdio and HTTP.
- Legacy 2024-2025 protocol clients remain supported over stdio and stateless Streamable HTTP at `/mcp`.
No separate endpoint or client configuration is needed. The SDK chooses the protocol era from the opening exchange. The legacy HTTP compatibility path is stateless, so it does not support legacy session-based GET/DELETE operations.
### Codex
Use stdio for Codex unless you specifically need HTTP. Add the server to your Codex MCP configuration using the local workspace path:
- Config file: `~/.codex/config.toml`
- Transport: stdio
```toml
[mcp_servers.eurostat-sbs-mcp]
command = "npm"
args = ["run", "start:stdio"]
cwd = "/absolute/path/to/eurostat-sbs-mcp"
```
For HTTP, start the HTTP process and use this entry **instead**:
```toml
[mcp_servers.eurostat-sbs-mcp]
url = "http://127.0.0.1:3000/mcp"
bearer_token_env_var = "MCP_ACCESS_TOKEN"
```
Supply `MCP_ACCESS_TOKEN` through the Codex process environment, not a committed file. This is MCP access to tools such as `agent_goal`; for actual A2A delegation, follow [Codex CLI / Codex in VS Code](#codex-cli--codex-in-vs-code).
### VS Code
For Copilot, run **MCP: Add Server** and select a command or HTTP endpoint. Current Copilot harness configurations use a top-level `mcpServers` object in workspace-root `.mcp.json` or a personal Copilot MCP configuration:
```json
{
"mcpServers": {
"eurostat-sbs-mcp": {
"type": "http",
"url": "http://127.0.0.1:3000/mcp",
"headers": {
"Authorization": "Bearer ${MCP_ACCESS_TOKEN}"
}
}
}
}
```
Start the HTTP process, make the token available to the Copilot runtime, review server trust, and enable its tools. Older editor-managed setups use `.vscode/mcp.json` with a top-level `servers` object; use the format appropriate to your selected harness rather than mixing the two. See the [VS Code configuration reference](https://code.visualstudio.com/docs/agents/reference/mcp-configuration). For direct A2A rather than MCP tools, follow [VS Code Copilot agent mode](#vs-code-copilot-agent-mode).
### Claude
For Claude Desktop, use stdio and add an MCP server entry that launches the process from this repository:
- Config file: `~/Library/Application Support/Claude/claude_desktop_config.json`
- Transport: stdio
```json
{
"mcpServers": {
"eurostat-sbs-mcp": {
"command": "npm",
"args": ["run", "start:stdio"],
"cwd": "/absolute/path/to/eurostat-sbs-mcp"
}
}
}
```
If you are using a Claude setup that supports MCP over HTTP, point it at `http://127.0.0.1:3000/mcp`.
Claude Code can register an HTTP MCP server with `claude mcp add --transport http eurostat-sbs-mcp http://127.0.0.1:3000/mcp`; configure its bearer credentials privately as described in the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp). This is still MCP, not A2A. See [Claude Code / Claude Desktop](#claude-code--claude-desktop) for the A2A route and Desktop limitations.
## Connect Codex, Claude, And VS Code To The Agent Via A2A
This server is the **remote agent**; Codex, Claude, or Copilot is the calling assistant. A2A submits a goal to the server's configured LangGraph agent and returns a durable task. It does not replace the client's chat model, synchronize chat history, or give the remote agent arbitrary access to your editor/workspace.
> **Note — A2A communication is asynchronous only.** A2A clients never communicate synchronously with the LangGraph engine. A goal submission to `/a2a` inserts a durable task and enqueues a pg-boss job in one Postgres transaction, then returns a submission acknowledgment; status and results are retrieved through subsequent `/a2a` task queries. Execution happens later in the dedicated agent worker, the only process that runs LangGraph. If the worker is not running, goals are accepted and queued but never executed.
>
> **How clients learn the retrieval contract:** there is no in-band "fetch your result here" instruction; the contract is conveyed by protocol and tool metadata. The Agent Card advertises `streaming: true`, `pushNotifications: false`, and `stateTransitionHistory: true`, so A2A clients either poll `GetTask` with the returned task id or omit `configuration.returnImmediately` to stream status updates on the submission call (bounded server-side wait); webhooks are not available. MCP callers see `agent_goal` described as asynchronous; it returns `202` with the submitted task plus a `nextAction` hint directing them to poll `agent_task_status`.
| Connection | Endpoint | What it provides |
| --- | --- | --- |
| MCP registration | `/mcp` | Tools, including `agent_goal` and task tools. Calling those agent tools is a supported alternative, but is not A2A transport. |
| A2A discovery | `/.well-known/agent-card.json` | Public Agent Card describing the JSON-RPC binding and endpoint. |
| A2A delegation | `/a2a` | Authenticated A2A 1.0 JSON-RPC messages, task status, and cancellation. |
The MCP configuration formats above do **not** make a client an A2A client. For Codex CLI, Claude Code, and VS Code Copilot with approved terminal/HTTP execution, the practical direct route is to call the A2A endpoint using the request flow below. A native A2A integration, if available in your client/version, must support this card's **A2A 1.0 JSON-RPC** binding; do not assume an A2A 0.3 client using `message/send` is compatible. This repository does not ship a client extension or an MCP-to-A2A bridge.
### Prepare The Remote Agent
1. Complete [infrastructure setup](#quick-start): initialize/unseal Vault and configure Postgres and valid Vault credentials. The Eurostat API itself needs no credentials.
2. Set `MCP_AGENT_WORKER_ENABLED=true` for both server and worker, configure HTTP bearer authentication, and start **both** processes:
```bash
# Terminal 1
npm run start:http
# Terminal 2, using the same namespace/database/authorization settings
npm run start:agent-worker
```
3. Store the inference credential in Vault and use the [agent configuration tools](#langgraph-agent-and-a2a) to create an enabled config for the calling token's tenant/principal. Set `permittedCapabilities` to the required registered tools (for the example below, include `service_health_check`). The server and worker must share the same application/pg-boss database. Config administration requires OAuth `mcp:admin` in scope mode or the configured admin key in key mode.
4. Give the caller a valid access token. OAuth or Vault-index identities need `mcp:invoke` or `mcp:agent` for A2A admission; add `mcp:write` for ordinary mutating capabilities or `mcp:admin` for admin capabilities. Legacy key-authorized agent mutations additionally require `mcp:admin` when an admin key is configured. A2A requests do not pass an `authorizationKey` argument. Static tokens without identity metadata use the default principal, so prefer a verified scoped identity for multi-user access.
5. For remote deployment, set `MCP_A2A_PUBLIC_URL=https://your-agent.example/a2a` so the card advertises the reachable endpoint, and terminate TLS at a trusted proxy or natively via `MCP_HTTP_TLS_ENABLED=true` (see [HTTPS Deployment Choice](#https-deployment-choice)). Configure allowed hosts/origins/IPs as needed. Local plain HTTP examples below are for loopback development.
### Discover, Submit, Check, And Cancel
Run these Bash commands in a trusted terminal. Load a short-lived access token without placing it literally in shell history or chat:
```bash
export A2A_BASE_URL="http://127.0.0.1:3000"
read -r -s -p "A2A access token: " A2A_TOKEN
printf '\n'
export A2A_TOKEN
# Public discovery; honor MCP_A2A_CARD_PATH if changed.
curl --fail-with-body --silent --show-error \
"$A2A_BASE_URL/.well-known/agent-card.json"
```
Inspect `supportedInterfaces` for the JSON-RPC endpoint. The examples use the default `/a2a`; change the URL if `MCP_A2A_PATH` or the public deployment path differs. The card is public, so fetching it alone does not verify authentication or inference readiness.
Submit a read-only goal:
```bash
curl --fail-with-body --silent --show-error "$A2A_BASE_URL/a2a" \
-H "Authorization: Bearer $A2A_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"jsonrpc": "2.0",
"id": "submit-1",
"method": "SendMessage",
"params": {
"message": {
"messageId": "health-message-1",
"role": "ROLE_USER",
"parts": [{"text": "Check the Eurostat dissemination API health using service_health_check."}]
},
"configuration": {"returnImmediately": true},
"metadata": {"idempotencyKey": "health-request-1"}
}
}'
```
This version returns the task under `result.task`, including `result.task.id`, `contextId`, and a status such as `TASK_STATE_SUBMITTED`. Save that ID; a submitted response is not a completed result. Reuse the same `idempotencyKey` only when retrying the same submission; use fresh message/request identifiers and a fresh key for a new goal.
Set `A2A_TASK_ID` to the returned `result.task.id`, then poll status using the **same authenticated tenant/principal**:
```bash
export A2A_TASK_ID="<returned-task-id>"
curl --fail-with-body --silent --show-error "$A2A_BASE_URL/a2a" \
-H "Authorization: Bearer $A2A_TOKEN" \
-H "Content-Type: application/json" \
--data "{\"jsonrpc\":\"2.0\",\"id\":\"status-1\",\"method\":\"GetTask\",\"params\":{\"id\":\"$A2A_TASK_ID\"}}"
```
`GetTask` returns the task directly under `result`, not `result.task`. Check `result.status.state`; completed output is in its artifacts/history. Poll at a modest interval (for example 2 seconds) and respect HTTP rate limits. Terminal states include `TASK_STATE_COMPLETED`, `TASK_STATE_FAILED`, and `TASK_STATE_CANCELED`; report failure/cancellation rather than treating every terminal state as success.
To cancel an owned task:
```bash
curl --fail-with-body --silent --show-error "$A2A_BASE_URL/a2a" \
-H "Authorization: Bearer $A2A_TOKEN" \
-H "Content-Type: application/json" \
--data "{\"jsonrpc\":\"2.0\",\"id\":\"cancel-1\",\"method\":\"CancelTask\",\"params\":{\"id\":\"$A2A_TASK_ID\"}}"
# When finished with this terminal session:
unset A2A_TOKEN
```
Inspect the JSON-RPC `error` field even when HTTP returns `200`. Avoid `curl -v`, shell tracing (`set -x`), or logging expanded authorization headers. Obtain/refresh OAuth tokens through your provider; this server does not implement a login or token-issuance flow.
### Codex CLI / Codex In VS Code
1. Prepare the remote agent and verify discovery/submission in the terminal above.
2. For Codex CLI, launch `codex` from the shell containing `A2A_BASE_URL` and `A2A_TOKEN`. For the Codex IDE integration, ensure its actual execution environment can reach the endpoint and obtain the token privately; an export in an unrelated terminal is not sufficient.
3. Approve only the required network/command access and give Codex this instruction:
```text
Delegate a read-only service-health goal to the server via A2A, not MCP.
Use A2A_BASE_URL and A2A_TOKEN from the execution environment without printing
the token. Fetch the Agent Card, use its A2A 1.0 JSON-RPC endpoint, send
SendMessage with returnImmediately=true and a fresh idempotency key, save
result.task.id, and poll GetTask to a terminal state. Summarize the result.
Ask for approval before any mutating goal.
```
4. Verify that Codex used `/a2a` and returned a task ID and terminal result. Adding `[mcp_servers...]` in Codex config only connects MCP; it does not attach A2A. If the execution environment cannot access the token or endpoint, run the commands yourself rather than pasting credentials into chat.
### Claude Code / Claude Desktop
1. For **Claude Code**, launch `claude` from the prepared shell so approved terminal commands can inherit `A2A_BASE_URL` and `A2A_TOKEN`.
2. Use the same delegation instruction above and approve the endpoint/terminal access as appropriate. Confirm `SendMessage` and `GetTask` calls, not just an Agent Card fetch or an MCP `agent_goal` call.
3. For **Claude Desktop**, the `claude_desktop_config.json` entry registers MCP only. It cannot turn `/a2a` into an MCP server. If Desktop has no approved A2A/HTTP tool integration, use this server's MCP `agent_goal`/task tools instead, or install an independently reviewed MCP-to-A2A bridge. A bridge must preserve bearer identity, task ownership, error handling, and the A2A version; none is included here.
### VS Code Copilot Agent Mode
1. Select the Copilot agent experience with approved terminal execution, and open a workspace where you can run the request flow. Configure the token in the **actual tool execution environment** using your approved secret mechanism; the environment of an arbitrary integrated terminal is not automatically inherited by Copilot.
2. Use the delegation instruction above. Review command/network approvals, restrict the goal to permitted capabilities, and verify a task ID followed by a terminal status/result.
3. If the selected harness cannot reach the endpoint or read the token securely, execute the requests yourself in the prepared terminal. `.vscode/mcp.json` or `.mcp.json` entries are MCP registrations, not native A2A attachment.
4. If you want ordinary tool integration rather than direct A2A, register `/mcp` through **MCP: Add Server**, enable the agent tools, and call `agent_goal` / `agent_task_status` / `agent_task_cancel`. This reaches the same durable agent through MCP, not A2A.
### A2A Connection Troubleshooting
- **Card loads, goal fails:** the public card does not prove credentials, worker readiness, or an enabled principal-specific agent config.
- **HTTP `401`:** missing, inactive, expired, wrong-audience, or otherwise invalid bearer credentials. Check the configured verifier/provider.
- **JSON-RPC scope denial:** use `mcp:invoke` or `mcp:agent`; `mcp:admin` alone does not satisfy A2A admission.
- **Task stays submitted:** verify the dedicated worker is running with matching namespace/database and inspect its logs. Starting HTTP or `start:both` does not start the worker.
- **Task fails during execution:** inspect task status and worker logs for inference credentials, endpoint/config validation, permitted capabilities, or mutation-scope failures.
- **Cannot find another session's task:** use the original authenticated tenant/principal; changing credentials to a different owner does not transfer task access.
- **Protocol/method errors:** use the Agent Card's JSON-RPC version and this server's `SendMessage`, `GetTask`, and `CancelTask` methods, not an older client's method names.
Client integration references: [Codex MCP](https://developers.openai.com/codex/mcp), [Claude Code MCP](https://code.claude.com/docs/en/mcp), and [VS Code MCP](https://code.visualstudio.com/docs/agents/reference/mcp-configuration). These describe MCP configuration; the A2A wire examples above are grounded in this repository's [A2A adapter](src/agent/a2a.js) and [protocol tests](tests/agent.test.js).
## Tool Catalog
All tools return MCP text content containing JSON. Success payloads follow this shape:
```json
{
"ok": true,
"status": 200,
"data": {}
}
```
Errors follow this shape and set MCP `isError=true`:
```json
{
"ok": false,
"status": 401,
"error": "Unauthorized: invalid authorizationKey for mutating API operation"
}
```
With the default `MCP_AUTHZ_MODE=auto`, verified OAuth callers authorize mutations using `mcp:write` or `mcp:admin`; admin-only capabilities require `mcp:admin`. Other callers require `authorizationKey` when `MCP_ADMIN_AUTH_KEY` is configured. See [OAuth providers and authorization capabilities](#oauth-providers-and-authorization-capabilities).
### Configure the admin key
`MCP_ADMIN_AUTH_KEY` is not generated automatically. Generate a random value locally:
```bash
openssl rand -hex 32
```
Set the generated value in your local `.env` or deployment secret/environment configuration:
```dotenv
MCP_ADMIN_AUTH_KEY=<generated-value>
```
Restart the MCP server and agent worker processes after setting or rotating the key. For Docker Compose, recreate the containers so they receive the updated environment; a container restart alone does not update environment variables. Both Compose manifests pass this setting to the server and worker. OAuth scope authorization does not require this key or the `authorizationKey` argument.
Pass the same value as the `authorizationKey` argument to protected tools, for example:
```json
{
"name": "agent_schedule_grant_create",
"arguments": {
"capabilities": ["service_health_check"],
"scopes": ["mcp:invoke"],
"authorizationKey": "<generated-value>"
}
}
```
Without a configured key, agent configuration mutations, schedule mutations, and other admin-only operations are disabled; ordinary read-only tools remain available. This key is separate from the HTTP bearer token: HTTP clients still need transport authentication, and protected tool calls additionally require `authorizationKey`.
Treat the key as a secret. Do not commit it, put it in goals or memory, or share it in logs. To rotate it, generate a replacement, update all server/worker environments and authorized callers, and restart or recreate the affected processes.
### service_query_suggestion
- Category: advisory (read-only)
- Risk: low
- Use when: you want schema discovery for all MCP tools and recommendations on what tool sequence to run for an intent/workflow
- Do not use when: you already know the exact specialized tool and validated endpoint path
- Required permissions/prerequisites: none
- Environment behavior:
- Detects whether a workflow is mutating from `operationType` or `method`
- Reports the caller's effective authorization mode and whether `authorizationKey` is required for the suggested mutating call
- Parameters:
- `intent` (optional string)
- `operationType` (optional enum: `discover|read|mutate|data|structure|catalogue|async|scoped`)
- `method` (optional string, normalized to uppercase)
- `path` (optional string, normalized to leading slash)
- `includeExamples` (optional boolean, default `true`)
- `includeToolSchemas` (optional boolean, default `true`)
- Expected response shape:
- `data.summary`: intent + mutating/auth flags
- `data.recommendedOrder`: ordered tool recommendations with reasons
- `data.safetyChecks`: checklist for safer execution
- `data.toolSchemas`: schema-like catalog for all operational tools (unless disabled)
- `data.examples`: baseline read/mutate examples (unless disabled)
- Common failures:
- `500` for unexpected internal recommendation errors
- Recommended tools:
- Prerequisite: none
- Follow-up: any tool listed in `data.recommendedOrder`
- Example:
```json
{
"name": "service_query_suggestion",
"arguments": {
"intent": "discover SBS datasets and read enterprise statistics for France",
"operationType": "data",
"method": "GET",
"path": "/statistics/1.0/data/sbs_ovw_act"
}
}
```
#### Recommended Playbooks
| Intent | Suggested tool sequence | Notes |
| --- | --- | --- |
| Verify runtime and service connectivity | `service_connection_info` -> `service_health_check` | Baseline check before any operational request. |
| Discover SBS datasets | `service_connection_info` -> `service_health_check` -> `eurostat_sbs_datasets` | Filters the catalogue table of contents on SBS code prefixes. |
| Learn a dataset's dimensions and values | `eurostat_sdmx21_datastructure` -> `eurostat_sdmx21_codelist` -> `eurostat_sdmx21_contentconstraint` | Resolve the DSD, code lists, and valid dimension values before querying data. |
| Read focused data (JSON-stat) | `eurostat_sbs_datasets` -> `eurostat_statistics_data` | Use dimension `filters` (e.g. `geo`, `time`, `nace_r2`) to keep responses small. |
| Bulk/key-based extraction (SDMX 2.1) | `eurostat_sdmx21_datastructure` -> `eurostat_sdmx21_data` | Use `key`, `startPeriod`/`endPeriod`, or `lastNObservations` to bound the response. |
| SDMX 3.0 extraction with component filters | `eurostat_sdmx30_datastructure` -> `eurostat_sdmx30_data` | Use `c` filters such as `{"TIME_PERIOD": "ge:2020"}`. |
| Asynchronous bulk download | `eurostat_async_status` -> `eurostat_async_data` | For extractions too large for synchronous responses. |
| Execute a generic read request | `service_connection_info` -> `service_health_check` -> `service_list_endpoints` -> `service_api_request` (`GET`) | The upstream API is read-only; mutating methods are rejected. |
| Inspect tenant/principal scope metadata | `service_connection_info` -> `service_scope_info` | Use scope details for tenant/user or tenant/account-aware workflows. |
### service_connection_info
- Category: read-only
- Risk: low
- Use when: you need runtime MCP + Eurostat connection metadata (server name/version, auth-gate status, scope model, base URLs, timeout, size limits)
- Do not use when: you need health verification or endpoint discovery; prefer `service_health_check` or `service_list_endpoints`
- Required permissions/prerequisites: none
- Environment behavior: reports current process config (`MCP_SERVER_NAME`, default tenant/user/account scope, admin-auth configured state, and `MCP_AUTHZ_MODE`) plus the caller's effective scope/key authorization mode
- Parameters: none
- Expected response shape:
- `data.server`: server metadata, `scopeModel`, configured `authzMode`, effective `authorizationMode`, and `adminAuthConfigured`
- `data.service`: service client connection info
- Common failures:
- `500` if service client metadata retrieval fails
- Recommended tools:
- Prerequisite: none
- Follow-up: `service_health_check`, `service_list_endpoints`
- Example:
```json
{
"name": "service_connection_info",
"arguments": {}
}
```
### service_scope_info
- Category: read-only
- Risk: low
- Use when: you need tenant/principal scoping details used for Postgres and Vault paths before making scoped calls
- Do not use when: you only need default scope metadata; `service_connection_info` already includes default scope model
- Required permissions/prerequisites: none
- Environment behavior: requires `tenantId` plus exactly one of `userId` or `accountId`
- Parameters:
- `tenantId` (required string, non-empty)
- `userId` (optional string, non-empty)
- `accountId` (optional string, non-empty)
- Expected response shape:
- `data.appName`
- `data.tenantId`
- `data.tenantIdPathSegment`
- `data.principalType`
- `data.principalId`
- `data.principalIdPathSegment`
- `data.userId` or `data.accountId`
- `data.postgres.tableName`, `data.postgres.primaryKey`, `data.postgres.scope`
- `data.vault.tokenIndexPath`, `data.vault.scope`
- Common failures:
- `500` for unexpected normalization/path construction errors
- Recommended tools:
- Prerequisite: none
- Follow-up: `service_api_request` (for scoped API calls)
- Example:
```json
{
"name": "service_scope_info",
"arguments": {
"tenantId": "tenant-a",
"userId": "default"
}
}
```
### service_list_endpoints
- Category: read-only
- Risk: low
- Use when: you want a safe discovery list of implemented/documented target endpoints
- Do not use when: you need endpoint liveness; use `service_health_check`
- Required permissions/prerequisites: none
- Environment behavior: output depends on service adapter implementation bundled with current build
- Parameters: none
- Expected response shape:
- `data.endpoints`: adapter-provided endpoint list
- Common failures:
- `500` if endpoint catalog cannot be produced
- Recommended tools:
- Prerequisite: `service_connection_info`
- Follow-up: `service_api_request`, `service_health_check`
- Example:
```json
{
"name": "service_list_endpoints",
"arguments": {}
}
```
### service_health_check
- Category: read-only
- Risk: low
- Use when: you need reachability/health validation before operational calls
- Do not use when: you need to retrieve business data; use specific service tools
- Required permissions/prerequisites: outbound network path to ec.europa.eu must be available
- Environment behavior: uses configured service base URL and auth mode from runtime env
- Parameters: none
- Expected response shape:
- `data`: adapter-specific health payload
- Common failures:
- `5xx` if the Eurostat API is down/unreachable
- `429` when the upstream temporarily rate limits
- Recommended tools:
- Prerequisite: `service_connection_info`
- Follow-up: `service_list_endpoints`, `service_api_request`
- Example:
```json
{
"name": "service_health_check",
"arguments": {}
}
```
### Eurostat Service Tools
All `eurostat_*` tools are **read-only**, **idempotent**, and require **no upstream credentials or `authorizationKey`** — the Eurostat dissemination API is public. HTTP callers still need transport authentication (bearer token or OAuth with `mcp:invoke`/`mcp:read`). Shared behavior:
- Every tool accepts an optional `server` argument (`main` default, `comext` for DS-prefixed Comext/Prodcom datasets); destinations are restricted to the two validated base URLs.
- Requests use bounded retries with exponential backoff for `429/5xx` (honoring `Retry-After`), an `EUROSTAT_TIMEOUT_MS` timeout, and an `EUROSTAT_MAX_RESPONSE_BYTES` response size limit. Oversized responses fail with `413` and guidance to narrow the query or use the asynchronous API.
- Common failures: `400` invalid dataset/dimension codes, `404` unknown dataset/artefact, `413` response too large (narrow filters or use async tools), `429` upstream rate limiting (retried, then surfaced), `500/503` upstream outage (retried, then surfaced), `504` timeout.
- Expected response shape: `data.status`, `data.url`, `data.contentType`, `data.bytes`, and `data.data` (parsed JSON for JSON responses, text for XML/TSV/CSV).
Data-selection guidance: start with `eurostat_sbs_datasets` to find SBS dataset codes, inspect structure with `eurostat_sdmx21_datastructure`/`eurostat_sdmx21_codelist`, then read data with `eurostat_statistics_data` (focused JSON-stat) or `eurostat_sdmx21_data`/`eurostat_sdmx30_data` (bulk/key-based).
#### eurostat_statistics_data
- Operation: `GET /statistics/1.0/data/{datasetCode}` (STATISTICS 1.0, JSON-stat 2.0)
- Use when: you want focused observations with simple dimension filters — the best default for SBS data reads
- Avoid when: you need bulk extraction or non-JSON formats; use the SDMX data tools
- Parameters: `datasetCode` (required, e.g. `sbs_ovw_act`), `lang` (`en|fr|de`), `format` (`JSON`), `filters` (object of dimension code -> value or value list, e.g. `{"geo": "FR", "time": ["2020", "2021"]}`), `sinceTimePeriod`, `untilTimePeriod`, `lastTimePeriod` (integer), `server`
- Example:
```json
{
"name": "eurostat_statistics_data",
"arguments": {
"datasetCode": "<sbs-dataset-code>",
"lang": "en",
"filters": { "geo": "<geo-code>", "time": "<year>" }
}
}
```
#### eurostat_sdmx21_data
- Operation: `GET /sdmx/2.1/data/{flow}/{key}` (SDMX 2.1)
- Use when: you need key-based series selection, period bounds, or TSV/SDMX-CSV output
- Parameters: `flow` (required dataset code), `key` (series key, default `all`), `startPeriod`, `endPeriod`, `firstNObservations`, `lastNObservations`, `dimensionAtObservation`, `detail` (`full|dataonly|serieskeysonly|nodata`), `format` (`TSV|SDMX-CSV|JSON`; documented in the official detailed guidelines), `server`
- Warning: unfiltered full-dataset requests can be very large; bound the query or use the async tools
- Example:
```json
{
"name": "eurostat_sdmx21_data",
"arguments": {
"flow": "<sbs-dataset-code>",
"key": "<A.CODE1.CODE2>",
"startPeriod": "<year>",
"format": "JSON"
}
}
```
#### SDMX 2.1 structure tools
`eurostat_sdmx21_dataflow`, `eurostat_sdmx21_datastructure`, `eurostat_sdmx21_codelist`, `eurostat_sdmx21_conceptscheme`, `eurostat_sdmx21_contentconstraint`, `eurostat_sdmx21_categoryscheme`, `eurostat_sdmx21_categorisation`
- Operation: `GET /sdmx/2.1/{structureType}/{agencyID}/{resourceID}/{version}` (SDMX 2.1)
- Use when: discovering datasets (`dataflow`), dimensions (`datastructure`), valid codes (`codelist`, `contentconstraint`), concepts, or the navigation tree (`categoryscheme`, `categorisation`)
- Parameters: `resourceID` (required; `all` supported), `agencyID` (default `ESTAT`; `all` supported), `version` (default `latest`; `all` supported), `references` (`none|parents|parentsandsiblings|children|descendants|all`), `detail` (`allstubs|referencestubs|referencepartial|allcompletestubs|referencecompletestubs|full`), `server`
- Example:
```json
{
"name": "eurostat_sdmx21_datastructure",
"arguments": { "resourceID": "<dataset-code>", "references": "children" }
}
```
#### eurostat_sdmx30_data
- Operation: `GET /sdmx/3.0/data/dataflow/{agencyID}/{resourceID}/{version}[/{key}]` (SDMX 3.0; both path variants)
- Use when: you want SDMX 3.0 component filters (`c`) or SDMX-CSV 2.0 output
- Parameters: `resourceID` (required), `agencyID` (default `ESTAT`), `version` (default `+` latest), `key` (optional; `*` wildcards), `c` (object of component -> filter expression, e.g. `{"TIME_PERIOD": "ge:2020+le:2022"}`), `attributes` (`dsd|series|obs|all|none`), `measures` (`all|none`), `format` (`structurespecificdata|csvdata`), `formatVersion` (`2.0|3.0`), `lang`, `labels` (`id|name|both`, SDMX-CSV only), `compress` (`true|false`), `server`
- Example:
```json
{
"name": "eurostat_sdmx30_data",
"arguments": {
"resourceID": "<sbs-dataset-code>",
"c": { "TIME_PERIOD": "ge:<year>", "geo": "<geo-code>" }
}
}
```
#### SDMX 3.0 structure tools
`eurostat_sdmx30_dataflow`, `eurostat_sdmx30_datastructure`, `eurostat_sdmx30_codelist`, `eurostat_sdmx30_conceptscheme`, `eurostat_sdmx30_dataconstraint`
- Operation: `GET /sdmx/3.0/structure/{structureType}/{agencyID}/{resourceID}[/{version}]` (SDMX 3.0; both path variants — omit `version` for the latest)
- Parameters: `resourceID` (required), `agencyID` (default `ESTAT`), `version` (optional), `references` (allowed values depend on the structure type; see [inventory/openapi/sdmx-rest.yaml](inventory/openapi/sdmx-rest.yaml)), `detail`, `format` (`structure`), `formatVersion` (`3.0`), `compress`, `server`
- Example:
```json
{
"name": "eurostat_sdmx30_codelist",
"arguments": { "resourceID": "<codelist-id>" }
}
```
#### eurostat_async_status and eurostat_async_data
- Operations: `GET /1.0/async/status/{uuid}` and `GET /1.0/async/data/{uuid}` (ASYNC 1.0)
- Use when: a large extraction was submitted asynchronously and returned a UUID; poll status until available, then download
- Parameters: `uuid` (required, UUID format), `server`
- Common failures: `404` unknown/expired UUID; downloading before completion returns a not-ready status
- Example:
```json
{
"name": "eurostat_async_status",
"arguments": { "uuid": "<extraction-uuid>" }
}
```
#### Catalogue tools
- `eurostat_catalogue_toc_txt` — `GET /catalogue/toc/txt` (`lang`: `en|fr|de`): tab-separated table of contents of all datasets.
- `eurostat_catalogue_toc_xml` — `GET /catalogue/toc/xml`: XML table of contents.
- `eurostat_catalogue_toc_schema` — `GET /catalogue/toc/TableOfContent.xsd`: XSD of the TOC format (also used by `service_health_check`).
- `eurostat_catalogue_dcat` — `GET /catalogue/dcat/{agencyID}[/{extractionType}]` (`extractionType`: `FULL|UPDATES`): DCAT-AP catalogue.
- `eurostat_catalogue_rss` — `GET /catalogue/rss/{language}/statistics-update.rss` (`language`: `en|fr|de`): dataset-update feed.
- `eurostat_catalogue_metabase` — `GET /catalogue/metabase.txt.gz`: gunzipped metabase of every dataset/dimension/value combination. **Warning: very large; may exceed the configured response size limit.**
#### eurostat_sbs_datasets
- Category: read-only convenience discovery (builds on `GET /catalogue/toc/txt`; does not replace endpoint coverage)
- Use when: you want Structural Business Statistics dataset codes and titles without scanning the full catalogue
- Parameters: `lang` (`en|fr|de`, default `en`), `prefixes` (dataset code prefixes, default `["sbs"]`), `limit` (max rows, default 500)
- Expected response shape: `data.datasets` (TOC records), `data.count`, `data.truncated`
- Example:
```json
{
"name": "eurostat_sbs_datasets",
"arguments": { "lang": "en", "prefixes": ["sbs"] }
}
```
### service_api_request
- Category: read-only (the upstream API is read-only; mutating methods are rejected with `405`)
- Risk: medium
- Use when: you need flexible access to documented Eurostat dissemination API operations without a dedicated argument shape
- Do not use when: a dedicated `eurostat_*` tool exists, because those provide validated parameters and clearer intent
- Required permissions/prerequisites:
- Only `GET` and `HEAD` reach the upstream API; `POST|PUT|PATCH|DELETE` additionally require `mcp:write`/`mcp:admin` (OAuth) or `authorizationKey` (key mode) before being rejected by the read-only adapter — defense in depth, not an invitation to mutate
- `path` must target a documented dissemination API route (see `service_list_endpoints`)
- Environment behavior:
- `method` is normalized to uppercase and `path` to leading-slash form
- Requests always target the validated `main` or `comext` base URL; arbitrary hosts are rejected
- Parameters:
- `method` (required string; `GET` or `HEAD`)
- `path` (required string; `/`-prefixed normalization applied)
- `query` (optional object: string keys, scalar values string|number|boolean)
- `headers` (optional object: string keys and string values)
- `server` (optional enum `main|comext`)
- `authorizationKey` (only relevant for mutating methods, which the upstream rejects anyway)
- Expected response shape:
- `data`: adapter HTTP response payload (`status`, `url`, `contentType`, `bytes`, `data`)
- Common failures:
- `400` invalid path/query for the upstream API
- `404` endpoint/resource not found
- `405` mutating method rejected (upstream API is read-only)
- `413` response exceeds the configured size limit
- `429` upstream rate limiting
- `5xx`/`504` upstream or transport failure
- Recommended tools:
- Prerequisite: `service_list_endpoints`, `service_health_check`
- Follow-up: dedicated `eurostat_*` tools for validated reads
- Example:
```json
{
"name": "service_api_request",
"arguments": {
"method": "GET",
"path": "/catalogue/toc/txt",
"query": { "lang": "en" }
}
}
```
### pg-boss Queue And Scheduling Tools
This server embeds [pg-boss](https://github.com/timgit/pg-boss) (Postgres-backed job queue and cron/rrule scheduler) and exposes its management API as MCP tools. pg-boss stores all queue state in the app Postgres database under a schema derived from `MCP_SERVER_NAME`. Vault stays the secret store; pg-boss holds only job/queue data.
Design notes:
- The pg-boss instance starts lazily on the first `pgboss_*` tool call, so the MCP server works without Postgres until queue tools are used.
- No long-running worker handlers are registered inside the MCP server. Use `pgboss_fetch_jobs` for pull-based processing and `pgboss_complete_jobs` / `pgboss_fail_jobs` to settle claimed jobs.
- Background maintenance/cron supervision is off by default (`PGBOSS_SUPERVISE=false`). Schedules only fire while some pg-boss instance with supervision enabled is running (either this server with `PGBOSS_SUPERVISE=true` or a dedicated worker process). `pgboss_supervise` runs one on-demand maintenance pass.
- Connection details are redacted in all tool output: connection strings, usernames, and passwords are reported only as `*Configured` booleans.
Read-only tools (no `authorizationKey` required):
| Tool | Description |
| --- | --- |
| `pgboss_health` | Healthcheck: start state, schema installation, schema version |
| `pgboss_status` | Redacted connection info, schema version, maintenance/timekeeping state |
| `pgboss_get_queues` | List queues with configuration and job counts (optional `names` filter) |
| `pgboss_get_queue` | One queue with counts: queued/ready/active/failed/total (queue size) |
| `pgboss_get_queue_stats` | Historical stats snapshots (needs `persistQueueStats` on a monitor instance) |
| `pgboss_get_job` | Fetch one job by queue and id, including metadata |
| `pgboss_find_jobs` | Find jobs by id, singleton key, data containment, or queued state |
| `pgboss_get_schedules` | List schedules, optionally filtered by queue name and key |
| `pgboss_preview_schedule` | Preview upcoming occurrences of a cron/rrule expression in a timezone |
Mutating tools (require `mcp:write`/`mcp:admin` in scope mode, or `authorizationKey` when using a configured admin key):
| Tool | Description |
| --- | --- |
| `pgboss_create_queue` | Create a queue (`policy`: standard, short, singleton, stately, exclusive, key_strict_fifo; plus partition, deadLetter, retry/expire/retention options) |
| `pgboss_update_queue` | Update queue options (policy/partition are immutable) |
| `pgboss_delete_queue` | Delete a queue and all of its jobs |
| `pgboss_purge_queue` | Delete jobs by scope: `queued` (pending), `stored` (completed/failed), `all` |
| `pgboss_send` | Send a job with full options: `priority`, `startAfter`, `singletonKey`/`singletonSeconds`, `retryLimit`/`retryDelay`/`retryBackoff`/`retryDelayMax`, `expireInSeconds`, `retentionSeconds`, `deleteAfterSeconds`, `deadLetter` |
| `pgboss_send_after` | Send a delayed job (`after`: ISO 8601 timestamp or seconds from now) |
| `pgboss_send_throttled` | At most one job per `seconds` interval (optional `key`); `jobId=null` when deduplicated |
| `pgboss_send_debounced` | Keep the last job submitted within a `seconds` interval (optional `key`) |
| `pgboss_insert_jobs` | Bulk-insert jobs in one statement |
| `pgboss_schedule` | Create/update a recurring schedule (cron or RFC 5545 rrule, timezone, key, job options) |
| `pgboss_unschedule` | Remove a schedule by queue name and optional key |
| `pgboss_fetch_jobs` | Manually claim up to `batchSize` jobs (marks them active) |
| `pgboss_cancel_jobs` / `pgboss_resume_jobs` | Cancel jobs / resume cancelled jobs by id |
| `pgboss_retry_jobs` | Queue failed jobs for retry by id |
| `pgboss_delete_jobs` | Delete jobs by id |
| `pgboss_complete_jobs` / `pgboss_fail_jobs` | Settle active jobs with optional output/error data |
| `pgboss_supervise` | Run one on-demand maintenance pass (expiration, retention, monitoring) |
Scheduling format:
- `cron` accepts a standard 5-field cron expression: `minute hour day-of-month month day-of-week` (e.g. `0 3 * * *` = daily at 03:00, `*/15 * * * 1-5` = every 15 minutes on weekdays), or an RFC 5545 recurrence rule such as `FREQ=MONTHLY;BYDAY=-1FR;BYHOUR=17`.
- `options.tz` is an IANA timezone name (e.g. `America/Chicago`); default is `UTC`.
- `options.key` allows multiple schedules on the same queue.
- `options.missed` controls catch-up after downtime: `skip` (default) or `once`.
Examples:
```json
{
"name": "pgboss_schedule",
"arguments": {
"name": "nightly-report",
"cron": "0 3 * * *",
"data": { "reportType": "daily" },
"options": { "tz": "America/Chicago", "retryLimit": 2 },
"authorizationKey": "<admin-key-if-required>"
}
}
```
```json
{
"name": "pgboss_send",
"arguments": {
"name": "emails",
"data": { "to": "user@example.com" },
"options": {
"priority": 5,
"startAfter": 60,
"singletonKey": "welcome-user-42",
"retryLimit": 3,
"retryDelay": 30,
"retryBackoff": true,
"expireInSeconds": 900,
"deadLetter": "emails-dlq"
},
"authorizationKey": "<admin-key-if-required>"
}
}
```
```json
{
"name": "pgboss_preview_schedule",
"arguments": { "cron": "0 8 * * MON", "tz": "Europe/Berlin", "count": 3 }
}
```
## Security Behavior
- Sensitive fields are redacted unless MCP_ALLOW_SENSITIVE_OUTPUT=true.
- Mutating operations use verified OAuth scopes or the existing `MCP_ADMIN_AUTH_KEY` policy, selected by `MCP_AUTHZ_MODE`.
- Vault write operations are serialized through an internal queue and retried with exponential backoff.
## LangGraph Agent and A2A
### Postgres Configuration, Rotation, and Vault Agent Tools
These base tools remain available independently of agent enablement:
| Tool | Purpose and controls |
| --- | --- |
| `config_list`, `config_get` | Read configuration in the authenticated tenant/principal scope, or configured default scope for stdio/local calls. |
| `config_set`, `config_delete` | Mutate Postgres configuration; require `mcp:write`/`mcp:admin` in scope mode or `authorizationKey` when using a configured admin key. Values containing recognizable secret material are rejected; use Vault for secrets. |
| `token_rotation_config` | Resolve the interval in order: scoped Postgres override, default-scope Postgres override, then global environment default. |
| `vault_agent_token_read` | Inspect the enabled app-readable Vault Agent sink; requires `mcp:admin` in scope mode or a configured matching admin key. Raw token additionally requires `includeToken=true`. |
`MCP_CONFIG_DEFAULT_TENANT_ID`, `MCP_CONFIG_DEFAULT_PRINCIPAL_TYPE`, `MCP_CONFIG_DEFAULT_USER_ID`, and `MCP_CONFIG_DEFAULT_ACCOUNT_ID` define the default scope. HTTP callers cannot choose a different principal by supplying tool arguments; the scope must match the verified token/OAuth identity. Rotation uses `MCP_TOKEN_ROTATION_DEFAULT_INTERVAL_MS` plus the per-principal key named by `MCP_TOKEN_ROTATION_USER_INTERVAL_CONFIG_KEY`.
The optional agent uses LangGraph JS with a Postgres checkpoint saver, a separate `pg-boss` worker, and the same executable MCP tool registry as tool discovery. The MCP server continues to serve existing tools when the agent has no enabled configuration; agent goal/status/resume/cancel tools are disabled until an enabled configuration exists. New runs pin the current configuration revision. Disabling/deleting a config blocks new submissions but does not cancel already-submitted work; cancellation is a separate task operation.
Agent configuration is scoped to the authenticated tenant/principal and stored in the MCP-name-derived agent config table (for example `eurostat_sbs_mcp_agent_config`) with append-only revisions. A valid configuration has this shape:
```json
{
"inference": {
"protocol": "openai-compatible",
"baseUrl": "https://inference.example/v1",
"model": "model-name"
},
"credentialRef": "inference/provider",
"temperature": 0.2,
"maxTokens": 1024,
"timeLimitMs": 120000,
"instructions": "Use only registered tools that are permitted for this agent.",
"executionLimits": { "maxToolCalls": 8, "maxSteps": 12 },
"permittedCapabilities": ["service_health_check", "service_list_endpoints"],
"memory": { "semantic": true, "episodic": true, "procedural": true, "maxItems": 8 }
}
```
`credentialRef` is a relative KV path. The credential is read from Vault under `${MCP_SERVER_NAME}/<credentialRef>`; config, task, and memory rows never contain the credential. Only the OpenAI-compatible protocol is currently supported. HTTPS is required except for loopback development endpoints; public hostnames are resolved and private-address results are rejected. There is no fallback inference endpoint.
The configured time limit is capped by `MCP_AGENT_MAX_TASK_RUN_TIME_MS` (default 120000 ms); `MCP_AGENT_MAX_GOAL_BYTES` (default 16000) bounds persisted goals and MCP inputs.
Agent MCP tools:
| Tool | Purpose and controls |
| --- | --- |
| `agent_config_get` | Read the calling principal's config/revision with Vault reference redacted. |
| `agent_config_set`, `agent_config_update`, `agent_config_delete` | Admin-authorized revisioned writes (`mcp:admin` or a matching configured admin key); require `expectedRevision` to prevent lost updates. |
| `agent_config_user_get`, `agent_config_user_list` | Read another user's config/list user config revisions in an authorized tenant; require `mcp:agent-config:admin` or `mcp:admin`. |
| `agent_config_user_set`, `agent_config_user_update`, `agent_config_user_delete` | Cross-user revisioned writes; require `mcp:agent-config:admin` or `mcp:admin`. Mutations and their acting/target identities are audited atomically. |
| `agent_config_validate` | Validate settings and URL safety without persisting or connecting. |
| `agent_config_test_connection` | Admin-authorized Vault credential resolution and inference endpoint check; never returns the credential. |
| `agent_goal`, `agent_task_status`, `agent_task_resume`, `agent_task_cancel` | Scoped durable execution; registered disabled by default, enabled when an enabled config is loaded/written, and each handler independently validates the caller's authenticated scope. `agent_goal` returns `202` with the submitted task and a `nextAction` hint; poll `agent_task_status` with the returned task id until a terminal state to retrieve results. Resume uses the task's pinned config/checkpoint. |
| `agent_compositions_list`, `agent_composition_run` | Discover and execute declarative compositions learned from successful runs. |
| `agent_memory_search`, `agent_memory_add` | Search scoped semantic/episodic/procedural memories or add redaction-checked semantic memory. |
`agent_compositions_list` reflects newly registered capabilities on each read; `agent_composition_run` executes the selected declarative composition by its returned `toolName`. The MCP tool surface remains a static generic list/run pair, so composition changes do not require a tool-list notification. Each composition stores references to registered tools, their input JSON Schemas, provenance, version, and outcome metrics; it contains no generated code.
Agent configuration mutations, connection tests, and memory writes require `mcp:admin` in scope mode or a configured matching `MCP_ADMIN_AUTH_KEY` in key mode. Mutating capabilities called by an agent require `mcp:write` or `mcp:admin`; legacy key-authorized execution additionally requires `mcp:admin` when an admin key is configured. OAuth execution never injects the server's admin key into tool arguments. Tool inputs are schema-validated and execution events are stored with secrets redacted. Memory and task access always use authenticated scope, never caller-supplied identity.
Cross-user configuration tools do not change the authenticated identity used for task execution. They resolve an explicit active target `{tenantId, userId}` and require `mcp:agent-config:admin` or global `mcp:admin`.
The HTTP process serves an A2A SDK JSON-RPC endpoint at `MCP_A2A_PATH` and a public Agent Card at `MCP_A2A_CARD_PATH`. The card advertises JSON-RPC and bearer authentication; goal submission, task status, cancellation, and results use the same HTTP token/OAuth auth, body-size, IP/origin, and rate-limit controls as MCP. A2A communication is **asynchronous only**: goal submission returns an acknowledgment after the task and queue job commit, inference never runs inside the HTTP request, and clients poll task status/results through later `/a2a` calls while the dedicated worker executes LangGraph. Clients may send `metadata.idempotencyKey` to deduplicate A2A goal submissions. A dedicated worker (`npm run start:agent-worker`) consumes the durable queue; enable it with `MCP_AGENT_WORKER_ENABLED=true`. Local and external Compose stacks include this worker. In production, configure HTTPS at the service (`MCP_HTTP_TLS_ENABLED=true`) or a trusted TLS-terminating proxy and set `MCP_A2A_PUBLIC_URL` to the externally reachable endpoint; see [Production Deployment](#production-deployment) for the full runbook.
The worker restores the task's tenant and principal when invoking tools. Task insertion/resume and pg-boss submission now commit in the same Postgres transaction using pg-boss's supported `db.executeSql` adapter. An enqueue failure rolls back the task, rather than reporting an unconfirmed submission. Idempotent retries and worker reconciliation repair legacy submitted/no-job tasks (including the old queue-submission failure state); execution failures still require explicit resume. Stable task/job identities, scoped idempotency keys, and a task execution advisory lock prevent duplicate tasks/concurrent execution on delivery replay. This is not an exactly-once guarantee for external tool side effects after a worker crash; use idempotent service operations.
Checkpoint tables are isolated in the derived `${MCP_SERVER_NAME}` LangGraph schema; pg-boss uses a separate derived schema. Application tables include the existing config table plus versioned migrations, revisioned agent config, tool registrations/events, scoped semantic/episodic/procedural/tool memories, durable agent tasks, the tenancy directory (tenants and tenant principals with active flags), and the admin audit table recording delegated administrative actions. Memory retrieval uses Postgres full-text search and `ILIKE`; pgvector is not required.
### How the agent uses memory
The agent distinguishes short-term execution state from long-term, cross-task memory:
- **Short-term state (checkpoints).** Conversational/tool state for a single task lives in LangGraph's Postgres checkpointer under the derived `${MCP_SERVER_NAME}_langgraph` schema, keyed by a per-task thread. Checkpoints power retry and `agent_task_resume` continuation; they are not searchable memory.
- **Long-term memory (scoped tables).** Four memory classes are stored in namespaced, tenant/principal-scoped tables: **semantic** (facts added via `agent_memory_add`), **episodic** (records of successful runs), **procedural** (learned declarative tool compositions), and **tool** (per-tool usage/outcome summaries).
Runtime behavior in [src/agent/engine.js](src/agent/engine.js):
1. **Retrieval at run start (prompt augmentation).** If any class is enabled in the agent config's `memory` policy, the engine searches the owner's semantic, episodic, and procedural memories using the **task's goal text** as the query (Postgres full-text search and `ILIKE`). Up to `memory.maxItems` results (1–50, default 8), each truncated to 1000 characters, are appended to the system prompt under the label *"Relevant scoped memories (untrusted reference material)"*. This is the only automatic path by which memories reach the model; there is no mid-run memory lookup unless a memory tool is explicitly registered and permitted.
2. **Write-back on success (learning).** When a run completes and `memory.procedural` is enabled, one transaction registers the declarative composition and writes procedural memory (the composition), tool memory (tools used and outcome), and episodic memory (success record with task metadata).
3. **Manual semantic writes.** `agent_memory_add` is the only semantic write path: admin-authorized, content capped at 10000 characters, and content resembling a credential is rejected. `agent_memory_search` reads the same scoped stores.
Memory content is treated as **untrusted reference material**, never as instructions; retrieval and writes always use the authenticated tenant/principal scope, and stored content passes the same redaction checks as other persisted agent data. Disable any class per principal via the config's `memory` flags.
### Failure, retry, and recovery behavior
A task that fails due to a system issue does **not** automatically restart when the issue is resolved unless it is still within its bounded retry budget or never started executing. The behavior depends on where the failure occurs:
| Failure scenario | Recovery |
| --- | --- |
| Transient execution error (inference endpoint, Vault read, DB blip) within the job retry budget | Automatic: the engine returns the task to `working` and rethrows; pg-boss retries the delivery (default `retryLimit: 3`, `retryDelay: 5s`; schedule occurrences use `retryLimit: 10`). Each retry resumes from the saved LangGraph checkpoint rather than restarting from scratch. |
| Error persists past the retry budget | The task is marked `failed` and stays failed after the outage ends. Recovery is explicit: the owner calls `agent_task_resume`, which re-enqueues from the pinned config revision and last checkpoint under the resuming caller's authorization. |
| Worker offline at submission time | Automatic: the task and queue job are committed transactionally, so the goal waits durably and runs when the worker returns. |
| Worker crash mid-run | Automatic: pg-boss redelivers the job after expiration; the per-task advisory lock prevents concurrent duplicates and the checkpoint resumes prior progress. External tool side effects are not exactly-once across a crash — use idempotent service operations. |
| pg-boss enqueue failure at submission | The task insert rolls back and the caller receives an error instead of an unconfirmed submission; retry the submission with the same `idempotencyKey`. |
| Legacy submitted/no-job rows | Repaired by idempotent resubmission and the worker's startup/interval reconciliation. |
| Scheduled occurrences missed during downtime | Skipped by design (`missed=skip`); there is no catch-up or backfill. The next occurrence runs normally if the schedule and its grant remain active. |
Cancellation always wins: a task observed as `canceled` is never retried or resumed automatically, and resume of a schedule-originated task still requires its grant to be active.
### Durable agent scheduling
Scheduling is additive and remains discoverable even when the agent config is absent or disabled. Read operations always filter by the authenticated tenant/principal (or the existing default scope for local stdio). **All schedule mutations, manual runs, and previews require `mcp:admin` in scope mode, or a configured `MCP_ADMIN_AUTH_KEY` and matching `authorizationKey` in key mode.** No caller identity, bearer token, credential, arbitrary context, or inference settings are stored in a schedule.
| Tool | Inputs / behavior |
| --- | --- |
| `agent_schedule_grant_create` | `capabilities`, optional `scopes` (default `["mcp:invoke"]`); issues a non-secret owner-scoped grant ID. Only registered non-`agent_*` tool names are permitted; mutation capabilities marked `requiresAuthorizationKey` require `mcp:admin` in the grant. |
| `agent_schedule_grant_get`, `agent_schedule_grant_revoke` | `grantId`; reads or independently revokes an owned grant. Revocation cannot be undone; create a new grant and explicitly update the schedule. |
| `agent_schedule_create` | `goal`, `grantId`, `timing`, optional `enabled` (default true), `retryPolicy`. |
| `agent_schedule_once` | `goal`, `grantId`, `at` (future ISO timestamp with timezone), optional `enabled`, `retryPolicy`. |
| `agent_schedule_update` | `scheduleId`, `expectedRevision`, strict `patch` of the create fields. Timing/retry objects replace their whole object. |
| `agent_schedule_get`, `agent_schedule_list` | Owned schedule ID or bounded `limit` (1–100, default 50). |
| `agent_schedule_enable`, `agent_schedule_disable`, `agent_schedule_delete` | `scheduleId`, `expectedRevision`; increment revision, reconcile cron registration, and never cancel previously submitted tasks. Delete tombstones the schedule and retains history. |
| `agent_schedule_run_now` | `scheduleId`, caller-generated UUID `requestId`; queues an idempotent immediate trigger, not an unconditional task. Disabled/config-unavailable/revoked/overlapping schedules do not execute. |
| `agent_schedule_preview` | `timing`, optional `from` (ISO timestamp), `count` (1–20, default 5); no task or connection test is performed. |
| `agent_schedule_runs`, `agent_schedule_history` | `scheduleId`, bounded `limit`; run outcome/reason, occurrence ID, fresh task ID, and joined current task status/error. Works after schedule deletion. |
Timing is either `{"kind":"cron","cron":"0 9 * * *","tz":"America/New_York","missed":"skip"}` or `{"kind":"once","at":"2027-01-15T14:00:00Z"}`. Only five-field, minute-or-coarser cron is supported; timezone and cron validation/preview use the actual installed pg-boss 12.38.1 parser, with `from` converted to its required `Date` input. `missed` currently supports **only `skip`** (no catch-up/backfill). Unknown context/settings are rejected, not silently ignored. Goals use the normal byte/secret checks. `retryPolicy` controls task retries: `retryLimit` 0–10 (default 3), `retryDelay` 1–3600 seconds (default 5). Infrastructure trigger retries are independently bounded to 10 retries/5 seconds.
Admin-managed grant example (key mode; in OAuth scope mode use a token with `mcp:admin` and omit `authorizationKey`). All calls use the same authenticated owner; IDs below are placeholders returned by previous calls:
```json
{"tool":"agent_schedule_grant_create","arguments":{"capabilities":["service_health_check"],"scopes":["mcp:invoke"],"authorizationKey":"<admin-key>"}}
{"tool":"agent_schedule_create","arguments":{"goal":"Check service health","grantId":"<returned-grant-uuid>","timing":{"kind":"cron","cron":"0 9 * * *","tz":"America/New_York","missed":"skip"},"authorizationKey":"<admin-key>"}}
{"tool":"agent_schedule_preview","arguments":{"timing":{"kind":"cron","cron":"0 9 * * *","tz":"America/New_York"},"count":3,"authorizationKey":"<admin-key>"}}
{"tool":"agent_schedule_once","arguments":{"goal":"Check service health once","grantId":"<returned-grant-uuid>","at":"2027-01-15T14:00:00Z","authorizationKey":"<admin-key>"}}
{"tool":"agent_schedule_run_now","arguments":{"scheduleId":"<returned-schedule-uuid>","requestId":"<new-request-uuid>","authorizationKey":"<admin-key>"}}
{"tool":"agent_schedule_grant_revoke","arguments":{"grantId":"<returned-grant-uuid>","authorizationKey":"<admin-key>"}}
```
Migration version **3** adds `<normalized_mcp_name>_agent_schedules`, `_agent_schedule_runs`, and `_agent_schedule_grants`, plus task schedule/grant/capability references. Owners, revisions, timing, non-secret goals, retry policy, and grant authority live in Postgres; inference credentials still resolve through Vault. MCP name normalization/collision checks and previous config migrations remain intact.
The dedicated `<normalized_mcp_name>.agent.schedule-triggers` queue carries only schedule reference/revision and owner. Each pg-boss job ID is the durable occurrence identity; one-shots and manual requests use deterministic UUID job IDs. The trigger transaction locks the schedule, rechecks the current enabled config and active owner grant, checks overlap, and atomically inserts a **new task/context**, its queue job, and unique occurrence-to-task run mapping. Deleted/missing schedules, disabled schedules, stale revisions, unavailable config, revoked grants, and active-task overlap are recorded as skipped. Overlap is per schedule, includes submitted/working tasks, and is concurrency-safe. Disabling/config deletion does not cancel prior tasks. The worker intersects the grant with current config capabilities at trigger time; the task's pinned config and capability snapshot bound execution thereafter. Grant activity is rechecked before inference and every tool call; revoking a grant blocks pending tasks/new tool calls without storing or replaying bearer tokens.
Scheduled task failures use their bounded queue retry policy; an explicit new attempt uses admin-authorized `agent_schedule_run_now`. The existing caller-scoped `agent_task_resume` refuses scheduled tasks, so it cannot replay an admin-managed grant or bypass schedule overlap/disable controls. Normal non-scheduled task resume/checkpoint behavior is unchanged.
Worker operation:
```bash
# Dedicated process; supervision/cron is forced on in this process.
MCP_AGENT_WORKER_ENABLED=true npm run start:agent-worker
# Local stack includes mcp-agent-worker; Vault init dependency ordering is unchanged.
docker compose up -d
# Existing Vault/Postgres, no local infrastructure containers:
docker compose -f docker-compose.external.yml up -d
```
For app-only external deployments set `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`, `VAULT_ADDR`, and `VAULT_TOKEN` (or the documented Vault Agent file/listener runtime), with TLS and least-privilege production auth. Use the same `MCP_SERVER_NAME` and default scope/limits in MCP and worker. **Agent tasks/scheduling require pg-boss in the same Postgres database as application config**, so transactional queue operations can see the derived schema; leave `PGBOSS_CONNECTION_STRING` empty or point it at that same database. A separate database is not supported for agent dispatch. Schema creation/migrations require the existing deployment permissions.
Queues are created before registering task/trigger workers. Startup and periodic reconciliation upsert current cron registrations, remove orphan registrations, restore missing one-shot jobs, and repair legacy unqueued tasks; transactionally written schedule metadata/pg-boss rows cannot partially commit. Failures are logged and retried on the next interval (startup failures exit for supervisor restart); pg-boss scheduler errors/warnings are logged. SIGINT/SIGTERM stop reconciliation and drain the queue before closing Postgres. Compose uses `restart: unless-stopped`; supervise standalone workers with your process manager.
`MCP_AGENT_SCHEDULE_RECONCILE_MS` defaults to **30000**, positive integer. `MCP_AGENT_SCHEDULE_RETENTION_DAYS` defaults to **90**, positive integer. Reconciliation prunes old run rows only when no active mapped task or retained trigger queue job references them; it does not prune schedules, grants, tasks, checkpoints, or audit events. pg-boss job retention remains its own queue policy. Maintain separate retention/backup policies for tasks, grants/tombstones, checkpoints, and Vault. External tool side effects must remain idempotent across retries.
## Environment Variables
Core:
- MCP_SERVER_NAME (single namespace source; defaults to `eurostat-sbs-mcp`)
- APP_NAME (legacy Postgres/Vault migration source only; not a current naming knob)
- MCP_SERVER_VERSION
- MCP_ALLOW_SENSITIVE_OUTPUT
- MCP_ADMIN_AUTH_KEY
- MCP_AUTHZ_MODE (`auto` by default; `admin-key` or `oauth-scopes` for explicit policy selection)
- MCP_TRANSPORT_MODE (`stdio`, `http`, or `both`)
- MCP_CONFIG_DEFAULT_TENANT_ID
- MCP_CONFIG_DEFAULT_PRINCIPAL_TYPE
- MCP_CONFIG_DEFAULT_USER_ID
- MCP_CONFIG_DEFAULT_ACCOUNT_ID
- MCP_TOKEN_ROTATION_DEFAULT_INTERVAL_MS
- MCP_TOKEN_ROTATION_USER_INTERVAL_CONFIG_KEY
- MCP_VAULT_AGENT_AUTH_MODE_CONFIG_KEY
- MCP_VAULT_AGENT_TOKEN_FILE_PATH_CONFIG_KEY
- MCP_VAULT_AGENT_LISTENER_ADDR_CONFIG_KEY
- 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
Eurostat dissemination API (public, read-only; no upstream credentials exist):
- EUROSTAT_BASE_URL (default `https://ec.europa.eu/eurostat/api/dissemination`)
- EUROSTAT_COMEXT_BASE_URL (default `https://ec.europa.eu/eurostat/api/comext/dissemination`; used when a tool passes `server: "comext"`)
- EUROSTAT_TIMEOUT_MS (default `30000`)
- EUROSTAT_MAX_RESPONSE_BYTES (default `8388608`; oversized responses fail with `413` and async-API guidance)
- EUROSTAT_MAX_RETRIES (default `2`; bounded retries for 429/5xx and transient network failures — safe because all supported methods are reads)
- EUROSTAT_RETRY_BASE_DELAY_MS (default `500`)
- EUROSTAT_RETRY_MAX_DELAY_MS (default `10000`)
- EUROSTAT_USER_AGENT (optional custom User-Agent header)
HTTP transport:
- MCP_HTTP_HOST
- MCP_HTTP_PORT
- MCP_HTTP_PATH
- MCP_HTTP_HEALTH_PATH
- MCP_HTTP_AUTH_MODE (`token`, `oauth2`, `both`)
- MCP_HTTP_TOKEN_SOURCE (`vault` for indexed verification; `static` for `MCP_HTTP_AUTH_TOKENS`)
- MCP_HTTP_AUTH_TOKENS (comma-separated bearer tokens)
- MCP_HTTP_TRUST_PROXY
- MCP_HTTP_ALLOWED_ORIGINS (comma-separated)
- MCP_HTTP_ALLOWED_IPS (comma-separated)
- MCP_HTTP_MAX_BODY_BYTES
- MCP_HTTP_RATE_LIMIT_WINDOW_MS
- MCP_HTTP_RATE_LIMIT_MAX_REQUESTS
- MCP_HTTP_VAULT_TOKEN_INDEX_PATH
- MCP_HTTP_VAULT_TOKEN_DEFAULT_USER_ID
- MCP_HTTP_VAULT_TOKEN_REQUIRED_SCOPES
- MCP_HTTP_VAULT_TOKEN_REQUIRED_AUDIENCE
- MCP_HTTP_VAULT_TOKEN_CACHE_TTL_MS
- MCP_HTTP_OAUTH2_INTROSPECTION_URL
- MCP_HTTP_OAUTH2_CLIENT_ID
- MCP_HTTP_OAUTH2_CLIENT_SECRET
- MCP_HTTP_OAUTH2_REQUIRED_SCOPES
- MCP_HTTP_OAUTH2_REQUIRED_AUDIENCE
- MCP_HTTP_OAUTH2_TIMEOUT_MS
- MCP_HTTP_OAUTH2_CACHE_TTL_MS
- MCP_HTTP_APIFY_PROXY_TOKEN (optional trusted Apify identity secret)
- MCP_HTTP_MCPIZE_PROXY_TOKEN (optional trusted MCPize identity secret)
- MCP_HTTP_OAUTH2_ISSUER (optional introspection issuer check for the legacy single provider)
- MCP_HTTP_OAUTH2_SCOPE_MAP (optional provider-scope to MCP-scope allowlist)
- MCP_HTTP_OAUTH2_PROVIDERS (comma-separated provider names; replaces the legacy single-provider definition)
- `MCP_HTTP_OAUTH2_<PROVIDER>_INTROSPECTION_URL` (required for each named provider)
- `MCP_HTTP_OAUTH2_<PROVIDER>_CLIENT_ID`
- `MCP_HTTP_OAUTH2_<PROVIDER>_CLIENT_SECRET`
- `MCP_HTTP_OAUTH2_<PROVIDER>_ISSUER`
- `MCP_HTTP_OAUTH2_<PROVIDER>_REQUIRED_SCOPES`
- `MCP_HTTP_OAUTH2_<PROVIDER>_REQUIRED_AUDIENCE`
- `MCP_HTTP_OAUTH2_<PROVIDER>_SCOPE_MAP`
- `MCP_HTTP_OAUTH2_<PROVIDER>_TIMEOUT_MS`
- `MCP_HTTP_OAUTH2_<PROVIDER>_CACHE_TTL_MS`
- MCP_HTTP_TLS_ENABLED (native TLS termination via `node:https`; see [HTTPS Deployment Choice](#https-deployment-choice))
- MCP_HTTP_TLS_CERT_PATH (PEM certificate path; required when TLS is enabled)
- MCP_HTTP_TLS_KEY_PATH (PEM private key path; required when TLS is enabled)
- MCP_HTTP_TLS_KEY_PASSPHRASE (optional passphrase for an encrypted key)
- MCP_HTTP_TLS_MIN_VERSION (optional; default `TLSv1.2`)
Postgres:
- POSTGRES_HOST
- POSTGRES_PORT
- POSTGRES_DB
- POSTGRES_USER
- POSTGRES_PASSWORD
- POSTGRES_CONNECTION_STRING (optional; overrides individual Postgres fields)
pg-boss (Postgres job queue/scheduler):
- PGBOSS_ENABLED (default `true`; when `false`, `pgboss_*` tools return 503)
- PGBOSS_CONNECTION_STRING (optional dedicated connection string; when empty, shared `POSTGRES_*` settings are used; agent tasks/scheduling require the same database)
- pg-boss schema is derived from `MCP_SERVER_NAME`; `PGBOSS_SCHEMA` is ignored
- PGBOSS_SUPERVISE (default `false` for MCP processes; dedicated agent worker always enables maintenance/cron supervision)
- PGBOSS_MIGRATE (default `true`; apply pg-boss schema migrations on start)
- PGBOSS_CREATE_SCHEMA (default `true`; create the pg-boss schema if missing — requires `CREATE` privilege on the database)
- PGBOSS_MAX_POOL_SIZE (optional max connections for the pg-boss pool)
Postgres config model:
- Configuration data is stored in `${MCP_SERVER_NAME}`-derived namespaced tables. The config table uses composite key `(tenant_id, principal_type, principal_id, key)`.
- MCP config tools accept optional tenant/user/account scope for local calls, resolved through the configured defaults. HTTP calls use the authenticated principal; caller-supplied scope must match that identity.
- Agent config, task, memory, registration, and audit/event tables use the same namespace and authenticated principal scope. LangGraph checkpoints and pg-boss system tables use their own `${MCP_SERVER_NAME}`-derived schemas.
- The tenancy directory (`${MCP_SERVER_NAME}`-derived tenants and tenant-principals tables) records explicit active tenants, users, and accounts managed through the `tenancy_*` tools; disabled entries are rejected during HTTP/OAuth authentication. The admin audit table records delegated tenancy and cross-user configuration actions with actor, scopes, target, revision, and request metadata.
- Seed records include:
- `default/sample.feature`
- `default/app.defaults` for future default parameters.
- `default/token.rotation.intervalMs`
- `default/vault.agent.auth.mode`
- `default/vault.agent.tokenFilePath`
- `default/vault.agent.listener.addr`
Vault:
- VAULT_ADDR
- VAULT_TOKEN
- 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
- VAULT_KV_MOUNT
- VAULT_WRITE_RETRY_ATTEMPTS
- VAULT_WRITE_RETRY_BASE_DELAY_MS
- VAULT_WRITE_RETRY_MAX_DELAY_MS
Naming defaults:
- `MCP_SERVER_NAME` defaults to `eurostat-sbs-mcp`. Postgres names normalize punctuation to underscores (for example `eurostat_sbs_mcp_config`); Vault paths use the MCP name prefix (for example `eurostat-sbs-mcp/http/auth/token-index`).
- Postgres identifiers are checked against the 63-character limit and a namespaced metadata row rejects different MCP names that normalize to the same Postgres prefix.
- `APP_NAME` is used only to find legacy data. Existing `${APP_NAME}_config` rows are copied into the MCP-namespaced config table without deleting or modifying the source. Vault KV v2 data can be copied explicitly with `npm run vault:migrate-namespace -- --dry-run`, then `npm run vault:migrate-namespace`; the old source is retained and existing destination records are not overwritten. Set `MCP_SERVER_NAME` consistently for the MCP process and worker.
Reference values are in [.env.example](.env.example).
## Quick Start
Requires Node.js 22+ and npm; local containers also require Docker Compose (2.24+ for optional `.env` support).
1. Install dependencies with `npm ci`.
2. Copy [.env.example](.env.example) to a local `.env`; adjust Eurostat settings if needed (no upstream credentials exist). Do not commit credentials.
3. Start infrastructure first with `docker compose up -d postgres vault`. This also runs the Vault key-file helper through the Vault dependency.
4. Initialize and unseal the Raft-backed local Vault on first use:
```bash
docker exec -e VAULT_ADDR=http://127.0.0.1:8200 eurostat-sbs-mcp-vault vault operator init -key-shares=1 -key-threshold=1 -format=json
docker exec -e VAULT_ADDR=http://127.0.0.1:8200 eurostat-sbs-mcp-vault vault operator unseal <unseal_key_returned_by_vault_init>
```
5. Securely retain Vault's actual initialization output, configure valid application Vault authentication in `.env`, and enable the KV v2 mount used by `VAULT_KV_MOUNT` if absent. The example `VAULT_TOKEN=root` is a placeholder, not a token created by Raft initialization. The managed key-file helper does not initialize Vault, set its Shamir shares, or auto-unseal it.
6. Choose the capabilities to enable:
| Goal | Start / configure |
| --- | --- |
| Local MCP tools | `npm run start:stdio` with `MCP_TRANSPORT_MODE=stdio`; register the process with your MCP client. No agent/inference setup is needed. |
| Remote MCP / A2A access | Configure [HTTP token or OAuth authentication](#http-mcp-endpoint), then run `npm run start:http`. |
| Both MCP transports | Run `npm run start:both`; this launches transports only. |
| Durable agent tasks and schedules | Set `MCP_AGENT_WORKER_ENABLED=true`, run `npm run start:agent-worker` separately, store an inference credential in Vault, and create an enabled [scoped agent config](#langgraph-agent-and-a2a). Create a revocable grant before a schedule. |
| Containerized HTTP + worker | After adapting the Compose environment for valid Vault/service credentials, run `docker compose up -d mcp-http mcp-agent-worker`. The local manifest's explicit `environment` entries override `.env`, including its placeholder `VAULT_TOKEN=root`; override those entries in your deployment configuration. For hardening, see [Production Deployment](#production-deployment). |
7. Run `npm test` for workspace contracts and application coverage. Database-backed agent/scheduling integration tests require an isolated database configured through `MCP_AGENT_TEST_DATABASE_URL`.
The supplied Compose stacks enable the worker process, not a principal's inference configuration. Creating a config and granting capabilities are separate administrative steps using OAuth `mcp:admin` or the configured admin-key policy.
## External Services Mode
Use this mode when Vault and Postgres are already managed outside this repository.
Required environment variables:
- `POSTGRES_HOST`, `POSTGRES_PORT`, `POSTGRES_DB`, `POSTGRES_USER`, `POSTGRES_PASSWORD`
- `VAULT_ADDR`, `VAULT_TOKEN`
Run the app-only compose stack:
```bash
docker compose -f docker-compose.external.yml up -d
```
Notes:
- The app still uses Vault for secrets and Postgres for config.
- The external stack runs the MCP HTTP container and dedicated agent worker, but skips local Postgres/Vault containers.
- If you keep Vault sealed, the app will still require whatever unseal process your external Vault uses.
### Test Coverage Notes
Run `npm test` for the node:test suite. Agent coverage includes configuration validation/secret redaction, namespace collision and identifier limits, registry authorization and schema validation, A2A card/JSON-RPC/auth lifecycle, and worker/config wiring. The live Postgres agent integration test is opt-in via `MCP_AGENT_TEST_DATABASE_URL`; when unset it is reported as skipped, not as a verified database test.
Existing automation includes listener-related coverage for Vault Agent runtime resolution:
- [tests/vault-agent-runtime.test.js](tests/vault-agent-runtime.test.js) validates:
- listener mode resolution from Postgres defaults
- both mode resolution (listener + file)
- fallback to environment values when database mode is invalid
- `VaultService` applies Postgres-backed listener settings and preserves environment behavior when database pointers are absent
Transport scripts:
```bash
# stdio only (default)
npm run start:stdio
# HTTP transport only
npm run start:http
# run stdio + HTTP as two processes
npm run start:both
```
## Production Deployment
This section is the consolidated runbook for operating this server in production. It links to the detailed sections rather than repeating them. The supplied compose stacks and credentials are development defaults; production readiness is the deployer's responsibility.
### Production architecture and process layout
Run two separately supervised services built from this repository:
| Service | Entry | Notes |
| --- | --- | --- |
| MCP HTTP + A2A | `npm run start:http` / `mcp-http` container | Serves `/mcp`, `/a2a`, the Agent Card, and `/healthz`. |
| Agent worker | `npm run start:agent-worker` / `mcp-agent-worker` container | Requires `MCP_AGENT_WORKER_ENABLED=true`; drains gracefully on shutdown. |
Stdio transport is for local/registered-client use, not production service deployment. The server and worker must share **one Postgres database** (transactional task dispatch) and identical `MCP_SERVER_NAME`, authorization mode, Eurostat, and Vault settings. The supported production shape is [docker-compose.external.yml](docker-compose.external.yml) against managed Postgres and Vault ([External Services Mode](#external-services-mode)); Kubernetes or systemd deployments are operator adaptations — wire liveness to `/healthz` and stop the worker with SIGTERM to allow queue drain.
### Credential replacement inventory
Every development placeholder that must be replaced before production:
| Setting | Replace with | Documented at |
| --- | --- | --- |
| `VAULT_TOKEN=root` | Real Vault auth (AppRole or Vault Agent). The local manifest's explicit `environment` entries override `.env` — override them in deployment configuration. | [Vault Production Migration](#vault-production-migration-raft) |
| `MCP_ADMIN_AUTH_KEY` | Generated secret (`openssl rand -hex 32`) in deployment secrets | [Configure the admin key](#configure-the-admin-key) |
| HTTP bearer tokens | Vault-stored per-user token index (`MCP_HTTP_TOKEN_SOURCE=vault`), seeded per user | [Vault Multi-User Token Model](#vault-multi-user-token-model), [Vault HTTP Token Seeding](#vault-http-token-seeding) |
| OAuth client secrets | Deployment secrets, never committed files; HTTPS introspection endpoints | [OAuth providers](#oauth-providers-and-authorization-capabilities) |
| Upstream API credentials | None — the Eurostat dissemination API is public and read-only | [Environment Variables](#environment-variables) |
| Inference credentials | Vault KV under `${MCP_SERVER_NAME}/<credentialRef>`, configured post-deploy via agent config tools | [LangGraph Agent and A2A](#langgraph-agent-and-a2a) |
### Network and transport hardening
- Choose a TLS mode: reverse proxy (recommended; set `MCP_HTTP_TRUST_PROXY=true`) or native Node TLS. See [HTTPS Deployment Choice](#https-deployment-choice).
- Set `MCP_A2A_PUBLIC_URL` to the externally reachable `/a2a` endpoint so the Agent Card advertises the right address.
- Restrict admission: `MCP_HTTP_ALLOWED_ORIGINS`, `MCP_HTTP_ALLOWED_IPS`, `MCP_HTTP_MAX_BODY_BYTES`, and the rate-limit window/max settings.
- Rate limits and verification caches are **process-local**. Run a single HTTP instance, or enforce rate limiting at the proxy/load balancer when running more than one.
- Select the authorization mode deliberately: `auto` (default), `admin-key`, or `oauth-scopes`; configure the same mode in server and worker.
### Vault production posture
1. Convert to a Raft-backed server-mode Vault and harden it: [Vault Production Migration (Raft)](#vault-production-migration-raft) covers conversion, then audit logging, a least-privilege policy, and AppRole via the post-conversion bootstrap script.
2. Own the unseal procedure: the managed key-file helper supplies key material for local flows; production unseal (including who holds shares) is an operational decision.
3. Prefer [Vault Agent auto-auth and token renewal](#vault-agent-auto-auth-and-token-renewal) over long-lived static tokens.
4. Back up Vault with Raft snapshots on a schedule (`vault operator raft snapshot save <file>`) and store them with the same care as the secrets themselves. Test restore (`... snapshot restore`) periodically.
### Postgres production posture
- Use a managed or properly backed-up Postgres. One database holds everything the MCP owns: config, agent tasks, memories, schedules, grants, LangGraph checkpoints (`${MCP_SERVER_NAME}_langgraph`), and pg-boss state (`${MCP_SERVER_NAME}_pgboss`) — a single backup/restore point.
- Grant the application role privileges to create and use its derived schemas and tables on first run; migrations are applied by the application and are forward-only.
- Postgres and Vault restores are independent. After a Vault restore/rotation, tasks referencing changed credentials fail cleanly and can be resumed; no Postgres rows contain secrets.
### Scaling and availability boundaries
- **Workers scale horizontally.** Multiple worker processes are safe: pg-boss delivery plus the per-task advisory lock prevent concurrent duplicate execution. Run exactly one worker fleet per database/namespace; cron supervision and reconciliation run inside the workers.
- **HTTP instances need edge coordination.** Multiple instances work, but rate limits and token-verification caches do not share state — enforce limits at the edge.
- External side effects are at-least-once after a crash ([failure behavior](#failure-retry-and-recovery-behavior)); keep upstream operations idempotent.
### Observability and operations
Monitor:
- `/healthz` for liveness; HTTP access logs for admission and rate-limit events.
- Worker logs for reconciliation lines and schedule/grant skips.
- Failed/stuck tasks via `agent_task_status` and queue depth via the `pgboss_*` tools.
- Vault seal status and audit log; Postgres connection and storage headroom.
Stored tool events and task results are redacted; treat process logs with the same discipline and never log bearer tokens or expanded authorization headers.
### Upgrade and rollback
- Treat `MCP_SERVER_NAME` as immutable in production; renaming changes every derived namespace and requires an explicit migration plan.
- Application migrations are versioned and forward-only; in-flight tasks pin their agent-config revision, so config changes do not disturb running work.
- Upgrade order: drain and stop workers, update server, update workers, restart. Validate with `npm test` (including workspace conformance assertions) before rollout.
- Roll back by redeploying the prior image/commit; schema migrations already applied stay in place and are designed to be additive.
### Production readiness checklist
- [ ] Managed Postgres provisioned; server and worker point at the same database
- [ ] Vault converted to Raft server mode, initialized, unsealed, audited
- [ ] AppRole or Vault Agent auth replacing `VAULT_TOKEN=root` everywhere (including compose overrides)
- [ ] Raft snapshot backups scheduled and restore tested
- [ ] `MCP_ADMIN_AUTH_KEY` generated and distributed via deployment secrets (if key mode is used)
- [ ] HTTP auth configured: Vault token index seeded per user, or OAuth providers with HTTPS introspection and scope maps
- [ ] `MCP_AUTHZ_MODE` chosen and identical in server and worker
- [ ] TLS terminated (proxy with `MCP_HTTP_TRUST_PROXY=true`, or native TLS with provisioned cert/key)
- [ ] `MCP_A2A_PUBLIC_URL`, allowed origins/IPs, body and rate limits set
- [ ] Single HTTP instance, or edge rate limiting for multiple instances
- [ ] Worker enabled (`MCP_AGENT_WORKER_ENABLED=true`) and supervised with graceful shutdown
- [ ] Inference credential stored in Vault (the Eurostat API needs no credentials)
- [ ] Agent config created per principal with bounded `permittedCapabilities`; grants issued before schedules
- [ ] Delegated administration mapped to least privilege: `mcp:tenancy:admin` and `mcp:agent-config:admin` issued instead of global `mcp:admin` where possible, with `allowedTenantIds` bounding multi-tenant admins; tenancy directory seeded for managed tenants/users
- [ ] Monitoring in place for health, worker reconciliation, failed tasks, queue depth, Vault seal
- [ ] `npm test` green on the exact deployed commit
## HTTP MCP Endpoint
Default endpoint values:
- MCP URL: `http://127.0.0.1:3000/mcp`
- Health URL: `http://127.0.0.1:3000/healthz`
HTTP transport security controls:
- Every `/mcp` request requires `Authorization: Bearer <token>`.
- For `MCP_HTTP_AUTH_MODE=token`, set `MCP_HTTP_TOKEN_SOURCE=vault` to validate tokens from Vault.
- For `MCP_HTTP_AUTH_MODE=oauth2`, bearer tokens are validated by OAuth2 introspection.
- For `MCP_HTTP_AUTH_MODE=both`, either token strategy can authorize requests.
- Mutating tools use OAuth scopes by default for OAuth-authenticated callers; non-OAuth callers retain the admin-key policy. See below for explicit mode selection.
- Request limits are enforced with:
- `MCP_HTTP_MAX_BODY_BYTES`
- `MCP_HTTP_RATE_LIMIT_WINDOW_MS`
- `MCP_HTTP_RATE_LIMIT_MAX_REQUESTS`
- Optional network restrictions:
- `MCP_HTTP_ALLOWED_ORIGINS`
- `MCP_HTTP_ALLOWED_IPS`
### OAuth providers and authorization capabilities
The server validates access tokens using OAuth2 introspection; it does not issue tokens, implement an authorization/login flow, or add JWT/JWKS signature verification. Configure one or more trusted authorization servers that support introspection.
```dotenv
MCP_HTTP_AUTH_MODE=oauth2
MCP_AUTHZ_MODE=auto
MCP_HTTP_OAUTH2_PROVIDERS=okta,keycloak
MCP_HTTP_OAUTH2_OKTA_INTROSPECTION_URL=https://okta.example.com/oauth2/default/v1/introspect
MCP_HTTP_OAUTH2_OKTA_CLIENT_ID=<introspection-client-id>
MCP_HTTP_OAUTH2_OKTA_CLIENT_SECRET=<deployment-secret>
MCP_HTTP_OAUTH2_OKTA_ISSUER=https://okta.example.com/oauth2/default
MCP_HTTP_OAUTH2_OKTA_REQUIRED_SCOPES=api.invoke
MCP_HTTP_OAUTH2_OKTA_REQUIRED_AUDIENCE=mcp
MCP_HTTP_OAUTH2_OKTA_SCOPE_MAP=api.invoke:mcp:invoke,api.write:mcp:write,api.admin:mcp:admin,api.tenancy:mcp:tenancy:admin,api.agent-config:mcp:agent-config:admin
MCP_HTTP_OAUTH2_KEYCLOAK_INTROSPECTION_URL=https://keycloak.example.com/realms/mcp/protocol/openid-connect/token/introspect
MCP_HTTP_OAUTH2_KEYCLOAK_CLIENT_ID=<introspection-client-id>
MCP_HTTP_OAUTH2_KEYCLOAK_CLIENT_SECRET=<deployment-secret>
MCP_HTTP_OAUTH2_KEYCLOAK_ISSUER=https://keycloak.example.com/realms/mcp
MCP_HTTP_OAUTH2_KEYCLOAK_REQUIRED_SCOPES=mcp:invoke
MCP_HTTP_OAUTH2_KEYCLOAK_REQUIRED_AUDIENCE=mcp
```
Provider names are unique case-insensitively, start with a letter, and contain only letters, digits and underscores. Every named provider requires an introspection URL. Each supports `CLIENT_ID`, `CLIENT_SECRET`, `ISSUER`, `REQUIRED_SCOPES` (comma-separated), `REQUIRED_AUDIENCE`, `SCOPE_MAP`, `TIMEOUT_MS` (default 5000, positive), and `CACHE_TTL_MS` (default 30000, non-negative). Use HTTPS endpoints in production and supply client secrets through deployment secrets, not committed files.
When `MCP_HTTP_OAUTH2_PROVIDERS` is empty, the existing unprefixed `MCP_HTTP_OAUTH2_*` settings remain supported as provider `default`; named providers replace that legacy definition. Named providers automatically select `oauth2` authentication only if `MCP_HTTP_AUTH_MODE` is unset. An explicit `token` setting still disables OAuth. Both Compose manifests default to `token`, so explicitly set `MCP_HTTP_AUTH_MODE=oauth2` or `both` there.
JWT `iss` is an untrusted routing hint, never proof of authentication. A configured `ISSUER` must match the introspection response's `iss` (providers omitting that claim must leave `ISSUER` unset). Opaque tokens are tried against the configured providers in order until accepted; **only configure providers trusted to receive the same bearer credentials**, since opaque tokens may be sent to each of them. A provider outage does not prevent trying later providers. All failures deny access. Positive and negative caches are bounded to 1000 entries per provider, retain token hashes rather than plaintext cache keys, and successful entries never outlive token expiry.
`REQUIRED_SCOPES` checks the original provider scopes before mapping. Without `SCOPE_MAP`, verified scopes pass through unchanged. With a non-empty mapping, only explicitly mapped scopes are retained: `api.admin:mcp:admin` grants admin capability, while unmapped scopes (including a raw `mcp:admin`) are discarded. Mappings accept the canonical targets `mcp:invoke`, `mcp:read`, `mcp:write`, `mcp:admin`, `mcp:agent`, `mcp:tenancy:admin`, and `mcp:agent-config:admin`.
#### Authorization modes
| `MCP_AUTHZ_MODE` | Behavior |
| --- | --- |
| `auto` (default) | OAuth-authenticated requests use scopes instead of the admin key. Stdio and static/Vault-index-token callers retain the existing key policy, even when OAuth is configured. |
| `admin-key` | Preserve legacy key authorization for all callers, including OAuth callers. |
| `oauth-scopes` | Require scopes for protected operations; no admin-key fallback, even if a matching key is supplied. Startup requires OAuth-enabled HTTP authentication. Local stdio callers have no verified scopes and cannot perform protected operations. |
`authorizationKey` remains an optional schema parameter for client compatibility, but is ignored when scope authorization applies. In key mode, regular mutations remain allowed if no key is configured; admin-only operations remain disabled until a key is configured. Missing mutation/admin scopes return `403`; missing/invalid required admin keys return `401`; disabled key-only admin operations return `503`. Invalid HTTP bearer credentials return `401`.
#### Scope capabilities
| Scope | Capabilities |
| --- | --- |
| `mcp:invoke` or `mcp:agent` | Submit/read/resume/cancel agent tasks and invoke agent compositions/A2A, subject to agent enablement and principal ownership. |
| `mcp:write` | Mutating service calls, Postgres config writes/deletes, and mutating pg-boss tools in scope mode. |
| `mcp:admin` | All write capabilities plus Vault token seed/lifecycle/sink inspection, agent config changes/connection tests/memory writes, and schedule/grant mutations/manual runs/previews. |
| `mcp:read` | Descriptive read scope; existing read tools do not add a per-tool scope gate. Restrict HTTP admission with provider `REQUIRED_SCOPES` as needed. |
| `mcp:tenancy:admin` | Manage tenants and tenant users, including tenant/user token seeding. A dedicated tenancy administrator is limited to its authenticated tenant or `allowedTenantIds`. |
| `mcp:proxy:initialize` | Initialize the trusted Apify or MCPize caller in its fixed platform tenant. This scope does not grant general tenancy administration. |
| `mcp:agent-config:admin` | Read and mutate agent configurations for other users in an authorized tenant. It does not grant tenancy or Vault server-token administration. |
`mcp:admin` satisfies write/admin checks but does not replace the separate `mcp:invoke`/`mcp:agent` requirement for agent execution. Neither scopes nor scope mapping bypass tenant/principal ownership checks. Agent `permittedCapabilities` still limits the runnable tool names; composition steps and scheduled tasks enforce the same underlying tool handlers and scope checks.
Service-specific upstream OAuth scopes: **none** — the Eurostat dissemination API is public and unauthenticated, so no upstream scopes exist. All `eurostat_*`, `service_connection_info`, `service_scope_info`, `service_list_endpoints`, `service_health_check`, and `service_query_suggestion` tools are read-only and require only HTTP admission (`mcp:invoke` by default via `MCP_HTTP_VAULT_TOKEN_REQUIRED_SCOPES` or provider `REQUIRED_SCOPES`). Mutating capabilities in this MCP are exclusively server administration (config writes, Vault token seeding/lifecycle, pg-boss management, agent configuration, schedules) and require `mcp:write` or the admin-only scopes shown above rather than a raw bearer token or authorization key alone.
The delegated admin scopes are restricted to the caller's authenticated `tenantId` unless OAuth introspection or a Vault token entry supplies `allowedTenantIds` (also accepted as `tenantIds`). `mcp:admin` remains global for backward compatibility. Recorded disabled tenants and users are rejected during subsequent HTTP/OAuth authentication.
Durable tasks persist the verified authentication method and granted scopes, never bearer tokens or admin keys. Workers restore this method, scopes, tenant, and principal. A resume replaces authorization with the resuming caller's method/scopes. Pre-existing tasks without a recorded method retain legacy authorization in `auto`. Scheduled tasks use their independently revocable admin-issued grant scopes in `auto`/`oauth-scopes`; grant capability intersections and revocation checks remain enforced.
Both Compose manifests load an optional local `.env` for server and worker, including arbitrary named-provider variables, and pass `MCP_AUTHZ_MODE` explicitly. Configure the same mode/provider settings in both processes, then recreate containers after changes (`env_file` optional-path syntax requires Docker Compose 2.24+). For host-exported provider secrets not in `.env`, add explicit deployment environment entries; Compose interpolation alone does not forward arbitrary host variables.
`service_connection_info` reports configured `authzMode` and the caller's effective `authorizationMode`; `service_query_suggestion` reports effective mode and whether the admin-key argument is needed.
### Delegated tenancy administration
The namespaced Postgres schema stores explicit active tenants and tenant users. The following tools require `mcp:tenancy:admin` or global `mcp:admin`:
| Tools | Behavior |
| --- | --- |
| `tenancy_tenant_get`, `tenancy_tenant_list` | Inspect tenants visible to the delegated administrator. |
| `tenancy_tenant_create` | Create an active tenant. |
| `tenancy_tenant_update`, `tenancy_tenant_disable` | Update metadata or disable a tenant without deleting its records. |
| `tenancy_user_get`, `tenancy_user_list` | Inspect users in an authorized tenant. |
| `tenancy_user_create` | Create an active tenant user. |
| `tenancy_user_update`, `tenancy_user_disable` | Update metadata or disable a user without deleting owned configs/tasks. |
| `tenancy_account_get`, `tenancy_account_list` | Inspect accounts in an authorized tenant. |
| `tenancy_account_create`, `tenancy_account_update`, `tenancy_account_disable` | Create, update, or disable tenant account principals with the same audit and activation model. |
Tenant/user IDs are stable once created. Token seeding now requires `mcp:tenancy:admin` or `mcp:admin` and references an active tenant user. Legacy Vault server-token lifecycle and sink-inspection tools remain under the global `mcp:admin` scope. Administrative tenancy changes and cross-user config changes record actor, scopes, target, revision, and request metadata in the namespaced admin audit table.
### Vault Multi-User Token Model
Store HTTP bearer tokens in Vault at `MCP_HTTP_VAULT_TOKEN_INDEX_PATH`.
If unset, the base token index path is `${MCP_SERVER_NAME}/http/auth/token-index`; the verifier preserves tenant/principal scoping and default-user fallback within that index.
Default-user fallback behavior:
- `MCP_HTTP_VAULT_TOKEN_DEFAULT_USER_ID` defaults to `default`.
- If no non-default users exist in the token index, the default user is always used as fallback.
Supported index shape:
```json
{
"tokens": {
"<sha256(token)>": {
"userId": "user-123",
"tokenId": "tok-123",
"active": true,
"scopes": ["mcp:invoke", "mcp:read"],
"audience": ["codex", "claude"],
"allowedTenantIds": ["tenant-a", "tenant-b"],
"expiresAt": "2026-12-31T23:59:59Z"
}
}
}
```
Notes:
- Store only token hashes in Vault index data, never plaintext tokens.
- `MCP_HTTP_VAULT_TOKEN_REQUIRED_SCOPES` and `MCP_HTTP_VAULT_TOKEN_REQUIRED_AUDIENCE` enforce policy checks.
- `allowedTenantIds` is optional and only consulted for delegated admin scopes (`mcp:tenancy:admin`, `mcp:agent-config:admin`); it does not widen ordinary data access, which stays bound to the token's tenant/principal.
- This keeps secrets in Vault under the MCP-name prefix while configuration remains in MCP-namespaced Postgres tables.
### Vault HTTP Token Seeding
Use the helper script to generate an opaque bearer token and store it in the Vault user token structure:
```bash
npm run vault:seed-http-token -- --user-id default --json
```
Useful options:
- `--user-id <id>`: Vault user to seed.
- `--token-id <id>`: Optional token id stored with the entry.
- `--scopes <list>`: Comma or space separated scopes.
- `--audience <list>`: Comma or space separated audience values.
- `--allowed-tenant-ids <list>`: Tenant IDs that a delegated admin token may target.
- `--expires-at <value>`: Optional ISO timestamp or unix seconds.
- `--path <vault-path>`: Override the token index path.
The script writes the token record in the MCP-namespaced index and mirrors the token in the top-level token map for compatibility.
If you need to reseed a user, run the script again with the same `--user-id` and a new `--token-id`.
### Vault OAuth Token Seeding
Use the helper script to store a provided OAuth access token in the Vault user token structure:
```bash
npm run vault:seed-oauth-token -- --token "$OAUTH_ACCESS_TOKEN" --user-id default --json
```
Useful options:
- `--token <value>`: OAuth access token to seed.
- `--user-id <id>`: Vault user to seed.
- `--token-id <id>`: Optional token id stored with the entry.
- `--scopes <list>`: Comma or space separated scopes.
- `--audience <list>`: Comma or space separated audience values.
- `--allowed-tenant-ids <list>`: Tenant IDs that a delegated admin token may target.
- `--expires-at <value>`: Optional ISO timestamp or unix seconds.
- `--path <vault-path>`: Override the token index path.
The script stores the provided token under the MCP-namespaced index, keeps the top-level token map aligned, and marks the entry as `oauth2` in Vault metadata.
### MCP Tool
The same capability is exposed as an MCP tool for controlled setup workflows:
- `vault_seed_http_token`: generate a bearer token and store it in the Vault HTTP token index for a user.
- `vault_seed_oauth_token`: store a provided OAuth access token in the Vault HTTP token index for a user.
For both tools, include app/user scope in requests so clients can reason about target storage:
- `mcpServerName` determines the MCP/Postgres/Vault namespace.
- `tenantId` and `userId` determine the token-index path under `${MCP_SERVER_NAME}/tenants/<tenant_id>/users/<user_id>/...`.
Both tools require `mcp:admin` in scope mode, or a configured `MCP_ADMIN_AUTH_KEY` and matching `authorizationKey` in key mode. The bearer seeding tool returns the generated token once; the OAuth seeding tool never echoes the supplied token. Vault index data stores only the token hash and metadata. Seeding an OAuth token in this index does not make index-based authentication an introspected OAuth request: `auto` still uses the key policy for index-authenticated callers.
### Vault Token Lifecycle MCP Tools
This server exposes node-vault token lifecycle methods as MCP tools:
- `token_lookup_self` -> `tokenLookupSelf`
- `token_renew_self` -> `tokenRenewSelf`
- `token_create` -> `tokenCreate`
- `token_revoke` -> `tokenRevoke`
- `token_revoke_self` -> `tokenRevokeSelf`
These tools are intended for controlled operational usage.
All five lifecycle tools require `mcp:admin` in scope mode, or a configured `MCP_ADMIN_AUTH_KEY` and matching `authorizationKey` in key mode. `token_create` and `token_renew_self` redact the raw client token unless the admin-authorized caller explicitly supplies `includeToken=true`.
### Vault Agent Auto-Auth and Token Renewal
Vault Agent can own token auth/renewal while this service reads the sink token file.
- Enable with `VAULT_AGENT_ENABLED=true`
- Choose auth mode with `VAULT_AGENT_AUTH_MODE`:
- `file`: use Vault Agent token sink file
- `listener`: use Vault Agent listener endpoint
- `both`: enable listener operations and file-based token read workflows
- Configure sink file path with `VAULT_AGENT_TOKEN_FILE_PATH`
- Enable listener with `VAULT_AGENT_LISTENER_ENABLED=true`
- Configure listener with `VAULT_AGENT_LISTENER_ADDR`
- Use `vault_agent_token_read` when application workflows need token sink visibility
- Raw token sink data is returned only with `includeToken=true` and admin authorization; the default response contains path/configuration metadata only.
When Vault Agent mode is enabled:
- File mode refreshes token state from the configured token sink path.
- Listener mode routes Vault operations through the configured Vault Agent listener.
- Both mode supports listener operations and token sink read workflows.
### Option 3: Postgres-Backed Non-Secret Vault Agent Settings
This server supports storing non-secret Vault Agent runtime pointers/settings in Postgres while keeping token material in Vault.
- Runtime settings are read from default user config scope (`MCP_CONFIG_DEFAULT_USER_ID`).
- Key names are configurable with:
- `MCP_VAULT_AGENT_AUTH_MODE_CONFIG_KEY`
- `MCP_VAULT_AGENT_TOKEN_FILE_PATH_CONFIG_KEY`
- `MCP_VAULT_AGENT_LISTENER_ADDR_CONFIG_KEY`
- Recommended values in Postgres:
- `vault.agent.auth.mode`
- `vault.agent.tokenFilePath`
- `vault.agent.listener.addr`
### Rotation Time Configuration
Rotation interval supports both global defaults and user-scoped overrides:
- Global default env variable: `MCP_TOKEN_ROTATION_DEFAULT_INTERVAL_MS`
- User-scoped config key name: `MCP_TOKEN_ROTATION_USER_INTERVAL_CONFIG_KEY` (default `token.rotation.intervalMs`)
Effective value resolution is:
1. User-scoped Postgres config (`userId` + key)
2. Default user Postgres config (`default` + key)
3. Global env default
Use `token_rotation_config` tool to inspect the resolved rotation interval for a user scope.
Minimal remote call example:
```bash
curl -i http://127.0.0.1:3000/mcp \
-H "Authorization: Bearer replace-me-token" \
-H "Accept: application/json, text/event-stream" \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-11-25",
"capabilities": {},
"clientInfo": { "name": "client", "version": "1.0.0" }
}
}'
```
## HTTPS Deployment Choice
The HTTP transport supports two TLS modes.
### Option A: Reverse-proxy TLS (recommended)
Terminate TLS at a reverse proxy or load balancer.
- Keep this app on internal HTTP (`MCP_HTTP_TLS_ENABLED=false`).
- Enforce HTTPS, client allowlists, and edge-level controls at the proxy/LB.
- Forward traffic to `MCP_HTTP_HOST:MCP_HTTP_PORT` and set `MCP_HTTP_TRUST_PROXY=true` so rate limiting uses the forwarded client IP.
Popular patterns include Nginx, Traefik, Envoy, ALB/NLB, or Cloudflare Tunnel in front of `/mcp`.
### Option B: Native TLS termination in Node.js
The server terminates TLS itself via `node:https` — no proxy or extra dependency required.
```bash
MCP_HTTP_TLS_ENABLED=true
MCP_HTTP_TLS_CERT_PATH=/path/to/server.crt # PEM leaf cert (append intermediates for a full chain)
MCP_HTTP_TLS_KEY_PATH=/path/to/server.key # PEM private key
# Optional:
# MCP_HTTP_TLS_KEY_PASSPHRASE=... # for an encrypted key
# MCP_HTTP_TLS_MIN_VERSION=TLSv1.2 # default TLSv1.2
```
- Startup fails fast with a descriptive error if TLS is enabled and the cert or key path is missing or unreadable.
- Keep `MCP_HTTP_TRUST_PROXY=false` when clients connect directly.
- Certificate rotation requires a process restart; ACME/Let's Encrypt automation, mTLS client certificates, and an HTTP→HTTPS redirect listener are out of scope.
- In Docker Compose, mount the cert/key (e.g. `./certs:/app/certs:ro`, ignored by git) and set the paths to `/app/certs/...`; the `mcp-http` service passes the `MCP_HTTP_TLS_*` variables through.
Generate a self-signed certificate for local testing:
```bash
mkdir -p certs
openssl req -x509 -newkey rsa:2048 -nodes -days 365 \
-subj "/CN=localhost" \
-keyout certs/server.key -out certs/server.crt
```
Then verify with `curl --cacert certs/server.crt https://localhost:3000/healthz` (or `-k` for a quick check).
## Vault Production Migration (Raft)
The repository now includes a Vault production migration scaffold under [vault-production](vault-production):
- [vault-production/config/vault.hcl](vault-production/config/vault.hcl): Raft-backed Vault server configuration.
- [vault-production/docker-compose.vault-prod.yml](vault-production/docker-compose.vault-prod.yml): Compose definition for Vault in server mode (non-dev).
- [vault-production/scripts/convert-dev-to-prod.sh](vault-production/scripts/convert-dev-to-prod.sh): Script to export dev KV data, start Raft Vault, initialize/unseal, and import secrets.
- [vault-production/scripts/bootstrap-post-conversion.sh](vault-production/scripts/bootstrap-post-conversion.sh): Script to enable audit, write policy, configure AppRole, and emit service credentials.
- [scripts/vault-unseal-key.js](scripts/vault-unseal-key.js): Script to resolve unseal key from `VAULT_UNSEAL_KEY` or `src/config/vault.unseal.key.json`.
- [vault-production/README.md](vault-production/README.md): Detailed migration notes and options.
Managed unseal key flow:
- `VAULT_UNSEAL_KEY` is optional and can be injected at runtime.
- If `VAULT_UNSEAL_KEY` is not set, `npm run vault:unseal-key` reads `src/config/vault.unseal.key.json`.
- If the key file is missing or empty, a 24-character key is generated and saved to `src/config/vault.unseal.key.json`.
- Both compose stacks run a one-shot `vault-unseal-key-init` service before Vault startup to ensure key material exists.
Run the conversion:
```bash
bash vault-production/scripts/convert-dev-to-prod.sh --init-keys-out vault-production/backups/vault-init.json
```
Common options:
```bash
# Use a different KV mount
bash vault-production/scripts/convert-dev-to-prod.sh --mount secret
# Migrate infra only (skip data movement)
bash vault-production/scripts/convert-dev-to-prod.sh --skip-export --skip-import
# Use when Raft Vault is already initialized
bash vault-production/scripts/convert-dev-to-prod.sh --skip-init
# Explicitly set key file path used by convert script
bash vault-production/scripts/convert-dev-to-prod.sh --unseal-key-path src/config/vault.unseal.key.json
# Post-conversion hardening bootstrap (audit, policy, AppRole)
bash vault-production/scripts/bootstrap-post-conversion.sh --vault-token <root_or_admin_token>
# CI-friendly machine output
bash vault-production/scripts/bootstrap-post-conversion.sh \
--vault-token <root_or_admin_token> \
--output json
```
## Development Agent Docs
This repository retains the skeleton's project agent structure as development documentation for extending this MCP implementation:
- [agent/README.md](agent/README.md): Overview of agent assets.
- [agent/playbooks/service-onboarding.md](agent/playbooks/service-onboarding.md): Step-by-step onboarding checklist used when this adaptation was built.
- [agent/templates/service-spec.md](agent/templates/service-spec.md): Request template for describing service integration changes.
Use these when you want a coding agent to:
1. Extend the Eurostat adapter under `src/services`.
2. Register matching MCP tools in `src/mcp/server.js`.
3. Update env validation in `src/config/env.js`.
4. Preserve authorization and redaction behavior.
5. Add tests, regenerate the inventory, and update documentation.
## Test Coverage
Run everything locally with:
```bash
npm run inventory:check
npm test
```
Enable the version-controlled pre-push hook once per clone (required development setup); it runs the same checks and blocks a normal push when they fail:
```bash
npm run setup:hooks
```
Eurostat service tests in [tests/eurostat-service.test.js](tests/eurostat-service.test.js) cover (against a local mock upstream — no live Eurostat calls):
- Documented path/query construction for every API family (statistics, SDMX 2.1/3.0 data and structures, async, catalogue)
- Base-URL validation, `main`/`comext` server routing, and read-only method rejection
- Filter/dimension validation, upstream error propagation, bounded retries on 503, response-size limits with async-API guidance, timeouts, and gzip metabase decoding
- SBS dataset discovery filtering
Inventory tests in [tests/inventory.test.js](tests/inventory.test.js) cover:
- The committed official OpenAPI snapshot hash
- One-to-one spec-operation ↔ tool mapping (30/30, no duplicates or gaps)
- Read-only/public classification of every operation
- Registration of every mapped tool on the MCP server and deterministic artifact generation
Integration tests in [tests/server.integration.test.js](tests/server.integration.test.js) cover:
- Healthcheck behavior and registration of every documented endpoint tool
- Eurostat tool delegation to the service adapter
- Read-only tools working without `authorizationKey`; authorization gates on the generic mutating path
- Tool workflow suggestions, read-only upstream safety checks, and admin-authorization requirements
HTTP transport tests in [tests/http.integration.test.js](tests/http.integration.test.js) cover:
- Unauthorized requests are rejected
- Authorized MCP initialization succeeds
- Modern and legacy client tool calls
- Request-body size enforcement
- Health endpoint behavior
OAuth tests in [tests/oauth2.test.js](tests/oauth2.test.js) cover:
- Legacy and named-provider configuration, explicit startup validation, issuer routing, introspection checks, provider fallback/outages, and negative caching.
- Scope-map allowlists, required provider scopes, audience/expiry rejection, and successful cache entries bounded by token expiry.
- Scope/key authorization modes, no key fallback for missing OAuth scopes, and no admin-key injection into OAuth agent/composition calls.
- Real HTTP MCP mutation/admin/schedule calls without `authorizationKey`, mixed token callers retaining key gates, and effective authorization-mode reporting.
- Authentication method/scope persistence on durable task submission and replacement on resume.
Agent tests in [tests/agent.test.js](tests/agent.test.js) cover configuration/secret validation, scope and capability enforcement, Vault token administration/redaction, and A2A SDK/HTTP behavior. [tests/agent-postgres.integration.test.js](tests/agent-postgres.integration.test.js) adds opt-in live database migrations, config revision conflicts, scoped memory, checkpointed tool execution, idempotency, and resume coverage.
Vault token auth tests in [tests/vault-token-auth.test.js](tests/vault-token-auth.test.js) cover:
- Multi-user token index lookup by SHA-256 hash
- Inactive token rejection
- Missing required scope rejection, top-level index compatibility, and default-user fallback
Production migration tests in [tests/vault-production.test.js](tests/vault-production.test.js) cover:
- Presence of Vault production scaffold files
- Raft config expectations
- Non-dev Vault compose command validation
- Conversion/bootstrap script help and bash syntax checks
pg-boss tests in [tests/pgboss.test.js](tests/pgboss.test.js) cover (using an injected fake boss, no live Postgres required):
- Tool registration and catalog exposure (with and without the pg-boss service wired)
- Authorization gating of all mutating queue/job/schedule tools
- Read-only tools working without `authorizationKey`
- Credential/connection-string redaction in `pgboss_status` and connection info
- Lazy single start, graceful stop, disabled-mode 503s, 404s, and error propagation
- Cron/timezone/key passthrough for scheduling tools and job lifecycle API mapping
Scheduling tests in [tests/agent-schedules.test.js](tests/agent-schedules.test.js) and the updated [prerequisite tests](tests/agent-scheduling-prerequisites.test.js) cover:
- Trigger → transactional queue → fresh task → actual LangGraph/OpenAI-compatible fake endpoint/tool execution, restored account/tenant ownership, recurring fresh context IDs, and terminal replay protection.
- One-shot identity/reconciliation, manual request idempotency, transaction/crash rollback/recovery, legacy unqueued task repair, and concurrent overlap skipping.
- Stale/deleted/disabled/config-unavailable/revoked grant skips, grant rechecks at each tool call, all scheduling admin gates/discovery, real HTTP MCP owner filtering and strict schemas, secret rejection, real parser timezone/DST preview, and worker registration/shutdown.
- [tests/agent-schedules-postgres.integration.test.js](tests/agent-schedules-postgres.integration.test.js) exercises actual pg-boss/Postgres atomic rollback, registrations, runs/task joins, ownership, overlap, grants, and reconciliation when `MCP_AGENT_TEST_DATABASE_URL` is set to an isolated test database. Without that URL it is explicitly skipped, not live-DB verified.
## CI Automation
GitHub Actions runs inventory enforcement and the full test matrix via [.github/workflows/inventory-and-tests.yml](.github/workflows/inventory-and-tests.yml) on pushes, pull requests, and manual dispatch.
- The inventory job:
- installs dependencies reproducibly with `npm ci`
- runs `npm run inventory:generate` and `npm run inventory:check`
- fails on stale committed inventory artifacts, uncovered required operations, or missing/duplicate endpoint-to-tool mappings
- uploads a deterministic repository file inventory as a workflow artifact
- The test job runs `npm test` (workspace packages + application) and blocks merges when tests fail.
- The integration job starts a disposable Postgres 16 service, sets `MCP_AGENT_TEST_DATABASE_URL`, reruns the full suite so the opt-in agent/scheduler/pg-boss integration tests execute against a real database with the controlled local OpenAI-compatible inference server, and fails if those tests report as skipped. Vault behavior is verified by the deterministic Vault test suites (token index, lifecycle, agent runtime, production scaffold); no live Vault service is required in CI.
Local enforcement: run `npm run setup:hooks` once per clone to enable the committed [.githooks/pre-push](.githooks/pre-push) hook, which runs `npm run inventory:check` and `npm test` before every push. Branch protection/required status checks are a repository-settings step; configure them on `main` for the `Generate Inventory`, `Enforce Tests`, and `Postgres Integration` jobs when permissions allow.
## Extending This MCP
1. Extend the Eurostat adapter in [src/services/eurostatService.js](src/services/eurostatService.js) and keep the endpoint mapping in [src/services/eurostatEndpoints.js](src/services/eurostatEndpoints.js) as the single source of truth; regenerate the inventory after changes.
2. Register tools in [src/mcp/server.js](src/mcp/server.js) with schemas and catalog metadata so direct MCP, agent capabilities, and compositions share the executable handlers.
3. Reuse [runtime contracts](packages/runtime) for namespaces, scope, authenticated context, and redaction. Preserve tenant/principal ownership when adding persistence.
4. Use the shared scope/key authorization checks for mutations; admin-only operations require `mcp:admin` in scope mode. Keep `authorizationKey` optional in schemas for OAuth callers.
5. Store secrets in Vault and non-secret configuration in Postgres; redact outputs and execution events.
6. Wire new dependencies into both request processes and the worker when its capabilities use them. Add corresponding [tests](tests), capability documentation, and environment examples, and run `npm run inventory:check` before pushing.
## Notes
- docker-compose.yml now runs Vault with Raft-backed storage for local persistence.
- The managed key script is an automation helper and not a Vault KMS/HSM auto-unseal backend.
- The migration scaffold starts with bootstrap-friendly defaults and still requires TLS, production auth methods, and credential rotation before real production use.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues