sec-edgar-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.
sec-edgar-mcp
A complete Node.js MCP server for the U.S. Securities and Exchange Commission's SEC EDGAR data APIs (data.sec.gov / www.sec.gov), with tenant/principal-scoped persistence, multi-provider OAuth authorization, and optional durable agent execution.
Built from the skeleton-mcp reference architecture (source commit bfbf26a6939a3c3c387a34bd2461f1bb5d0b8eec, standalone new-mode build; that recorded commit is the only provenance link to the skeleton). Upstream attribution and the skeleton's MIT license are retained.
Repository name vs server identity: sec-edgar-mcp is both the repository name and the MCP_SERVER_NAME value here, but they play different roles. MCP_SERVER_NAME — not the repository name — is the single namespace source for all application-owned Vault paths and Postgres tables/schemas (see service_scope_info). Changing MCP_SERVER_NAME changes the persistence namespace and requires an explicit migration plan (npm run vault:migrate-namespace plus Postgres copy); never rename it silently. APP_NAME remains only as a documented legacy-migration input.
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.
SEC EDGAR coverage: dedicated read-only tools for every documented callable EDGAR data API operation (submissions, XBRL company concepts, company facts, frames, and the company-ticker reference files), full-text search over filing documents (efts.sec.gov), out-of-band bulk-archive download helpers, plus discovery, CIK lookup, and fair-access User-Agent management. See SEC EDGAR API coverage and inventory.
The upstream EDGAR data APIs are public, read-only, and unauthenticated, but the SEC fair-access policy requires a declared
User-Agentwith contact information and caps automated traffic at 10 requests/second. This server enforces both. The supplied infrastructure settings still require hardening before production use.
Start Here
Related MCP server: sec-edgar-mcp
Purpose
This repository is a service-specific MCP server for the SEC EDGAR data APIs that provides:
Multi-tenant, multi-user support with tenant/user and tenant/account identity.
Secret reads and writes through Vault (HTTP auth token index, inference credentials).
Config reads and writes through Postgres (including the scoped SEC fair-access User-Agent).
Tool-level authorization for mutating operations.
Redacted tool output by default (contact details in declared User-Agents are masked).
Client-side SEC fair-access throttling, bounded retries, and explicit timeouts.
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.
Capabilities At A Glance
Area | Included capabilities | Configuration / boundary |
Service integration | SEC EDGAR adapter with dedicated | Adapter: src/services/secEdgar.js; operation inventory source of record: src/services/secEdgarOperations.js; tool registration. |
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
This architecture (inherited from the skeleton) 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=sec-edgar-mcp, application tables use the sec_edgar_mcp_ prefix, checkpoint and queue schemas are sec_edgar_mcp_langgraph and sec_edgar_mcp_pgboss, and Vault paths begin with sec-edgar-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.
Trusted MCP Proxy Identities
The upstream skeleton repository ships two standalone HTTP proxy templates
(Apify and MCPize) for publishing an MCP server through hosted platforms; the
proxy projects themselves are not copied into this service repository. This
application retains the server-side half of that integration: when
MCP_HTTP_APIFY_PROXY_TOKEN and/or MCP_HTTP_MCPIZE_PROXY_TOKEN are set to
independent random secrets, a proxy that presents the shared secret can
forward a trusted per-caller identity, and the caller invokes
proxy_user_initialize once (idempotent, mcp:proxy:initialize scope) to
create/verify its platform tenant and principal. With these secrets unset, no
proxy identity is interpreted and behavior is unchanged. See the
skeleton-mcp repository for the
deployable proxy 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": {
"sec-edgar-mcp": {
"command": "npm",
"args": ["run", "start:stdio"],
"cwd": "/absolute/path/to/sec-edgar-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.sec-edgar-mcp]
command = "npm"
args = ["run", "start:stdio"]
cwd = "/absolute/path/to/sec-edgar-mcp"For HTTP, start the HTTP process and use this entry instead:
[mcp_servers.sec-edgar-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": {
"sec-edgar-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": {
"sec-edgar-mcp": {
"command": "npm",
"args": ["run", "start:stdio"],
"cwd": "/absolute/path/to/sec-edgar-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 sec-edgar-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
This server is the remote agent; Codex, Claude, or Copilot is the calling assistant. A2A submits a goal to this server's configured LangGraph agent and returns a durable task. It does not replace the client's chat model, synchronize chat history, or give the remote agent arbitrary access to your editor/workspace.
Note — A2A communication is asynchronous only. A2A clients never communicate synchronously with the LangGraph engine. A goal submission to
/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; this server 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 this server via A2A, not MCP. Use A2A_BASE_URL and A2A_TOKEN from the execution environment without printing the token. Fetch the Agent Card, use its A2A 1.0 JSON-RPC endpoint, send SendMessage with returnImmediately=true and a fresh idempotency key, save result.task.id, and poll GetTask to a terminal state. Summarize the result. Ask for approval before any mutating goal.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 server'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|company_submissions|company_concept|company_facts|xbrl_frames|lookup_cik|bulk|user_agent|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": "discover endpoints then fetch apple filing history",
"operationType": "company_submissions",
"method": "GET",
"path": "/submissions/CIK0000320193.json"
}
}Recommended Playbooks
Intent | Suggested tool sequence | Notes |
Verify runtime and upstream reachability |
| Baseline check before any operational request; confirms a declared User-Agent is configured. |
Configure the SEC fair-access User-Agent |
| OAuth: |
Resolve a ticker/company name to a CIK |
| The data APIs require a CIK; lookup returns 10-digit zero-padded CIKs. |
Fetch a company's filing history |
| Older filings are fetched with the |
Fetch one concept across a company's history |
| Needs taxonomy (e.g. |
Fetch all facts for a company |
| Response can be large; prefer |
Compare one concept across companies |
| Period format |
Execute a generic documented GET endpoint |
| Mutating methods are rejected; upstream is read-only. |
Search filing documents by phrase |
| efts.sec.gov backend of the official search UI; 2001+ documents; fixed page size 100, |
Locate / download bulk archives |
|
|
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": {}
}edgar_company_submissions
Category: read-only
Risk: low
Use when: you need an entity's filing history and metadata (
GET data.sec.gov/submissions/CIK##########.json)Do not use when: you need XBRL numeric data; use
edgar_company_concept/edgar_company_factsRequired permissions/prerequisites: a declared fair-access User-Agent (env or
edgar_user_agent_set); no upstream credentialsParameters:
cik(required, 1-10 digits as string or integer; zero-padded automatically,CIKprefix accepted)page(optional string; an additional-filings file name fromfilings.files, e.g.CIK0000320193-submissions-001.json)
Pagination: at least one year (or 1,000 filings) is returned in
filings.recent; older filings are listed infilings.filesand fetched by passingpageExpected response shape:
data.datais the upstream JSON document (entity metadata plusfilings)Common failures:
400invalid CIK or page name;403missing/undeclared User-Agent;404unknown CIK;429/503fair-access throttling (bounded retries applied);504timeoutRecommended tools: prerequisite
edgar_lookup_cik; follow-upedgar_company_factsExample:
{
"name": "edgar_company_submissions",
"arguments": { "cik": "<cik-number>" }
}edgar_company_concept
Category: read-only
Risk: low
Use when: you need every disclosure of one XBRL concept for one company (
GET data.sec.gov/api/xbrl/companyconcept/CIK##########/{taxonomy}/{tag}.json)Parameters:
cik(required, as above)taxonomy(required string, e.g.us-gaap,ifrs-full,dei,srt)tag(required XBRL tag, e.g.AccountsPayableCurrent)
Expected response shape:
data.data.unitsholds one facts array per unit of measureCommon failures:
400invalid parameters;403missing User-Agent;404unknown CIK/taxonomy/tag;429/503throttlingRecommended tools: prerequisite
edgar_lookup_cik; follow-upedgar_xbrl_framesfor cross-company comparisonExample:
{
"name": "edgar_company_concept",
"arguments": { "cik": "<cik-number>", "taxonomy": "us-gaap", "tag": "<xbrl-tag>" }
}edgar_company_facts
Category: read-only
Risk: low (large responses possible)
Use when: you need all XBRL facts for one company in one call (
GET data.sec.gov/api/xbrl/companyfacts/CIK##########.json)Do not use when: you only need one concept; prefer
edgar_company_conceptParameters:
cik(required, as above)Common failures:
400invalid CIK;403missing User-Agent;404unknown CIK;429/503throttlingExample:
{
"name": "edgar_company_facts",
"arguments": { "cik": "<cik-number>" }
}edgar_xbrl_frames
Category: read-only
Risk: low
Use when: you need one fact per reporting entity for a calendrical period (
GET data.sec.gov/api/xbrl/frames/{taxonomy}/{tag}/{unit}/{period}.json)Parameters:
taxonomy(required),tag(required)unit(required, e.g.USD,shares,USD-per-shares)period(required;CY####annual,CY####Q#quarterly,CY####Q#Iinstantaneous — schema-validated)
Notes: the API aggregates facts that most closely fit the requested calendrical period
Common failures:
400malformed period/unit;403missing User-Agent;404unknown frame;429/503throttlingExample:
{
"name": "edgar_xbrl_frames",
"arguments": { "taxonomy": "us-gaap", "tag": "<xbrl-tag>", "unit": "USD", "period": "CY2024Q1I" }
}edgar_company_tickers / edgar_company_tickers_exchange / edgar_company_tickers_mf
Category: read-only
Risk: low
Use when: you need the raw CIK/ticker reference files from
www.sec.gov/files/(company_tickers.json,company_tickers_exchange.json,company_tickers_mf.json)Do not use when: you only need to resolve one ticker; use
edgar_lookup_cikParameters: none
Provenance note: these reference files are well-established SEC developer resources but are not covered by the local documentation snapshot; see the coverage report
Example:
{
"name": "edgar_company_tickers",
"arguments": {}
}edgar_lookup_cik
Category: read-only (convenience; does not replace dedicated endpoint coverage)
Risk: low
Use when: you have a ticker symbol or company-name fragment and need the 10-digit CIK required by the data APIs
Parameters:
query(required string; exact ticker matches rank first)limit(optional integer 1-100, default 10)
Expected response shape:
data.matches[]withcik(zero-padded),ticker,titleExample:
{
"name": "edgar_lookup_cik",
"arguments": { "query": "<ticker-or-company-name>" }
}edgar_full_text_search
Category: read-only
Risk: low
Use when: you need to find filings whose documents contain a phrase (
GET efts.sec.gov/LATEST/search-index— the JSON backend of the official EDGAR full-text search UI), with form-type/CIK/date/entity filtersDo not use when: you already know the CIK and need structured data; use
edgar_company_submissions/ the XBRL tools insteadRequired permissions/prerequisites: declared fair-access User-Agent (same as all upstream calls); no admin authorization
Provenance/uncertainty: outside the local documentation snapshot and not an officially documented SEC API. A polite live probe (single low-volume GET with a compliant declared User-Agent) on 2026-12-02 was blocked by SEC's automated-tool
403edge page from the build environment, so the response shape could not be live-verified here; parameters and the Elasticsearch-shaped response (hits.total.{value,relation},hits.hits[]._idas{accession}:{filename},hits.hits[]._sourcewithadsh/ciks/display_names/form/root_forms/file_type/file_date/period_ending, …) are corroborated from the search UI's network behavior and third-party references only. The tool returns upstream JSON verbatim; treat undocumented fields as uncertain. Recorded asefts-public-interfaceprovenance in inventory/COVERAGE.md.Parameters:
q(required string, max 256 chars; wrap exact phrases in double quotes)forms(optional string or array, e.g."10-K"or["10-K","8-K"]; validated/uppercased, comma-joined)ciks(optional string/number/array; zero-padded to 10 digits)startdt/enddt(optionalyyyy-mm-dd; malformed dates are silently ignored upstream, so they are schema-validated here)dateRange(optional enumcustom|30d|1y|5y|10y;customrequires both dates; presets are uncertain — prefer explicit dates)from(optional integer 0-9900; fixed page size 100; upstream caps total results at ~10,000 —hits.total.relation="gte"signals truncation; split date ranges to collect more)sort(optional enumasc|descby filing date; uncertain),entityName(optional filer-name filter; uncertain)
Notes: full-text coverage starts with filings from 2001; pre-2001 windows can return upstream
5xx. Fair-access throttle/retry/User-Agent handling is identical to every other upstream call.Common failures:
400malformed parameters;403missing/undeclared User-Agent or SEC automated-tool edge block;429/503throttlingFollow-up tools:
edgar_company_submissions(filing history for a hit's CIK),service_api_request(fetch an additional documented JSON page)Example:
{
"name": "edgar_full_text_search",
"arguments": { "q": "\"<exact-phrase>\"", "forms": "10-K", "startdt": "<yyyy-mm-dd>", "enddt": "<yyyy-mm-dd>", "from": 0 }
}edgar_bulk_data_info
Category: read-only (informational; performs no network call)
Risk: low
Use when: you need the documented bulk archive URLs (
companyfacts.zip,submissions.zip), whether a download directory is configured, and which dedicated helper tools to useNotes: bulk ZIP archives are multi-gigabyte and are handled out-of-band by
edgar_bulk_companyfacts_download/edgar_bulk_submissions_download(user-approved on 2026-12-02; previously recorded as PENDING USER APPROVAL exclusions). Archive bytes are never returned through MCP responses.Example:
{
"name": "edgar_bulk_data_info",
"arguments": {}
}edgar_bulk_companyfacts_download / edgar_bulk_submissions_download
Category: dual-mode —
mode=metadata(default) is read-only;mode=downloadis read-only against the upstream but has an explicit local-disk write side effectRisk: high (download mode writes multi-gigabyte files to the host filesystem)
Use when: you need resumable out-of-band download metadata for a nightly bulk archive (
GET www.sec.gov/Archives/edgar/daily-index/xbrl/companyfacts.zip/.../bulkdata/submissions.zip), or an operator-controlled server-side download of oneDo not use when: you expect archive contents through the MCP response — the multi-GB payload is never streamed through MCP; use the data APIs for per-company JSON instead
Required permissions/prerequisites:
mode=metadata: declared fair-access User-Agent onlymode=download: additionally OAuthmcp:write/mcp:adminorauthorizationKey(whenMCP_ADMIN_AUTH_KEYis configured), and an operator-configuredSEC_EDGAR_BULK_DOWNLOAD_DIR(download mode fails with an actionable400until it is set)
Environment behavior and safety:
mode=metadataperforms aHEADrequest and returnsurl,contentLength,etag,lastModified,acceptRanges, acurl -C -resume example, and a disk-space warning — suitable for resumable out-of-band downloadsmode=downloadstreams intoSEC_EDGAR_BULK_DOWNLOAD_DIRvia a temp file renamed on completion (failed/aborted transfers are cleaned up), computes a SHA-256 digest, and enforces the optionalSEC_EDGAR_BULK_MAX_DOWNLOAD_BYTEScap both against the declaredContent-Lengthand the actual streamtargetFilenameis path-traversal-safe: plain.zipnames only (letters/digits/._-, no path separators, no..), schema- and adapter-validated; existing files are never replaced withoutoverwrite=true(409otherwise)Disk-space warning: archives are tens of GB (companyfacts ~1.2+ GB compressed and growing; submissions multi-GB; sizes vary nightly — check
mode=metadatafirst). Ensure sufficient free space; downloads are single-attempt (no automatic retry) — resume interrupted transfers out-of-band using the metadataThe timeout applies only until response headers arrive; the body transfer is not time-bounded
Parameters:
mode(optional enummetadata|download, defaultmetadata)targetFilename(optional validated.zipfile name; defaultscompanyfacts.zip/submissions.zip)overwrite(optional boolean, defaultfalse)authorizationKey(required formode=downloadunder key-based authorization)
Expected response shape: metadata mode as above; download mode returns
path,bytesWritten,sha256,etag,lastModified,durationMs, andsideEffect: "local-disk-write"— never archive bytesCommon failures:
400download dir unconfigured/invalid or bad file name;401missing/invalid key in download mode;403missing User-Agent;409destination exists withoutoverwrite;413cap exceeded;429/503throttlingPrerequisite/follow-up tools:
edgar_bulk_data_info(archive URLs + config state) before; verify thesha256/bytesWrittenafterExample:
{
"name": "edgar_bulk_companyfacts_download",
"arguments": { "mode": "download", "overwrite": false, "authorizationKey": "<admin-key-if-required>" }
}edgar_user_agent_set
Category: mutating (service-credential analog; stores non-secret configuration in Postgres)
Risk: medium
Use when: provisioning or rotating the declared SEC fair-access User-Agent for the authenticated/default tenant/principal scope
Required permissions/prerequisites: OAuth
mcp:write/mcp:admin, orauthorizationKeywhenMCP_ADMIN_AUTH_KEYis configured; the value must include contact information (email address or URL)Parameters:
userAgent(required string, max 200 chars, e.g."Example Corp admin@example.com")authorizationKey(key-based authorization only)
Expected response shape: scope row metadata plus
userAgentPreviewwith the email local part masked; the raw value is never echoedRotation/revocation: rotation is a subsequent
edgar_user_agent_set; revocation isedgar_user_agent_delete(falls back toSEC_EDGAR_USER_AGENT). There are no upstream credentials to expire or refresh — the EDGAR APIs are unauthenticated.Common failures:
400missing contact info;401missing/invalid key;403missing scopeExample:
{
"name": "edgar_user_agent_set",
"arguments": { "userAgent": "<company-name> <contact-email>", "authorizationKey": "<admin-key-if-required>" }
}edgar_user_agent_get
Category: read-only (redacted metadata inspection)
Risk: low
Use when: inspecting which declared User-Agent is effective for the authenticated/default scope and where it comes from
Parameters:
includeSensitive(optional boolean; raw value disclosure additionally requires admin authorization andMCP_ALLOW_SENSITIVE_OUTPUT=true)authorizationKey(required only withincludeSensitive=trueunder key-based authorization)
Expected response shape:
data.configured,data.source(postgres-scope-config|environment-default|unset),data.userAgentPreview(contact masked)Example:
{
"name": "edgar_user_agent_get",
"arguments": {}
}edgar_user_agent_delete
Category: mutating
Risk: medium
Use when: removing the scoped User-Agent override so requests fall back to
SEC_EDGAR_USER_AGENTRequired permissions/prerequisites: same authorization as
edgar_user_agent_setParameters:
authorizationKey(key-based authorization only)Expected response shape:
data.deletedbooleanExample:
{
"name": "edgar_user_agent_delete",
"arguments": { "authorizationKey": "<admin-key-if-required>" }
}service_api_request
Category: read-only (GET/HEAD only)
Risk: medium
Use when: you need a documented SEC endpoint without a dedicated tool (for example an additional submissions JSON page)
Do not use when: a dedicated
edgar_*tool exists; those provide validated parameters and clearer contractsRequired permissions/prerequisites: declared fair-access User-Agent; requests are restricted to the configured
data.sec.gov/www.sec.gov/efts.sec.govallow-listEnvironment behavior:
methodis normalized to uppercase; onlyGETandHEADare accepted — mutating methods return405because the upstream API is public and read-onlypathis normalized to leading-slash format;hostselectsdata(default),www, oreftscredential-style headers (
Authorization,Cookie,X-Api-Key) are stripped before dispatch
Parameters:
method(required string,GETorHEAD)host(optional enumdata|www|efts, defaultdata)path(required string)query(optional object: string keys, scalar values)headers(optional object: string keys/values; credential-style headers stripped)
Expected response shape:
datawithurl,status,contentType, and parseddataCommon failures:
400invalid host/path;403host outside allow-list or missing User-Agent;404unknown resource;405mutating method;429/503throttling;504timeoutExample:
{
"name": "service_api_request",
"arguments": {
"method": "GET",
"host": "data",
"path": "/submissions/CIK<10-digit-cik>.json"
}
}pg-boss Queue And Scheduling Tools
This server 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 sec_edgar_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. |
| 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.
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.
SEC EDGAR API Coverage And Inventory
The EDGAR data APIs publish no official OpenAPI specification, so this repository maintains a reviewed, normalized inventory with explicit provenance in src/services/secEdgarOperations.js (the single source of record consumed by the adapter, the discovery tools, and the inventory scripts).
Machine-readable inventory: inventory/sec-edgar-inventory.json
Human-readable coverage report: inventory/COVERAGE.md
Commands (deterministic; no live documentation downloads, so CI stays reproducible):
npm run inventory:generate # regenerate both artifacts from the source of record
npm run inventory:check # fail on drift, stale output, invalid/duplicate/missing tool mappingsCoverage summary:
10 documented callable operations, each with a dedicated MCP tool — 100% of required callable operations, zero pending exclusions: submissions, company concept, company facts, XBRL frames, the three company-ticker reference files, EDGAR full-text search (
efts.sec.gov), and the two bulk archives.The 2 bulk-archive operations (
companyfacts.zip,submissions.zip) were previously excluded PENDING USER APPROVAL; that approval was granted on 2026-12-02 and they are now implemented as out-of-band download helper tools (edgar_bulk_companyfacts_download,edgar_bulk_submissions_download): read-only upstream, with an explicit admin-gated local-disk write side effect in download mode. Multi-gigabyte payloads are never returned through MCP responses.Provenance:
https://www.sec.gov/edgar/sec-api-documentationblocks automated retrieval; entries transcribed from the documented endpoint set carry explicit uncertainty notes, and the local snapshots are API-DOCS.md and docs/data-sec-api-home.html. ThefullTextSearchentry carriesefts-public-interfaceprovenance: it is the JSON backend of the official search UI, outside the local snapshot; a polite live probe on 2026-12-02 was blocked by SEC's automated-tool403edge page, so its request/response shape is corroborated from the search UI behavior and third-party references only and remains explicitly uncertain. Nothing was invented beyond those sources.Upstream API versioning: the data APIs are unversioned (
LATEST); environments are production-only (data.sec.gov/www.sec.gov/efts.sec.gov), selectable viaSEC_EDGAR_DATA_BASE_URL/SEC_EDGAR_WWW_BASE_URL/SEC_EDGAR_FTS_BASE_URLfor testing.
Development Setup And Required Checks
Enable the version-controlled pre-push hook once per clone:
npm run hooks:install # sets git core.hooksPath to .githooksThe hook runs npm run inventory:check and npm test and blocks a normal
push when they fail. The same checks are enforced by
GitHub Actions on every push and
pull request, including the disposable-Postgres agent integration tests.
Environment Variables
Core:
MCP_SERVER_NAME (single namespace source; set to
sec-edgar-mcpin all supplied deployments. Renaming changes every derived Vault path and Postgres table/schema and requires an explicit migration plan.)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
SEC EDGAR upstream:
SEC_EDGAR_USER_AGENT (declared fair-access User-Agent with contact info, e.g.
Example Corp admin@example.com; optional at startup — requests fail with an actionable400until a global or scoped value exists)SEC_EDGAR_USER_AGENT_CONFIG_KEY (Postgres config key for scoped overrides; default
edgar.userAgent)SEC_EDGAR_DATA_BASE_URL (default
https://data.sec.gov)SEC_EDGAR_WWW_BASE_URL (default
https://www.sec.gov)SEC_EDGAR_FTS_BASE_URL (default
https://efts.sec.gov; full-text search backend of the official EDGAR search UI —efts-public-interfaceprovenance, see the coverage report)SEC_EDGAR_BULK_DOWNLOAD_DIR (default unset; operator-configured local destination directory for bulk-archive
mode=download. Must exist; download mode is disabled with an actionable400until set. Archives are multi-gigabyte — ensure sufficient free disk space.)SEC_EDGAR_BULK_MAX_DOWNLOAD_BYTES (default unset = no explicit cap; when set, bulk downloads exceeding this byte count are refused with
413, checked against both the declaredContent-Lengthand the actual stream)SEC_EDGAR_TIMEOUT_MS (default
15000)SEC_EDGAR_MAX_REQUESTS_PER_SECOND (default
5; hard-capped at the SEC fair-access limit of 10)SEC_EDGAR_MAX_RETRIES (default
2; retries apply to 429/502/503/504 and network errors on idempotent GET/HEAD only)SEC_EDGAR_RETRY_BASE_DELAY_MS (default
500; exponential backoff honoringRetry-After)
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
Naming defaults:
MCP_SERVER_NAMEissec-edgar-mcpin all supplied deployments. Postgres names normalize punctuation to underscores (for examplesec_edgar_mcp_config); Vault paths use the MCP name prefix (for examplesec-edgar-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; setSEC_EDGAR_USER_AGENTto your declared fair-access User-Agent (company/contact). 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 sec-edgar-mcp-vault vault operator init -key-shares=1 -key-threshold=1 -format=json
docker exec -e VAULT_ADDR=http://127.0.0.1:8200 sec-edgar-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 this server in production. It links to the detailed sections rather than repeating them. The supplied compose stacks and credentials are development defaults; production readiness is the deployer's responsibility.
Production architecture and process layout
Run two separately supervised services built from this repository:
Service | Entry | Notes |
MCP HTTP + A2A |
| 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 | |
SEC fair-access declaration | Production | |
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
Upstream OAuth scopes: none. The SEC EDGAR data APIs are public, read-only, and unauthenticated; no service-specific upstream OAuth scopes exist or are requested. All scopes below govern access to this MCP server itself.
Accepted scope summary for this deployment: HTTP admission requires the provider-verified scopes you configure (MCP_HTTP_VAULT_TOKEN_REQUIRED_SCOPES defaults to mcp:invoke; set provider REQUIRED_SCOPES for OAuth). All edgar_* read tools, discovery tools, and read-only service_*/config_*/pgboss_* tools require only admitted authentication (mcp:invoke, with mcp:read as the descriptive read scope). The mutating tools edgar_user_agent_set / edgar_user_agent_delete, config_set/config_delete, and mutating pg-boss tools require mcp:write or mcp:admin in scope mode (or authorizationKey in key mode). Vault token seeding/lifecycle, agent configuration mutations/connection tests, and schedule/grant administration require mcp:admin (or the delegated mcp:tenancy:admin/mcp:agent-config:admin scopes). Agent execution additionally requires mcp:invoke or mcp:agent. When registering an OAuth client for this server, request the provider-native scopes that your SCOPE_MAP translates into exactly these canonical scopes — see the scope-capabilities table below.
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
Scope | Capabilities |
| Submit/read/resume/cancel agent tasks and invoke agent compositions/A2A, subject to agent enablement and principal ownership. |
| Mutating service calls, Postgres config writes/deletes, and mutating pg-boss tools in scope mode. |
| All write capabilities plus Vault token seed/lifecycle/sink inspection, agent config changes/connection tests/memory writes, and schedule/grant mutations/manual runs/previews. |
| Descriptive read scope; existing read tools do not add a per-tool scope gate. Restrict HTTP admission with provider |
| Manage tenants and tenant users, including tenant/user token seeding. A dedicated tenancy administrator is limited to its authenticated tenant or |
| Initialize the trusted Apify or MCPize caller in its fixed platform tenant. This scope does not grant general tenancy administration. |
| Read and mutate agent configurations for other users in an authorized tenant. It does not grant tenancy or Vault server-token administration. |
mcp:admin satisfies write/admin checks but does not replace the separate mcp:invoke/mcp:agent requirement for agent execution. Neither scopes nor scope mapping bypass tenant/principal ownership checks. Agent permittedCapabilities still limits the runnable tool names; composition steps and scheduled tasks enforce the same underlying tool handlers and scope checks.
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
This server 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 server supports storing non-secret Vault Agent runtime pointers/settings in Postgres while keeping token material in Vault.
Runtime settings are read from default user config scope (
MCP_CONFIG_DEFAULT_USER_ID).Key names are configurable with:
MCP_VAULT_AGENT_AUTH_MODE_CONFIG_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 retains the generic onboarding assets inherited from the skeleton for extending this server with further capabilities:
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.
The skeleton-specific VS Code custom agent, skill, and repository-generation prompt files are intentionally not carried into this generated repository; use them from the skeleton-mcp repository.
Test Coverage
Integration tests in tests/server.integration.test.js cover:
Healthcheck behavior and dedicated-tool registration for every implemented inventory operation
Dedicated
edgar_*tool request/response mapping and schema boundaries (frames period validation)Read-only enforcement of
service_api_request(mutating methods rejected with405)Authorization on
edgar_user_agent_set/edgar_user_agent_delete, contact-info validation, and redaction of contact details (including gatedincludeSensitivedisclosure)Scoped User-Agent override resolution from Postgres config
edgar_full_text_searchfilter forwarding and schema boundaries (requiredq,fromcap, date formats)Bulk download tools: read-only metadata mode without authorization, admin-gated download mode, path-traversal-safe
targetFilenameschema, and no archive bytes in responsesTool workflow suggestions, admin-authorization reporting, and provenance visibility (zero remaining exclusions) in
service_list_endpoints
SEC EDGAR adapter tests in tests/sec-edgar-client.test.js cover:
CIK normalization, taxonomy/tag/unit/period validation, and submissions pagination page-name validation
Declared User-Agent requirement, contact-info validation, per-call override, and redaction
Documented URL construction for every implemented operation
Host allow-listing (including
efts.sec.gov), credential-header stripping, and read-only method enforcementBounded retries with backoff and
Retry-Afteron 429/5xx, retry-budget exhaustion, and timeout-to-504 mappingClient-side fair-access throttling and the 10 req/s hard cap
Full-text search URL construction, parameter validation (query/forms/ciks/dates/
from/sort/dateRange), and pre-dispatch rejection of malformed inputBulk archive HEAD metadata (resumable
Content-Length/ETag/Last-Modified), streamed downloads to a validated directory with SHA-256 digests, overwrite/409semantics, path-traversal rejection, unconfigured-directory errors, and byte-cap enforcement (declared and streamed) with partial-file cleanup
Inventory tests in tests/inventory.test.js cover:
Deterministic generation, committed-artifact drift detection, validation problems, 100% required-callable coverage with zero pending exclusions, unique tool mappings, efts provenance/uncertainty notes, and bulk-archive side-effect classification
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 now runs inventory generation and test enforcement via .github/workflows/inventory-and-tests.yml.
The inventory job:
runs
npm run inventory:checkagainst the committed artifactsruns
inventory:generateand fails if it changes tracked files that were not committedalways uploads a deterministic repository file inventory as a workflow artifact
The test job starts a disposable Postgres service, sets
MCP_AGENT_TEST_DATABASE_URL, and runsnpm testso the agent/scheduling database integration tests execute rather than skip; it blocks merges when tests fail.Locally,
npm run hooks:installenables the version-controlled pre-push hook that runs the same required checks before every push.
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
Read, search, and compare SEC EDGAR filings, pull tables, and run AI analysis from any MCP client.
EDGAR MCP — SEC EDGAR public APIs (free, no auth)
SEC MCP — SEC EDGAR public APIs (free, no auth)
Search SEC EDGAR 10-K/10-Q/8-K/Form 4 filings, XBRL facts, and full-text disclosures via MCP.
1
Related MCP Servers
- AlicenseNot gradedqualityBmaintenanceQuery SEC EDGAR filings, XBRL financials, and company data through MCP.422 npm12Apache 2.0
- AlicenseNot gradedqualityDmaintenanceHosted MCP server that gives AI agents real-time access to SEC EDGAR filings search, 10-K/8-K reading, XBRL financial facts, and insider-trade (Form 4) alerts.1MIT
- FlicenseAqualityDmaintenanceEnables AI clients to retrieve SEC company profiles, filing listings, and structured XBRL financial statements via MCP tools.13-
- AlicenseNot gradedqualityCmaintenanceHosted MCP server granting AI agents access to 20M+ SEC EDGAR filings, 100M+ exhibits, and comprehensive entity data through 49 tools, with support for raw documents, extracted sections, and structured JSON.3MIT