Skip to main content
Glama

unido-indstat-mcp

A complete Node.js MCP server for the UNIDO Statistics Portal frontend and SDMX 3.0 APIs (INDSTAT, MVA, CIP, SDG 9 industry statistics), with tenant/principal-scoped persistence, multi-provider OAuth authorization, and durable agent execution. Built from the skeleton-mcp reference architecture.

  • API coverage: a dedicated MCP tool for every documented UNIDO API operation (49 operations across the frontend and SDMX OpenAPI documents) plus discovery, schema, and suggestion tools. See 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 documented UNIDO API is public and declares no security schemes, so no upstream API credentials are required. MCP transport authentication, tenant/principal authorization, Vault/Postgres persistence, and admin-key protection for mutating operations remain fully enforced. Infrastructure credentials in the examples require hardening before production use.

Skeleton Provenance And Naming

  • Source skeleton: https://github.com/LesterAJohn/skeleton-mcp at commit bfbf26a6939a3c3c387a34bd2461f1bb5d0b8eec (standalone repository mode; no git-level fork relationship).

  • Repository name (unido-indstat-mcp on GitHub) identifies the repository only. MCP_SERVER_NAME (deployment default: unido-indstat-mcp) is the single runtime namespace source: it derives the server identity, Vault paths (unido-indstat-mcp/...), Postgres config/agent tables and schemas (unido_indstat_mcp...), LangGraph checkpoint schema, pg-boss schema, and queue names.

  • Changing MCP_SERVER_NAME changes the persistence namespace and requires an explicit migration plan (see npm run vault:migrate-namespace and the legacy APP_NAME migration notes). Never rename it silently on a live deployment.

  • MCP_SERVER_NAME validation: lowercase letters, digits, -/_, bounded length, normalized to the Postgres namespace unido_indstat_mcp; collisions with differently-spelled names that normalize identically are rejected at startup.

Related MCP server: portco-mcp

Start Here

Purpose

This repository exposes the UNIDO Statistics Portal APIs through secure MCP tools and provides:

  • Multi-user support.

  • Secret reads and writes through Vault

  • Config reads and writes through Postgres

  • Tool-level authorization for mutating operations

  • Redacted tool output by default

  • Basic reliability controls for external secret writes

  • Explicit timeouts and bounded retries for upstream UNIDO API calls

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.

Supported upstream API surface (committed OpenAPI documents, version 1.0):

UNIDO API Coverage And Inventory

Every documented callable operation has a dedicated unido_* MCP tool (100% required coverage; no approved exclusions). The generated inventory is the single source of truth for endpoint-to-tool mappings, classifications, parameter schemas, and test mappings:

npm run inventory:generate   # regenerate inventory/unido-operations.json + inventory/COVERAGE.md from docs/
npm run inventory:check      # verify committed inventory is fresh, unique, valid, and 100% covered
  • Deterministic and fully offline: both commands read only the committed OpenAPI documents under docs/ — CI never downloads live documentation.

  • Operations are deduplicated by HTTP method + normalized path across the two source documents.

  • Classification is behavior-based, not method-based: the three POST /dataset/get* operations are read-only queries submitted via POST bodies; POST /dataset/download/{xls,csv}/prepare are mutating because they create server-side export artifacts and therefore require admin authorization (authorizationKey or mcp:write/mcp:admin).

  • inventory:check fails on stale output, duplicate or invalid tool names, missing test mappings, and uncovered required operations. CI and the pre-push hook run it on every change.

Capabilities At A Glance

Area

Included capabilities

Configuration / boundary

Service integration

Dedicated unido_* tools for all 49 documented UNIDO operations, schema discovery (unido_operation_schema), endpoint listing, connection metadata, generic fallback requests, and suggested tool workflows

The adapter is src/services/unidoService.js; tools are generated from inventory/unido-operations.json via src/mcp/unidoTools.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

The skeleton now 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, target-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:

npm test

Run them independently with npm run test:packages or npm run test:app.

Skeleton Architecture

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[Target-service 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, 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, 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, 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, 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, target-service 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

For MCP_SERVER_NAME=unido-indstat-mcp, application tables use the unido_indstat_mcp_ prefix, checkpoint and queue schemas are unido_indstat_mcp_langgraph and unido_indstat_mcp_pgboss, and Vault paths begin with unido-indstat-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 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 runs the MCP HTTP process and dedicated agent worker against externally managed Postgres and Vault.

  • 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.

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 the skeleton's Vault/Postgres architecture:

Package

Platform behavior

Upstream OAuth

Billing

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 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 skeleton upstreams, 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:

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. Never configure /a2a as an MCP server URL.

For local development, stdio is the simplest option:

{
	"mcpServers": {
		"unido-indstat-mcp": {
			"command": "npm",
			"args": ["run", "start:stdio"],
			"cwd": "/Users/lesterjohn/Documents/GitHub/unido-indstat-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

[mcp_servers.unido-indstat-mcp]
command = "npm"
args = ["run", "start:stdio"]
cwd = "/absolute/path/to/unido-indstat-mcp"

For HTTP, start the HTTP process and use this entry instead:

[mcp_servers.unido-indstat-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.

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:

{
	"mcpServers": {
		"unido-indstat-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. For direct A2A rather than MCP tools, follow 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

{
	"mcpServers": {
		"unido-indstat-mcp": {
			"command": "npm",
			"args": ["run", "start:stdio"],
			"cwd": "/Users/lesterjohn/Documents/GitHub/unido-indstat-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 unido-indstat-mcp http://127.0.0.1:3000/mcp; configure its bearer credentials privately as described in the Claude Code MCP documentation. This is still MCP, not A2A. See Claude Code / Claude Desktop for the A2A route and Desktop limitations.

Connect Codex, Claude, And VS Code To The Agent Via A2A

The skeleton is the remote agent; Codex, Claude, or Copilot is the calling assistant. A2A submits a goal to the skeleton'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: initialize/unseal Vault and configure Postgres, valid Vault credentials, and the target service.

  2. Set MCP_AGENT_WORKER_ENABLED=true for both server and worker, configure HTTP bearer authentication, and start both processes:

    # 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 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). 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:

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:

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 target service 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:

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:

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; the skeleton 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:

    Delegate a read-only service-health goal to the skeleton 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 skeleton'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, Claude Code MCP, and VS Code MCP. These describe MCP configuration; the A2A wire examples above are grounded in this repository's A2A adapter and protocol tests.

Tool Catalog

All tools return MCP text content containing JSON. Success payloads follow this shape:

{
	"ok": true,
	"status": 200,
	"data": {}
}

Errors follow this shape and set MCP isError=true:

{
	"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.

Configure the admin key

MCP_ADMIN_AUTH_KEY is not generated automatically. Generate a random value locally:

openssl rand -hex 32

Set the generated value in your local .env or deployment secret/environment configuration:

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:

{
  "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|dataset_query|download_export|country_profile|cip|sdg|latest_trends|sdmx|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:

{
	"name": "service_query_suggestion",
	"arguments": {
		"intent": "prepare and download an INDSTAT XLS export",
		"operationType": "download_export",
		"method": "POST",
		"path": "/dataset/download/xls/prepare"
	}
}

Intent

Suggested tool sequence

Notes

Verify runtime and service connectivity

service_connection_info -> service_health_check

Baseline check before any operational request.

Discover documented operations and schemas

service_connection_info -> service_list_endpoints -> unido_operation_schema

Returns schema-valid example calls without executing them.

Query dataset observations

unido_dataset_get_dataset_by_type -> unido_dataset_get_data

Resolve dataset metadata (countries, variables, periods) before the POST-body query.

Prepare and download an export

unido_dataset_download_xls_prepare (or ..._csv_prepare) -> unido_dataset_download_check_by_file_name -> unido_dataset_download_by_file_name

Prepare is mutating: OAuth mcp:write/mcp:admin, or authorizationKey in key mode.

Read a country profile

unido_country_profile_countries -> unido_country_profile_by_country_code

Related group lists: unido_country_profile_{regions,income_groups,economic_groups,unido_groups}.

CIP scores and hierarchy

unido_cip_hierarchy -> unido_cip_data_by_country_code -> unido_cip_cip_score_by_code_by_year

All CIP tools are read-only.

SDG 9 industry indicators

unido_sdg_countries -> unido_sdg_by_country_code -> unido_sdg_sdg_score_by_code_by_year

Radar/compare variants: unido_sdg_sdg_radar_scores_by_code, unido_sdg_compare_to.

SDMX machine-readable access

unido_sdmx_dataflow_by_flow_id_by_version -> unido_sdmx_datastructure_by_flow_id_by_version -> unido_sdmx_data_by_flow_id_by_version_by_key

SDMX 3.0 flows published by UNIDO.

Execute a generic request

service_list_endpoints -> service_api_request

Only for paths without a dedicated unido_* tool; mutating methods require admin authorization.

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 + target-service connection metadata (server name/version, auth-gate status, scope model, service base URL/timeout)

  • 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:

{
	"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:

{
	"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:

{
	"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: network path to target service 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 target service is down/unreachable

    • 401/403 when upstream service credentials are invalid

  • Recommended tools:

    • Prerequisite: service_connection_info

    • Follow-up: service_list_endpoints, service_api_request

  • Example:

{
	"name": "service_health_check",
	"arguments": {}
}

UNIDO API tools (unido_*)

Every documented UNIDO operation has a dedicated tool generated from inventory/unido-operations.json. The complete endpoint-to-tool table lives in inventory/COVERAGE.md; exact parameter schemas and schema-valid examples are returned by unido_operation_schema.

Tool families:

  • unido_dataset_* — dataset metadata (unido_dataset_get_dataset_by_type, unido_dataset_get_dataset_by_type_by_revision), observation queries (unido_dataset_get_data, unido_dataset_get_data_without_activities, unido_dataset_get_cip_data), metadata lookups (unido_dataset_get_country_metadata_by_dataset_id_by_country_code, unido_dataset_get_variable_metadata), and the export pipeline (unido_dataset_download_xls_prepare, unido_dataset_download_csv_prepare, unido_dataset_download_check_by_file_name, unido_dataset_download_by_file_name).

  • unido_country_profile_*, unido_latest_trends_*, unido_sdg_*, unido_cip_* — country profiles, latest trends, SDG 9 indicators, and CIP index data plus region/income/economic/UNIDO group lists.

  • unido_sdmx_* — SDMX 3.0 dataflow, data structure, metadata structure, metadata, and data retrieval.

Shared behavior:

  • Classification: all tools are read-only except unido_dataset_download_xls_prepare and unido_dataset_download_csv_prepare, which create server-side export artifacts and are mutating/idempotency-unsafe. Mutating tools require mcp:write/mcp:admin (OAuth) or authorizationKey (key mode) and carry an explicit warning in their descriptions.

  • Identity/environment: the upstream API is public and global; tools never forward MCP credentials upstream. The target host is fixed by UNIDO_API_BASE_URL (default https://stat.unido.org/portal), preventing arbitrary credential or request forwarding.

  • Reliability: explicit request timeout (UNIDO_API_TIMEOUT_MS), bounded retries for idempotent GETs on 429/502/503/504 and transient network errors (UNIDO_API_MAX_RETRIES, UNIDO_API_RETRY_DELAY_MS); non-GET operations are never retried automatically.

  • Responses: data contains method, path, url, status, contentType, attempts, and the parsed upstream payload. Non-JSON payloads (SDMX XML, CSV/XLS downloads) are returned as text; unido_dataset_download_by_file_name can return large non-JSON content, so call unido_dataset_download_check_by_file_name first.

  • Common failures: 400 missing/invalid parameters (validated before any network call), 404 unknown resource (for example an unprepared export file), 429 upstream rate limiting, 5xx/504 upstream failures or timeout.

Example — read-only query with a POST body:

{
	"name": "unido_dataset_get_data",
	"arguments": {
		"body": {
			"datasetId": 0,
			"countryCode": "<countryCode>",
			"variableCode": "<variableCode>",
			"periods": ["<period>"]
		}
	}
}

Example — mutating export preparation (admin authorization required):

{
	"name": "unido_dataset_download_xls_prepare",
	"arguments": {
		"body": { "datasetId": 0, "countryCodes": ["<countryCode>"] },
		"authorizationKey": "<admin-key-if-required>"
	}
}

unido_operation_schema

  • Category: read-only discovery

  • Risk: low

  • Use when: you need the exact parameter schema, enums, classification, permissions, and a schema-valid example for one documented operation before calling it

  • Do not use when: you already validated the call shape; invoke the dedicated tool directly

  • Parameters: toolName (string), or method + path (documented template form, for example /sdg/{countryCode})

  • Expected response shape: data.operation (full inventory entry: source, method, path, operationId, parameters, requestBody, responses, classification) and data.exampleCall (schema-valid, placeholder-based; never executed)

  • Common failures: 400 when neither toolName nor method+path is provided; 404 when no documented operation matches

  • Follow-up: the dedicated unido_* tool from data.exampleCall.tool

{
	"name": "unido_operation_schema",
	"arguments": { "toolName": "unido_sdmx_data_by_flow_id_by_version_by_key" }
}

service_api_request

  • Category: read-only or mutating (depends on method)

  • Risk: variable; high for POST|PUT|PATCH|DELETE

  • Use when: you need flexible access to supported UNIDO endpoints not covered by dedicated tools (there are currently none; all documented operations have dedicated unido_* tools)

  • Do not use when: a dedicated unido_* tool exists, because those provide validated schemas, behavior-based classification, and safer contracts

  • Required permissions/prerequisites:

    • Mutating methods require mcp:write or mcp:admin for OAuth scope authorization, or authorizationKey if using a configured admin key

    • path must target valid adapter-supported route behavior

  • Environment behavior:

    • method is normalized to uppercase

    • path is normalized to leading slash format

    • auth and host safeguards are enforced by adapter

  • Parameters:

    • method (required string, e.g. GET, POST)

    • path (required string; /-prefixed normalization applied)

    • query (optional object: string keys, scalar values string|number|boolean)

    • body (optional JSON value)

    • headers (optional object: string keys and string values)

    • authorizationKey (optional unless mutating call requires it)

  • Expected response shape:

    • data: adapter HTTP response payload

  • Common failures:

    • 400 invalid path/query/body for upstream API

    • 401 invalid/missing authorizationKey for required mutating call

    • 403 upstream access denied

    • 404 endpoint/resource not found

    • 429 upstream rate limiting

    • 5xx upstream/transport failure

  • Safety warning: treat mutating methods as destructive-capable operations; verify target path, method, and body before invocation

  • Recommended tools:

    • Prerequisite: service_list_endpoints, service_health_check

    • Follow-up: specialized read tools for validation, or another service_api_request GET for post-change verification

  • Examples:

{
	"name": "service_api_request",
	"arguments": {
		"method": "GET",
		"path": "/countryProfile/countries"
	}
}
{
	"name": "service_api_request",
	"arguments": {
		"method": "POST",
		"path": "/dataset/download/csv/prepare",
		"body": {
			"datasetId": 0
		},
		"authorizationKey": "<admin-key-if-required>"
	}
}

pg-boss Queue And Scheduling Tools

The skeleton embeds 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:

{
	"name": "pgboss_schedule",
	"arguments": {
		"name": "nightly-report",
		"cron": "0 3 * * *",
		"data": { "reportType": "daily" },
		"options": { "tz": "America/Chicago", "retryLimit": 2 },
		"authorizationKey": "<admin-key-if-required>"
	}
}
{
	"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>"
	}
}
{
	"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 unido_indstat_mcp_agent_config) with append-only revisions. A valid configuration has this shape:

{
  "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_credential_set, agent_credential_rotate

Admin-authorized creation/update and rotation of tenant/principal-scoped inference credentials in Vault under ${MCP_SERVER_NAME}/inference/<tenant>/<principalType>/<principal>/<name>; return the credentialRef for agent_config_set and metadata (version, createdAt, rotatedAt); never echo the secret.

agent_credential_delete

Admin-authorized deletion of a scoped inference credential; configs referencing the deleted credentialRef fail connection tests and task execution until reconfigured.

agent_credential_inspect

Admin-authorized redacted metadata inspection (secretConfigured, version, timestamps); never returns secret values.

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.

Fresh deployment and MCP-based inference setup

A fresh deployment with healthy Vault and Postgres but no inference configuration starts all MCP transports, configuration tools, pg-boss, and workers. agent_config_get reports exists: false; agent goal/status/resume/cancel tools remain disabled and inference-dependent requests (including A2A goals and scheduled tasks) are rejected with actionable 503 errors stating that configuration is missing or disabled. Infrastructure readiness (pgboss_health, service_connection_info) is reported separately from inference readiness (agent_config_get, agent_config_test_connection). No provider fallback or fabricated credentials exist.

An authorized operator makes the deployment execution-ready entirely through MCP tools — no code change or rebuild:

  1. service_query_suggestion / agent_config_validate — discover the configuration schema and supported capability names (any registered tool name, for example unido_country_profile_countries).

  2. agent_credential_set with { "name": "<provider>", "apiKey": "<secret>" } — store the inference credential in scoped Vault storage; note the returned credentialRef.

  3. agent_config_validate — validate protocol (openai-compatible), endpoint URL safety, limits, capabilities, and memory settings without any network call.

  4. agent_config_set with the validated config (inference.baseUrl, inference.model, credentialRef, instructions, permittedCapabilities, token/time/tool-call/step limits, memory policy), enabled: true, expectedRevision: 0.

  5. agent_config_test_connection — explicit live connectivity test against the configured endpoint's /models (network activity; may incur provider cost).

  6. agent_goal with a non-destructive verification goal (for example "call service_health_check"), then agent_task_status until terminal — verifies worker consumption, checkpointing, and persistence.

  7. Later: agent_config_update for changes and agent_credential_rotate for credential rotation; agent_config_delete/agent_credential_delete disable execution (already-submitted tasks are not auto-canceled; schedules skip with recorded prerequisite errors).

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 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:

  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:

{"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:

# 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 unido-indstat-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

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)

  • 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

UNIDO Statistics Portal API (public upstream; no credentials):

  • UNIDO_API_BASE_URL (default https://stat.unido.org/portal; must be an absolute http(s) URL — all tool requests are restricted to this host)

  • UNIDO_API_TIMEOUT_MS (default 30000; per-request timeout)

  • UNIDO_API_MAX_RETRIES (default 2; bounded retries for idempotent GETs on 429/502/503/504 and transient network errors; non-GETs are never retried)

  • UNIDO_API_RETRY_DELAY_MS (default 500; linear backoff base delay)

  • UNIDO_API_HEALTH_PATH (default /countryProfile/countries; documented lightweight endpoint used by service_health_check — the probe performs a live HTTP request)

Naming defaults:

  • MCP_SERVER_NAME defaults to unido-indstat-mcp. Postgres names normalize punctuation to underscores (for example unido_indstat_mcp_config); Vault paths use the MCP name prefix (for example unido-indstat-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.

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 to a local .env; configure your target-service connection and authentication. 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:

docker exec -e VAULT_ADDR=http://127.0.0.1:8200 unido-indstat-mcp-vault vault operator init -key-shares=1 -key-threshold=1 -format=json
docker exec -e VAULT_ADDR=http://127.0.0.1:8200 unido-indstat-mcp-vault vault operator unseal <unseal_key_returned_by_vault_init>
  1. 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.

  2. 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, 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. 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.

  1. 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:

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 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:

# 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 the skeleton 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, target-service, and Vault settings. The supported production shape is docker-compose.external.yml against managed Postgres and Vault (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

MCP_ADMIN_AUTH_KEY

Generated secret (openssl rand -hex 32) in deployment secrets

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 HTTP Token Seeding

OAuth client secrets

Deployment secrets, never committed files; HTTPS introspection endpoints

OAuth providers

Upstream API credentials

None required — the documented UNIDO API is public and declares no security schemes

UNIDO API Coverage And Inventory

Inference credentials

Vault KV under ${MCP_SERVER_NAME}/<credentialRef>, configured post-deploy via agent config tools

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.

  • 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) 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 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); 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

  • Target-service production credentials set; inference credential stored in Vault

  • 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.

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

Complete accepted-scope contract for this MCP. The upstream UNIDO API is public and defines no OAuth scopes of its own, so no service-specific upstream scopes exist; all scopes below are MCP-level scopes verified via HTTP OAuth introspection (or recorded in Vault token-index entries for bearer tokens).

Scope

Purpose

Required authentication mode

Permitted tool/operation classes

Class

mcp:invoke (or mcp:agent)

Agent execution and baseline HTTP admission (default MCP_HTTP_VAULT_TOKEN_REQUIRED_SCOPES)

HTTP bearer (Vault token index) or OAuth introspection

Submit/read/resume/cancel agent tasks, run compositions, A2A goal/task access, all read-only tools

Read-only + agent execution

mcp:read

Descriptive read scope; read tools do not add per-tool gates. Restrict HTTP admission with provider REQUIRED_SCOPES as needed

OAuth introspection

Read-only unido_* tools, discovery tools, config/pgboss reads

Read-only

mcp:write

Mutating service and configuration operations

OAuth introspection (scope mode); other callers use authorizationKey

unido_dataset_download_xls_prepare/..._csv_prepare, mutating service_api_request, config_set/config_delete, mutating pgboss_*

Mutating

mcp:admin

Full administration

OAuth introspection (scope mode); other callers use authorizationKey with configured MCP_ADMIN_AUTH_KEY

All write capabilities plus Vault token seed/lifecycle/sink inspection, agent config set/update/delete/test, inference credential lifecycle (agent_credential_*), memory writes, schedule/grant mutations/manual runs/previews

Admin-only

mcp:tenancy:admin

Delegated tenant/user/account directory administration limited to the authenticated tenant or allowedTenantIds

OAuth introspection

tenancy_* tools, tenant/user token seeding

Admin-only (tenant-bounded)

mcp:proxy:initialize

Initialize the trusted Apify or MCPize caller in its fixed platform tenant

Trusted proxy identity headers

proxy_user_initialize only

Mutating (self-scope only)

mcp:agent-config:admin

Cross-user agent configuration administration in an authorized tenant

OAuth introspection

agent_config_user_* tools

Admin-only (tenant-bounded)

HTTP OAuth authorization requires the provider-mapped scopes above; client registration should request at least mcp:invoke plus mcp:read for read-only use, adding mcp:write or mcp:admin for mutating/administrative capabilities. A raw bearer token or authorizationKey alone never substitutes for mcp:admin/mcp:write in oauth-scopes mode.

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.

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:

{
	"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:

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:

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

The skeleton 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 skeleton 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:

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.

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.

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:

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:

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 vault-production/scripts/convert-dev-to-prod.sh --init-keys-out vault-production/backups/vault-init.json

Common options:

# 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

Service Onboarding Assets

This repository keeps the skeleton's onboarding assets for extending the server with additional service-backed MCP integrations:

To build another service-specific MCP repository, use the Build Service MCP prompt in the upstream skeleton: https://github.com/LesterAJohn/skeleton-mcp.

Test Coverage

UNIDO coverage tests in tests/unido-tools.test.js cover:

  • Inventory freshness (inventory:check) and 100% endpoint-to-tool registration for all 49 documented operations

  • Schema-valid, never-executed example calls from discovery tooling (unido_operation_schema)

  • Path/query/body mapping, URL-encoded path templating, and required-parameter validation

  • Admin authorization on the mutating export-prepare tools (missing, invalid, and valid keys)

  • Real UnidoServiceClient behavior against a mocked upstream server: health probe, GET/POST operations, bounded retries on 503, 404 error mapping, and timeout handling

Inference credential lifecycle tests in tests/agent-credentials.test.js cover:

  • Admin gating, scoped Vault paths derived from MCP_SERVER_NAME, create/rotate/delete/inspect flows, 404 behavior, and redaction (secret values never appear in responses)

Integration tests in tests/server.integration.test.js cover:

  • Healthcheck behavior

  • Authorization on mutating tools

  • Tool workflow suggestions and admin-authorization requirements

HTTP transport tests in 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 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 cover configuration/secret validation, scope and capability enforcement, Vault token administration/redaction, and A2A SDK/HTTP behavior. 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 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 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 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 and the updated prerequisite tests 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 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 and test enforcement via .github/workflows/inventory-and-tests.yml.

  • The inventory job:

    • runs npm run inventory:generate fully offline from the committed docs/ OpenAPI documents (no live documentation downloads)

    • fails if generation changes tracked files (stale committed inventory) and runs npm run inventory:check for structural/coverage validation

    • always uploads a deterministic repository file inventory as a workflow artifact

  • The test job runs npm test (workspace packages plus the application suite) and blocks merges when tests fail.

  • The integration job starts disposable Postgres and Vault service containers and runs the full suite with MCP_AGENT_TEST_DATABASE_URL set, so the Postgres agent and scheduling integration tests execute for real (not skipped). It fails when the required services are unavailable. Controlled inference uses a local OpenAI-compatible test server inside the tests; no real provider or credential is used.

Pre-push hook

A version-controlled pre-push hook at .githooks/pre-push runs npm run inventory:check and npm test and blocks the push on failure. Enable it once per clone as part of development setup:

npm install
npm run hooks:install   # sets git config core.hooksPath .githooks

Do not bypass failed checks (git push --no-verify) except for emergency documented procedures. Branch protection/required status checks should additionally be configured on GitHub where permissions allow.

Extend This Server

  1. Add domain adapters under src/services; keep the reference bootstrap and dependency wiring explicit.

  2. Register tools in src/mcp/server.js with schemas and catalog metadata so direct MCP, agent capabilities, and compositions share the executable handlers.

  3. Reuse runtime contracts 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, capability documentation, and environment examples.

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.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      C
      maintenance
      Enables enterprise multi-agent decision workflows that expose 8+ MCP tools such as SQL query, web search, Python sandbox, RAG, file access, data cleaning, chart generation, and HTTP calls, orchestrated with LangGraph, streaming output, and human-in-the-loop approvals.
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      A typed stdio/HTTP MCP server that lets agents drive governed portfolio-company data onboarding: profiling sources, inferring entities and joins, proposing canonical mappings, generating and sandbox-testing dbt artifacts, and publishing only human-certified results. It exposes agent and reviewer-only tools, tenant-scoped run/ontology/evidence resources, and guided prompts, keeping every calculation deterministic and every approval with a human.
      12
      MIT
    • A
      license
      C
      quality
      C
      maintenance
      It exposes business-logic services as MCP tools over streamable HTTP (stdio also supported), auto-registering each service so agents can invoke it through the same Pydantic contracts used by the bundled CLI and HTTP API. It also supports OAuth, per-call pricing, and optional UI enhancers for elicitation, image output, and dashboards.
      58
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables MCP-compatible clients to access model registry, prediction logging, drift detection, bias/fairness auditing, compliance and governance queries, explanation generation, LLM/RAG monitoring, content safety, alert management, multi-agent workflow tracking, and performance metrics through 197 tools across 18 domains. Supports stdio and hosted Streamable HTTP transports, plus MCP Apps interactive audit cards.
      52 PyPI
      MIT