unido-indstat-mcp
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
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-mcpon 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_NAMEchanges the persistence namespace and requires an explicit migration plan (seenpm run vault:migrate-namespaceand the legacyAPP_NAMEmigration notes). Never rename it silently on a live deployment.MCP_SERVER_NAMEvalidation: lowercase letters, digits,-/_, bounded length, normalized to the Postgres namespaceunido_indstat_mcp; collisions with differently-spelled names that normalize identically are rejected at startup.
Related MCP server: portco-mcp
Start Here
Hosted MCP proxies for Apify and MCPize deployment
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 Statistics Portal frontend API — docs/unido-api-openapi.json, official source https://stat.unido.org/portal/v3/api-docs/api (44 operations).
UNIDO SDMX 3.0 API — docs/unido-sdmx-openapi.json, official source https://stat.unido.org/portal/v3/api-docs/sdmx (5 operations).
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% coveredDeterministic 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}/prepareare mutating because they create server-side export artifacts and therefore require admin authorization (authorizationKeyormcp:write/mcp:admin).inventory:checkfails 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 | The adapter is src/services/unidoService.js; tools are generated from inventory/unido-operations.json via src/mcp/unidoTools.js. |
MCP access | Stdio, HTTP |
|
OAuth and tool authorization | Named introspection providers, issuer/audience/scope checks, per-provider scope mapping, bounded expiry-aware token caches |
|
Data and secrets | Scoped config tools, Vault token seeding/lifecycle/sink inspection, rotation-interval resolution, and redacted outputs |
|
Queue operations | pg-boss queue/job management, scheduling, lifecycle controls, and status tools | Generic |
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 | 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:
A reference application plus reusable contracts: common primitives are extracted into workspace packages while the complete integration remains visible in the root application.
MCP-name-derived persistence: configuration and agent data use versioned, namespaced Postgres objects; Vault paths use the MCP name prefix. Legacy
APP_NAMEis a migration source, not the current namespace setting.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.
OAuth scopes instead of per-call admin secrets: verified OAuth callers use
mcp:writefor regular mutations andmcp:adminfor administration in the defaultautomode. Provider scope maps and durable authentication provenance keep this policy consistent across direct tools, compositions, and workers.Delegated administration instead of one global admin:
mcp:tenancy:adminmanages tenants, tenant users/accounts, and token seeding, whilemcp:agent-config:adminmanages other users' agent configurations — each bounded to the caller's authenticated tenant or token-declaredallowedTenantIds, with atomic actor/target audit records.mcp:adminremains 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 |
| namespace derivation, tenant/principal scope, authenticated context, redaction | service bootstrap, tools, transports, Vault/Postgres services |
| explicit worker activation and queue/checkpoint/scheduling prerequisites | LangGraph engine, A2A handler, pg-boss worker, scheduling implementation |
| 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 testRun 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 --> REGISTRYProcess Boundaries
Process | Entry point | Responsibility |
MCP stdio | src/index.js, | Serve MCP tools using local/default principal context. The entry point also honors |
MCP HTTP + A2A | src/http/index.js, | 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, | 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, | 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
src/config/env.js validates environment settings; src/services/runtime.js wires Postgres, Vault, pg-boss, and the target-service client.
packages/runtime supplies namespace, scope, authenticated-context, and redaction primitives. src/services/configStore.js implements the application's migrations and scoped persistence.
src/http/oauth2.js verifies provider access tokens; src/auth/authorization.js selects scope/key authorization; src/mcp/server.js applies that policy to direct tool calls.
src/agent/toolRegistry.js validates agent/composition inputs and limits runnable capabilities; src/agent/engine.js restores the task's tenant/principal, authentication method, and granted scopes before invoking tools.
src/services/vault.js resolves secrets and serializes/retries secret writes; src/services/security.js preserves redacted output behavior.
packages/agent-runtime validates worker prerequisites; it does not contain the root application's LangGraph, A2A, or scheduling implementation.
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 Server Actor with Streamable HTTP | 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 container HTTP service with | Publisher-managed bearer token stored with | MCPize gateway manages subscriptions/usage; optional x402 per-tool pricing belongs in |
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.tomlTransport: 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.jsonTransport: 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
/a2ainserts 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/a2atask 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, andstateTransitionHistory: true, so A2A clients either pollGetTaskwith the returned task id or omitconfiguration.returnImmediatelyto stream status updates on the submission call (bounded server-side wait); webhooks are not available. MCP callers seeagent_goaldescribed as asynchronous; it returns202with the submitted task plus anextActionhint directing them to pollagent_task_status.
Connection | Endpoint | What it provides |
MCP registration |
| Tools, including |
A2A discovery |
| Public Agent Card describing the JSON-RPC binding and endpoint. |
A2A delegation |
| 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
Complete infrastructure setup: initialize/unseal Vault and configure Postgres, valid Vault credentials, and the target service.
Set
MCP_AGENT_WORKER_ENABLED=truefor 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-workerStore the inference credential in Vault and use the agent configuration tools to create an enabled config for the calling token's tenant/principal. Set
permittedCapabilitiesto the required registered tools (for the example below, includeservice_health_check). The server and worker must share the same application/pg-boss database. Config administration requires OAuthmcp:adminin scope mode or the configured admin key in key mode.Give the caller a valid access token. OAuth or Vault-index identities need
mcp:invokeormcp:agentfor A2A admission; addmcp:writefor ordinary mutating capabilities ormcp:adminfor admin capabilities. Legacy key-authorized agent mutations additionally requiremcp:adminwhen an admin key is configured. A2A requests do not pass anauthorizationKeyargument. Static tokens without identity metadata use the default principal, so prefer a verified scoped identity for multi-user access.For remote deployment, set
MCP_A2A_PUBLIC_URL=https://your-agent.example/a2aso the card advertises the reachable endpoint, and terminate TLS at a trusted proxy or natively viaMCP_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_TOKENInspect 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
Prepare the remote agent and verify discovery/submission in the terminal above.
For Codex CLI, launch
codexfrom the shell containingA2A_BASE_URLandA2A_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.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.Verify that Codex used
/a2aand 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
For Claude Code, launch
claudefrom the prepared shell so approved terminal commands can inheritA2A_BASE_URLandA2A_TOKEN.Use the same delegation instruction above and approve the endpoint/terminal access as appropriate. Confirm
SendMessageandGetTaskcalls, not just an Agent Card fetch or an MCPagent_goalcall.For Claude Desktop, the
claude_desktop_config.jsonentry registers MCP only. It cannot turn/a2ainto an MCP server. If Desktop has no approved A2A/HTTP tool integration, use this skeleton's MCPagent_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
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.
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.
If the selected harness cannot reach the endpoint or read the token securely, execute the requests yourself in the prepared terminal.
.vscode/mcp.jsonor.mcp.jsonentries are MCP registrations, not native A2A attachment.If you want ordinary tool integration rather than direct A2A, register
/mcpthrough MCP: Add Server, enable the agent tools, and callagent_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:invokeormcp:agent;mcp:adminalone 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:bothdoes 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, andCancelTaskmethods, 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 32Set 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
operationTypeormethodReports the caller's effective authorization mode and whether
authorizationKeyis 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, defaulttrue)includeToolSchemas(optional boolean, defaulttrue)
Expected response shape:
data.summary: intent + mutating/auth flagsdata.recommendedOrder: ordered tool recommendations with reasonsdata.safetyChecks: checklist for safer executiondata.toolSchemas: schema-like catalog for all operational tools (unless disabled)data.examples: baseline read/mutate examples (unless disabled)
Common failures:
500for 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"
}
}Recommended Playbooks
Intent | Suggested tool sequence | Notes |
Verify runtime and service connectivity |
| Baseline check before any operational request. |
Discover documented operations and schemas |
| Returns schema-valid example calls without executing them. |
Query dataset observations |
| Resolve dataset metadata (countries, variables, periods) before the POST-body query. |
Prepare and download an export |
| Prepare is mutating: OAuth |
Read a country profile |
| Related group lists: |
CIP scores and hierarchy |
| All CIP tools are read-only. |
SDG 9 industry indicators |
| Radar/compare variants: |
SDMX machine-readable access |
| SDMX 3.0 flows published by UNIDO. |
Execute a generic request |
| Only for paths without a dedicated |
Inspect tenant/principal scope metadata |
| 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_checkorservice_list_endpointsRequired permissions/prerequisites: none
Environment behavior: reports current process config (
MCP_SERVER_NAME, default tenant/user/account scope, admin-auth configured state, andMCP_AUTHZ_MODE) plus the caller's effective scope/key authorization modeParameters: none
Expected response shape:
data.server: server metadata,scopeModel, configuredauthzMode, effectiveauthorizationMode, andadminAuthConfigureddata.service: service client connection info
Common failures:
500if 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_infoalready includes default scope modelRequired permissions/prerequisites: none
Environment behavior: requires
tenantIdplus exactly one ofuserIdoraccountIdParameters:
tenantId(required string, non-empty)userId(optional string, non-empty)accountId(optional string, non-empty)
Expected response shape:
data.appNamedata.tenantIddata.tenantIdPathSegmentdata.principalTypedata.principalIddata.principalIdPathSegmentdata.userIdordata.accountIddata.postgres.tableName,data.postgres.primaryKey,data.postgres.scopedata.vault.tokenIndexPath,data.vault.scope
Common failures:
500for 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_checkRequired 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:
500if endpoint catalog cannot be produced
Recommended tools:
Prerequisite:
service_connection_infoFollow-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:
5xxif target service is down/unreachable401/403when upstream service credentials are invalid
Recommended tools:
Prerequisite:
service_connection_infoFollow-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_prepareandunido_dataset_download_csv_prepare, which create server-side export artifacts and are mutating/idempotency-unsafe. Mutating tools requiremcp:write/mcp:admin(OAuth) orauthorizationKey(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(defaulthttps://stat.unido.org/portal), preventing arbitrary credential or request forwarding.Reliability: explicit request timeout (
UNIDO_API_TIMEOUT_MS), bounded retries for idempotent GETs on429/502/503/504and transient network errors (UNIDO_API_MAX_RETRIES,UNIDO_API_RETRY_DELAY_MS); non-GET operations are never retried automatically.Responses:
datacontainsmethod,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_namecan return large non-JSON content, so callunido_dataset_download_check_by_file_namefirst.Common failures:
400missing/invalid parameters (validated before any network call),404unknown resource (for example an unprepared export file),429upstream rate limiting,5xx/504upstream 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), ormethod+path(documented template form, for example/sdg/{countryCode})Expected response shape:
data.operation(full inventory entry: source, method, path, operationId, parameters, requestBody, responses, classification) anddata.exampleCall(schema-valid, placeholder-based; never executed)Common failures:
400when neithertoolNamenormethod+pathis provided;404when no documented operation matchesFollow-up: the dedicated
unido_*tool fromdata.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|DELETEUse 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 contractsRequired permissions/prerequisites:
Mutating methods require
mcp:writeormcp:adminfor OAuth scope authorization, orauthorizationKeyif using a configured admin keypathmust target valid adapter-supported route behavior
Environment behavior:
methodis normalized to uppercasepathis normalized to leading slash formatauth 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:
400invalid path/query/body for upstream API401invalid/missingauthorizationKeyfor required mutating call403upstream access denied404endpoint/resource not found429upstream rate limiting5xxupstream/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_checkFollow-up: specialized read tools for validation, or another
service_api_requestGET 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_jobsfor pull-based processing andpgboss_complete_jobs/pgboss_fail_jobsto 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 withPGBOSS_SUPERVISE=trueor a dedicated worker process).pgboss_superviseruns one on-demand maintenance pass.Connection details are redacted in all tool output: connection strings, usernames, and passwords are reported only as
*Configuredbooleans.
Read-only tools (no authorizationKey required):
Tool | Description |
| Healthcheck: start state, schema installation, schema version |
| Redacted connection info, schema version, maintenance/timekeeping state |
| List queues with configuration and job counts (optional |
| One queue with counts: queued/ready/active/failed/total (queue size) |
| Historical stats snapshots (needs |
| Fetch one job by queue and id, including metadata |
| Find jobs by id, singleton key, data containment, or queued state |
| List schedules, optionally filtered by queue name and key |
| 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 |
| Create a queue ( |
| Update queue options (policy/partition are immutable) |
| Delete a queue and all of its jobs |
| Delete jobs by scope: |
| Send a job with full options: |
| Send a delayed job ( |
| At most one job per |
| Keep the last job submitted within a |
| Bulk-insert jobs in one statement |
| Create/update a recurring schedule (cron or RFC 5545 rrule, timezone, key, job options) |
| Remove a schedule by queue name and optional key |
| Manually claim up to |
| Cancel jobs / resume cancelled jobs by id |
| Queue failed jobs for retry by id |
| Delete jobs by id |
| Settle active jobs with optional output/error data |
| Run one on-demand maintenance pass (expiration, retention, monitoring) |
Scheduling format:
cronaccepts 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 asFREQ=MONTHLY;BYDAY=-1FR;BYHOUR=17.options.tzis an IANA timezone name (e.g.America/Chicago); default isUTC.options.keyallows multiple schedules on the same queue.options.missedcontrols catch-up after downtime:skip(default) oronce.
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_KEYpolicy, selected byMCP_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 |
| Read configuration in the authenticated tenant/principal scope, or configured default scope for stdio/local calls. |
| Mutate Postgres configuration; require |
| Resolve the interval in order: scoped Postgres override, default-scope Postgres override, then global environment default. |
| Inspect the enabled app-readable Vault Agent sink; requires |
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 |
| Read the calling principal's config/revision with Vault reference redacted. |
| Admin-authorized revisioned writes ( |
| Read another user's config/list user config revisions in an authorized tenant; require |
| Cross-user revisioned writes; require |
| Validate settings and URL safety without persisting or connecting. |
| Admin-authorized Vault credential resolution and inference endpoint check; never returns the credential. |
| Admin-authorized creation/update and rotation of tenant/principal-scoped inference credentials in Vault under |
| Admin-authorized deletion of a scoped inference credential; configs referencing the deleted |
| Admin-authorized redacted metadata inspection ( |
| 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. |
| Discover and execute declarative compositions learned from successful runs. |
| 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:
service_query_suggestion/agent_config_validate— discover the configuration schema and supported capability names (any registered tool name, for exampleunido_country_profile_countries).agent_credential_setwith{ "name": "<provider>", "apiKey": "<secret>" }— store the inference credential in scoped Vault storage; note the returnedcredentialRef.agent_config_validate— validate protocol (openai-compatible), endpoint URL safety, limits, capabilities, and memory settings without any network call.agent_config_setwith the validated config (inference.baseUrl,inference.model,credentialRef,instructions,permittedCapabilities, token/time/tool-call/step limits, memory policy),enabled: true,expectedRevision: 0.agent_config_test_connection— explicit live connectivity test against the configured endpoint's/models(network activity; may incur provider cost).agent_goalwith a non-destructive verification goal (for example "call service_health_check"), thenagent_task_statusuntil terminal — verifies worker consumption, checkpointing, and persistence.Later:
agent_config_updatefor changes andagent_credential_rotatefor credential rotation;agent_config_delete/agent_credential_deletedisable 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}_langgraphschema, keyed by a per-task thread. Checkpoints power retry andagent_task_resumecontinuation; 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:
Retrieval at run start (prompt augmentation). If any class is enabled in the agent config's
memorypolicy, the engine searches the owner's semantic, episodic, and procedural memories using the task's goal text as the query (Postgres full-text search andILIKE). Up tomemory.maxItemsresults (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.Write-back on success (learning). When a run completes and
memory.proceduralis 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).Manual semantic writes.
agent_memory_addis the only semantic write path: admin-authorized, content capped at 10000 characters, and content resembling a credential is rejected.agent_memory_searchreads 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 |
Error persists past the retry budget | The task is marked |
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 |
Legacy submitted/no-job rows | Repaired by idempotent resubmission and the worker's startup/interval reconciliation. |
Scheduled occurrences missed during downtime | Skipped by design ( |
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 |
|
|
|
|
|
|
|
|
|
|
| Owned schedule ID or bounded |
|
|
|
|
|
|
|
|
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 -dFor 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 (
autoby default;admin-keyoroauth-scopesfor explicit policy selection)MCP_TRANSPORT_MODE (
stdio,http, orboth)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 (
vaultfor indexed verification;staticforMCP_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_IDMCP_HTTP_OAUTH2_<PROVIDER>_CLIENT_SECRETMCP_HTTP_OAUTH2_<PROVIDER>_ISSUERMCP_HTTP_OAUTH2_<PROVIDER>_REQUIRED_SCOPESMCP_HTTP_OAUTH2_<PROVIDER>_REQUIRED_AUDIENCEMCP_HTTP_OAUTH2_<PROVIDER>_SCOPE_MAPMCP_HTTP_OAUTH2_<PROVIDER>_TIMEOUT_MSMCP_HTTP_OAUTH2_<PROVIDER>_CACHE_TTL_MSMCP_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; whenfalse,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_SCHEMAis ignoredPGBOSS_SUPERVISE (default
falsefor 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 — requiresCREATEprivilege 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 thetenancy_*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.featuredefault/app.defaultsfor future default parameters.default/token.rotation.intervalMsdefault/vault.agent.auth.modedefault/vault.agent.tokenFilePathdefault/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 byservice_health_check— the probe performs a live HTTP request)
Naming defaults:
MCP_SERVER_NAMEdefaults tounido-indstat-mcp. Postgres names normalize punctuation to underscores (for exampleunido_indstat_mcp_config); Vault paths use the MCP name prefix (for exampleunido-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_NAMEis used only to find legacy data. Existing${APP_NAME}_configrows are copied into the MCP-namespaced config table without deleting or modifying the source. Vault KV v2 data can be copied explicitly withnpm run vault:migrate-namespace -- --dry-run, thennpm run vault:migrate-namespace; the old source is retained and existing destination records are not overwritten. SetMCP_SERVER_NAMEconsistently 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).
Install dependencies with
npm ci.Copy .env.example to a local
.env; configure your target-service connection and authentication. Do not commit credentials.Start infrastructure first with
docker compose up -d postgres vault. This also runs the Vault key-file helper through the Vault dependency.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>Securely retain Vault's actual initialization output, configure valid application Vault authentication in
.env, and enable the KV v2 mount used byVAULT_KV_MOUNTif absent. The exampleVAULT_TOKEN=rootis 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.Choose the capabilities to enable:
Goal | Start / configure |
Local MCP tools |
|
Remote MCP / A2A access | Configure HTTP token or OAuth authentication, then run |
Both MCP transports | Run |
Durable agent tasks and schedules | Set |
Containerized HTTP + worker | After adapting the Compose environment for valid Vault/service credentials, run |
Run
npm testfor workspace contracts and application coverage. Database-backed agent/scheduling integration tests require an isolated database configured throughMCP_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_PASSWORDVAULT_ADDR,VAULT_TOKEN
Run the app-only compose stack:
docker compose -f docker-compose.external.yml up -dNotes:
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
VaultServiceapplies 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:bothProduction 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 |
| Serves |
Agent worker |
| Requires |
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 |
| Real Vault auth (AppRole or Vault Agent). The local manifest's explicit | |
| Generated secret ( | |
HTTP bearer tokens | Vault-stored per-user token index ( | |
OAuth client secrets | Deployment secrets, never committed files; HTTPS introspection endpoints | |
Upstream API credentials | None required — the documented UNIDO API is public and declares no security schemes | |
Inference credentials | Vault KV under |
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_URLto the externally reachable/a2aendpoint 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, oroauth-scopes; configure the same mode in server and worker.
Vault production posture
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.
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.
Prefer Vault Agent auto-auth and token renewal over long-lived static tokens.
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:
/healthzfor 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_statusand queue depth via thepgboss_*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_NAMEas 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=rooteverywhere (including compose overrides)Raft snapshot backups scheduled and restore tested
MCP_ADMIN_AUTH_KEYgenerated 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_MODEchosen and identical in server and workerTLS 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 setSingle HTTP instance, or edge rate limiting for multiple instances
Worker enabled (
MCP_AGENT_WORKER_ENABLED=true) and supervised with graceful shutdownTarget-service production credentials set; inference credential stored in Vault
Agent config created per principal with bounded
permittedCapabilities; grants issued before schedulesDelegated administration mapped to least privilege:
mcp:tenancy:adminandmcp:agent-config:adminissued instead of globalmcp:adminwhere possible, withallowedTenantIdsbounding multi-tenant admins; tenancy directory seeded for managed tenants/usersMonitoring in place for health, worker reconciliation, failed tasks, queue depth, Vault seal
npm testgreen on the exact deployed commit
HTTP MCP Endpoint
Default endpoint values:
MCP URL:
http://127.0.0.1:3000/mcpHealth URL:
http://127.0.0.1:3000/healthz
HTTP transport security controls:
Every
/mcprequest requiresAuthorization: Bearer <token>.For
MCP_HTTP_AUTH_MODE=token, setMCP_HTTP_TOKEN_SOURCE=vaultto 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_BYTESMCP_HTTP_RATE_LIMIT_WINDOW_MSMCP_HTTP_RATE_LIMIT_MAX_REQUESTS
Optional network restrictions:
MCP_HTTP_ALLOWED_ORIGINSMCP_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=mcpProvider 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
| Behavior |
| 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. |
| Preserve legacy key authorization for all callers, including OAuth callers. |
| 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 |
| Agent execution and baseline HTTP admission (default | 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 |
| Descriptive read scope; read tools do not add per-tool gates. Restrict HTTP admission with provider | OAuth introspection | Read-only | Read-only |
| Mutating service and configuration operations | OAuth introspection (scope mode); other callers use |
| Mutating |
| Full administration | OAuth introspection (scope mode); other callers use | All write capabilities plus Vault token seed/lifecycle/sink inspection, agent config set/update/delete/test, inference credential lifecycle ( | Admin-only |
| Delegated tenant/user/account directory administration limited to the authenticated tenant or | OAuth introspection |
| Admin-only (tenant-bounded) |
| Initialize the trusted Apify or MCPize caller in its fixed platform tenant | Trusted proxy identity headers |
| Mutating (self-scope only) |
| Cross-user agent configuration administration in an authorized tenant | OAuth introspection |
| 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 |
| Inspect tenants visible to the delegated administrator. |
| Create an active tenant. |
| Update metadata or disable a tenant without deleting its records. |
| Inspect users in an authorized tenant. |
| Create an active tenant user. |
| Update metadata or disable a user without deleting owned configs/tasks. |
| Inspect accounts in an authorized tenant. |
| 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_IDdefaults todefault.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_SCOPESandMCP_HTTP_VAULT_TOKEN_REQUIRED_AUDIENCEenforce policy checks.allowedTenantIdsis 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 --jsonUseful 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 --jsonUseful 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:
mcpServerNamedetermines the MCP/Postgres/Vault namespace.tenantIdanduserIddetermine 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->tokenLookupSelftoken_renew_self->tokenRenewSelftoken_create->tokenCreatetoken_revoke->tokenRevoketoken_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=trueChoose auth mode with
VAULT_AGENT_AUTH_MODE:file: use Vault Agent token sink filelistener: use Vault Agent listener endpointboth: enable listener operations and file-based token read workflows
Configure sink file path with
VAULT_AGENT_TOKEN_FILE_PATHEnable listener with
VAULT_AGENT_LISTENER_ENABLED=trueConfigure listener with
VAULT_AGENT_LISTENER_ADDRUse
vault_agent_token_readwhen application workflows need token sink visibilityRaw token sink data is returned only with
includeToken=trueand 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_KEYMCP_VAULT_AGENT_TOKEN_FILE_PATH_CONFIG_KEYMCP_VAULT_AGENT_LISTENER_ADDR_CONFIG_KEY
Recommended values in Postgres:
vault.agent.auth.modevault.agent.tokenFilePathvault.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_MSUser-scoped config key name:
MCP_TOKEN_ROTATION_USER_INTERVAL_CONFIG_KEY(defaulttoken.rotation.intervalMs)
Effective value resolution is:
User-scoped Postgres config (
userId+ key)Default user Postgres config (
default+ key)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.
Option A: Reverse-proxy TLS (recommended)
Terminate TLS at a reverse proxy or load balancer.
Keep this app on internal HTTP (
MCP_HTTP_TLS_ENABLED=false).Enforce HTTPS, client allowlists, and edge-level controls at the proxy/LB.
Forward traffic to
MCP_HTTP_HOST:MCP_HTTP_PORTand setMCP_HTTP_TRUST_PROXY=trueso 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.2Startup 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=falsewhen 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/...; themcp-httpservice passes theMCP_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.crtThen verify with curl --cacert certs/server.crt https://localhost:3000/healthz (or -k for a quick check).
Vault Production Migration (Raft)
The repository now includes a Vault production migration scaffold under vault-production:
vault-production/config/vault.hcl: Raft-backed Vault server configuration.
vault-production/docker-compose.vault-prod.yml: Compose definition for Vault in server mode (non-dev).
vault-production/scripts/convert-dev-to-prod.sh: Script to export dev KV data, start Raft Vault, initialize/unseal, and import secrets.
vault-production/scripts/bootstrap-post-conversion.sh: Script to enable audit, write policy, configure AppRole, and emit service credentials.
scripts/vault-unseal-key.js: Script to resolve unseal key from
VAULT_UNSEAL_KEYorsrc/config/vault.unseal.key.json.vault-production/README.md: Detailed migration notes and options.
Managed unseal key flow:
VAULT_UNSEAL_KEYis optional and can be injected at runtime.If
VAULT_UNSEAL_KEYis not set,npm run vault:unseal-keyreadssrc/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-initservice 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.jsonCommon 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 jsonService Onboarding Assets
This repository keeps the skeleton's onboarding assets for extending the server with additional service-backed MCP integrations:
agent/README.md: Overview of agent assets.
agent/playbooks/service-onboarding.md: Step-by-step onboarding checklist.
agent/templates/service-spec.md: Request template for describing new service 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 operationsSchema-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
UnidoServiceClientbehavior 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
authorizationKeyCredential/connection-string redaction in
pgboss_statusand connection infoLazy 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_URLis 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:generatefully offline from the committeddocs/OpenAPI documents (no live documentation downloads)fails if generation changes tracked files (stale committed inventory) and runs
npm run inventory:checkfor structural/coverage validationalways 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_URLset, 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 .githooksDo 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
Add domain adapters under src/services; keep the reference bootstrap and dependency wiring explicit.
Register tools in src/mcp/server.js with schemas and catalog metadata so direct MCP, agent capabilities, and compositions share the executable handlers.
Reuse runtime contracts for namespaces, scope, authenticated context, and redaction. Preserve tenant/principal ownership when adding persistence.
Use the shared scope/key authorization checks for mutations; admin-only operations require
mcp:adminin scope mode. KeepauthorizationKeyoptional in schemas for OAuth callers.Store secrets in Vault and non-secret configuration in Postgres; redact outputs and execution events.
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…
This server cannot be deployed
Maintenance
Related MCP Connectors
Multi-tenant backend your coding agent configures over MCP: auth, RBAC, data, workflows, deploy.
Agent-first social media publishing, scheduling, analytics, and unified inbox API + 16-tool MCP server across 18 social platforms (X, LinkedIn, Instagram, YouTube, TikTok, Threads, Bluesky, Reddit, Telegram, Discord, Mastodon, Facebook, Pinterest).
MCP server for your apps' tools and custom tools, plus hosted AI agents and approval-gated workflows
Your company's tools, memory and Automations for ChatGPT, Claude or any MCP agent. Open source.
Related MCP Servers
- AlicenseNot gradedqualityCmaintenanceEnables 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
- AlicenseAqualityBmaintenanceA 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.12MIT
- AlicenseCqualityCmaintenanceIt 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.58MIT
- AlicenseNot gradedqualityBmaintenanceEnables 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 PyPIMIT