Skip to content
FunCoding

api-config

Reference for core and server configuration in `@cyanheads/mcp-ts-core`. Covers env var tables with defaults, priority order, server-specific Zod schema pattern, and Workers lazy-parsing requirement.

Star
722
License
Apache-2.0
Last commit
Nov 11, 2026

framework-skills/api-config/SKILL.md

View on GitHub

Overview

Configuration has two layers: core config (managed by the framework, env-driven) and server config (your own Zod schema for domain-specific env vars). Never merge them.

Import: AppConfig, config, parseConfig, resetConfig, ConfigSchema from @cyanheads/mcp-ts-core/config.


Core config

Managed by @cyanheads/mcp-ts-core. Validated via Zod from environment variables. Uses a lazy proxy — parsing is deferred until the first property read, and importing the package (any subpath) never reads it, so a bad framework variable surfaces when createApp() starts: the Configuration error — server failed to start banner lists each failure as the variable, its schema path, and the reason ( - CANVAS_DEFAULT_ROW_LIMIT (canvas.defaultRowLimit): Too small: expected number to be >=1), and the process exits 1. The thrown ConfigurationError carries the same failures as data.issues ({ envVar, path, message, code }). createWorkerHandler() drops any config cached before its first request and re-parses after the bindings are injected.

Startup overrides must survive reparsing. createApp() resets core config when applying identity or session-mode options, so an earlier resetConfig(overrides) is not a persistent application default. After dotenv loading, seed server defaults into unset environment variables (including blank or whole-value placeholder settings), preserve explicit operator values, then reset the cached config. Validate the resolved core.config in setup().

Priority (highest to lowest):

  1. name/version/title/websiteUrl/description/icons options passed to createApp() or createWorkerHandler()
  2. Environment variables
  3. sessionMode.default passed to createApp() — a default, so it sits below the env var it seeds, unlike the identity options above
  4. package.json fields

Where package.json is read from: the application root — the nearest package.json at or above the process entry module (process.argv[1]), which is the served package on every launch path (npx, .mcpb, a client config naming dist/index.js), none of which run from the package root. The launching client's working directory is never the anchor: a stdio client starts the server from wherever it happens to be, so reading identity from there makes a server report a foreign project's name and version. When the entry module is a tool installed under a node_modules tree and the process runs from the directory owning that tree — a test runner is the usual case — the nearest manifest at or above the working directory wins instead. That also covers a workspace monorepo, where the runner is hoisted to the repo root while the process runs from a package directory: an owner that is a strict ancestor of the working directory qualifies only when it declares a workspace (a workspaces field in its manifest, or a pnpm-workspace.yaml beside it), which is what keeps a cache prefix or a plain project root — equally ancestors of a working directory inside them — from overriding an installed package's own identity. The owner is the outermost node_modules boundary, so a transitively-installed runner and a pnpm isolated layout resolve the same way. An entry package declaring @cyanheads/mcp-ts-core in dependencies, optionalDependencies, or peerDependencies is never such a tool: it runs the framework, so it is the application, and an installed server launched from the installing project's root or one of its workspace packages (node_modules/.bin/<server>, a local npx <server>) keeps its own identity, skills folder, and log directory. A package listing the framework only under devDependencies still counts as a tool. With no manifest reachable, the framework's own name and version are the fallback; the description is never taken from the framework, so a server with none of its own advertises none.


Identity

Env VarAppConfig fieldDefaultNotes
MCP_SERVER_NAMEmcpServerNamepackage.json nameOverrides package name
MCP_SERVER_VERSIONmcpServerVersionpackage.json versionOverrides package version
MCP_SERVER_DESCRIPTIONmcpServerDescriptionpackage.json descriptionOptional; createApp({ description }) wins when set. The resolved value reaches initialize serverInfo and every manifest surface (server card, GET on the endpoint, landing page) alike; with no source, none of them carries a description
PACKAGE_NAMEpkg.namepackage.json nameRarely needed
PACKAGE_VERSIONpkg.versionpackage.json versionRarely needed

SDK identity fields (API-only, no env var equivalent — passed to createApp() / createWorkerHandler(), forwarded to initialize and /.well-known/mcp.json):

OptionTypeNotes
titlestring?Human-readable display name shown in client listings
websiteUrlstring?Canonical homepage / repository URL
descriptionstring?One-line description; wins over MCP_SERVER_DESCRIPTION when set
iconsImplementation['icons']?Array of icon objects: { src, mimeType?, sizes?: string[], theme?: 'light'|'dark' }
cacheHintsCacheHints?Cache hints for the 2026-07-28 cacheable results, keyed by operation — see below
sessionModeSessionMode | { default?: SessionMode; require?: 'stateful' }Session posture declared in code — see below
Cache hints (cacheHints)

API-only, no env var. Sets the ttlMs / cacheScope a client may cache a cacheable result for on protocol revision 2026-07-28. Keys are the closed set of cacheable operations: tools/list, prompts/list, resources/list, resources/templates/list, resources/read, server/discover.

await createApp({
  cacheHints: {
    'tools/list': { ttlMs: 3_600_000, cacheScope: 'public' },
    'resources/read': { ttlMs: 60_000 },
  },
});
  • ttlMs — cache lifetime in milliseconds; must be a non-negative safe integer. An invalid value fails at startup with a ConfigurationError naming the field.
  • cacheScope — 'private' (only the requesting client may cache) or 'public' (shared caches may too).
  • A resource's own cacheHint overrides the resources/read entry for that resource, field by field — see the add-resource skill.
  • Omitting a hint keeps the SDK defaults (ttlMs: 0, cacheScope: 'private'). Responses to 2025-era clients are never affected.
Session mode (sessionMode)

Declares the session posture in src/ instead of leaving it to a deployment's MCP_SESSION_MODE. The bare string is shorthand for { default }. HTTP only — MCP_SESSION_MODE has no effect on stdio.

await createApp({ sessionMode: 'stateless' });                                  // default only
await createApp({ sessionMode: { default: 'stateful', require: 'stateful' } }); // and enforced
  • default applies only when MCP_SESSION_MODE carries no meaningful value. An empty string and a whole-value unsubstituted ${…} placeholder both read as unset on the config path, so both fall through to the option rather than to the schema default (auto). An explicit MCP_SESSION_MODE always wins.
  • require: 'stateful' fails startup with a ConfigurationError naming the conflicting env value when the resolved HTTP mode is stateless, before any service is constructed. Declare it when a handler gates a destructive action behind ctx.requestInput / inputRequired.elicit — see the MCP_SESSION_MODE row for why that combination is unusable for 2025-era clients. There is no require: 'stateless'; nothing needs statelessness to work.
  • The advertised transport.sessionMode follows automatically — resolveSessionMode is the single resolution the manifest, the session store, and the ctx.sessionId gate all read — and still never publishes auto.
  • Cloudflare Workers are outside this contract: MCP_SESSION_MODE is not in CORE_ENV_BINDINGS, so on a Worker whose process.env is not populated from its bindings, a [vars] entry reaches process.env only through extraEnvBindings.

Environment & logging

Env VarAppConfig fieldDefaultNotes
NODE_ENVenvironmentdevelopmentAliases: dev→development, prod→production, test→testing
MCP_LOG_LEVELlogLeveldebugThe floor for every log sink — stderr, the files, OTLP export, and the ctx.log mirror to the client (notifications/message), which a client's own level can only narrow. Compared on the RFC 5424 order, so notice drops info and crit drops error. Aliases: warn→warning, err→error, fatal/silent→emerg, trace→debug, information→info
LOGS_DIRlogsPath<app-root>/logsNode.js only; absolute paths are used verbatim, relative ones resolve against the application root (see Core config) — never the framework's install directory. A file under it that cannot be opened (read-only mount, another user's directory) is dropped at startup with one warning naming it and the error code; stderr and the other files keep logging
LOG_TOOL_FAILURE_PAYLOADSlogToolFailurePayloadsfalseOpt-in. Each failed tool call also writes a Tool failure payload: <tool> record carrying toolInput (the arguments as sent) and toolResult (the CallToolResult returned) as redacted JSON strings, at the call's error-record level. Reaches every log destination — stderr, combined.log, and OTLP when OTEL_EXPORTER_OTLP_LOGS_ENDPOINT is set. Redaction is by key name only, so a secret inside a free-form value (a query, a message) is logged. Record shape: api-telemetry Logs
LOG_TOOL_FAILURE_PAYLOAD_MAX_BYTESlogToolFailurePayloadMaxBytes16384Cap per payload, in UTF-8 bytes. A longer one is cut on a character boundary and flagged with toolInputTruncated / toolResultTruncated
LOG_LLM_INTERACTIONSlogLlmInteractionsfalseOpt-in. The OpenRouter provider (/services) writes each chat completion's full request and response bodies to interactions.log instead of metadata (model, message count, generation params, finish reasons, token usage). Transcripts can carry user PII, secrets, and confidential prompts, and redaction is by key name only. interactions.log sits under LOGS_DIR (Node.js only) and is never exported over OTLP

Transport

Env VarAppConfig fieldDefaultNotes
MCP_TRANSPORT_TYPEmcpTransportTypestdiostdio | http
MCP_HTTP_PORTmcpHttpPort3010Port for HTTP transport; integer, 0–65535
MCP_HTTP_HOSTmcpHttpHost127.0.0.1Bind address
MCP_HTTP_ENDPOINT_PATHmcpHttpEndpointPath/mcpHTTP endpoint path — the one the route serves and every advertised URL carries (server card, protected-resource metadata, landing page, robots.txt). Normalized at startup: trimmed, a missing leading / added, dot segments removed, and the escapes the router decodes anyway decoded (/a%7Eb → /a~b); a trailing slash and an escaped % (%25, which the router never decodes) are kept. A URL (//host/mcp, https://… — the origin belongs in MCP_PUBLIC_URL), a query or fragment, whitespace, a control character, a backslash, a malformed % escape, or route syntax (*, {, }, a segment starting with :) fails startup with a ConfigurationError naming the variable
MCP_HTTP_MAX_BODY_BYTESmcpHttpMaxBodyBytes1048576 (1 MiB)Integer. Max inbound JSON-RPC request body; oversized requests get 413 before per-request allocation. Does not cap upstream data staged into a canvas or response sizes. 0 disables (defer to runtime/proxy). The only body limit in force — the SDK's own 4 MiB read cap never engages, so a value above 4 MiB holds as set.
MCP_HTTP_MAX_PORT_RETRIESmcpHttpMaxPortRetries15Integer ≥ 0. Rungs of the port ladder walked when a bind collides; each rung tries port + 1. See Port binding
MCP_HTTP_PORT_RETRY_DELAY_MSmcpHttpPortRetryDelayMs50Delay between port retries; integer ms, 0–2147483647
MCP_SESSION_MODEmcpSessionModeautostateless | stateful | auto; auto resolves to stateful. Under stateless, the 2025-era multi-round-trip shim still runs but its capability gate refuses: each request is served by an instance that never processed initialize, so the client-capability view is empty and a ctx.requestInput round can never be answered — fail-closed, but unconditional, so the tool is unusable for those clients rather than merely guarded. 2026-07-28 clients and stdio are unaffected. Seed it from code with createApp({ sessionMode }) — see below
MCP_STATEFUL_SESSION_STALE_TIMEOUT_MSmcpStatefulSessionStaleTimeoutMs180000030 min; stale session eviction; integer ms, 1–2147483647
MCP_HTTP_RESUMABILITYmcpHttpResumabilitytrueSSE stream replay under stateful HTTP. On by default — selecting a session mode is the opt-in. Kill switch only; no effect on stateless serving or the session-less 2026-07-28 era
MCP_HTTP_RESUMABILITY_MAX_EVENTSmcpHttpResumabilityMaxEvents512Events retained per session for replay; oldest evicted first. Lower it on a server whose tools return large results
MCP_HTTP_RESUMABILITY_TTL_MSmcpHttpResumabilityTtlMs3000005 min; how long a retained event stays replayable
MCP_ALLOWED_ORIGINSmcpAllowedOrigins—Comma-separated list of browser origins the MCP endpoint accepts; others get 403. Omitted, CORS is wildcard but only loopback origins pass; * accepts any origin (disables DNS-rebinding protection). An accepted origin's preflight also allows Mcp-Method, Mcp-Name, Last-Event-ID, and each tool's Mcp-Param-<Name> — see api-auth
MCP_SERVER_RESOURCE_IDENTIFIERmcpServerResourceIdentifier—RFC 8707 resource indicator URL
MCP_PUBLIC_URLmcpPublicUrl—Public-facing base URL for reverse proxies (Cloudflare Tunnel, nginx, ALB) so emitted URLs carry the correct scheme: an http or https scheme, a host, an optional port, and an optional path prefix (https://example.com/mcp-proxy); a trailing slash is dropped. The server card, the protected-resource metadata, the 401 challenge, and the landing page all render its serialized form (host punycoded, path percent-encoded). A query or fragment (empty included), user info, or another scheme fails startup with a ConfigurationError naming the variable; the message never repeats the value
MCP_HEARTBEAT_INTERVAL_MSmcpHeartbeatIntervalMs0 (disabled)Heartbeat ping interval; integer ms, 0–2147483647; 0 disables
MCP_HEARTBEAT_MISS_THRESHOLDmcpHeartbeatMissThreshold3Integer ≥ 1. Missed heartbeats before session is considered stale
MCP_GC_PRESSURE_INTERVAL_MSmcpGcPressureIntervalMs0 (disabled)Bun-only opt-in forced GC loop for HTTP deployments with heap growth; integer ms, 0–2147483647; 0 disables
Port binding

MCP_HTTP_PORT is where the HTTP transport starts, not necessarily where it ends up. Startup walks a ladder: bind MCP_HTTP_PORT, and on a collision wait MCP_HTTP_PORT_RETRY_DELAY_MS and try the next port, up to MCP_HTTP_MAX_PORT_RETRIES times. Read the bound port off the HTTP transport listening at … log line or the startup banner — with the defaults the server may be anywhere in 3010–3025. Pin the port by setting MCP_HTTP_MAX_PORT_RETRIES=0, which makes a collision a startup failure instead of a silent move.

  • Startup resolves only once the server reports 'listening'. A bind failure arriving after the listen call — a collision the pre-bind probe could not see, because another process took the port in between — is routed to the ladder like any other, not reported as a successful start.
  • A failure the ladder cannot clear rejects immediately. Each rung only changes the port, so EACCES (privileged port, typically <1024 as a non-root user) and EADDRNOTAVAIL (the MCP_HTTP_HOST address is not local to this machine) fail startup on the first attempt with the OS error as the rejection's cause, rather than burning every rung. Ladder exhaustion carries the last bind error as cause too, when a real bind attempt produced one.
  • Runtime caveat: Bun reports a permission-denied bind as EADDRINUSE where Node reports EACCES. On Bun a privileged port therefore reads as an ordinary collision and walks the whole ladder before failing with Failed to bind to any port after N retries. — on Node the same port fails on the first attempt, naming EACCES.

Auth

Env VarAppConfig fieldDefaultNotes
MCP_AUTH_MODEmcpAuthModenonenone | jwt | oauth
MCP_AUTH_SECRET_KEYmcpAuthSecretKey—Required for jwt mode; min 32 chars
MCP_AUTH_DISABLE_SCOPE_CHECKSmcpAuthDisableScopeChecksfalseWhen true, bypasses both withRequiredScopes (declared auth: [...]) and checkScopes (runtime/tenant scopes). Token validation (sig/aud/iss/exp) intact. Logs a WARNING at startup. See api-auth skill.
MCP_REQUEST_STATE_KEYmcpRequestStateKey—Opt-in, any auth mode. When set, the framework seals the requestState a handler returns with ctx.requestInput (bound to the request's clientId / subject / tenantId, valid 900 s) and every server instance rejects any other state as -32602 invalid_request_state before the handler runs; ctx.inputs.state() still returns the handler's string. Must be ≥ 32 UTF-8 bytes — shorter fails startup with a ConfigurationError naming the variable — and identical on every instance a retry can reach (stateless replicas, Worker isolates, restarts). Unset or empty: no verifier, state round-trips raw. See api-context § requestState
OAUTH_ISSUER_URLoauthIssuerUrl—Required for oauth mode
OAUTH_AUDIENCEoauthAudience—Required for oauth mode
OAUTH_JWKS_URIoauthJwksUri—Override JWKS endpoint (otherwise derived from issuer)
OAUTH_JWKS_COOLDOWN_MSoauthJwksCooldownMs3000005 min; min time between JWKS refetches; integer ms, 0–2147483647; 0 disables the cooldown
OAUTH_JWKS_TIMEOUT_MSoauthJwksTimeoutMs5000JWKS fetch timeout; integer ms, 1–2147483647
DEV_MCP_AUTH_BYPASSdevMcpAuthBypassfalseSkip auth in development; blocked in production. On Cloudflare Workers, honored only when the environment is explicitly development or testing, declared by ENVIRONMENT or by a NODE_ENV that reaches process.env; with the flag on and neither set, startup fails with a ConfigurationError naming DEV_MCP_AUTH_BYPASS and ENVIRONMENT. For local development, set ENVIRONMENT=development beside the flag
MCP_JWT_EXPECTED_ISSUERmcpJwtExpectedIssuer—Optional issuer validation for JWT mode; with a shared HS256 key it does not stop another service's token on its own — pair it with MCP_JWT_EXPECTED_AUDIENCE
MCP_JWT_EXPECTED_AUDIENCEmcpJwtExpectedAudience—Optional audience validation for JWT mode. Unset, any token signed with MCP_AUTH_SECRET_KEY is accepted whatever its aud, and a strategy that loads a key logs a WARNING at startup naming this variable
DEV_MCP_CLIENT_IDdevMcpClientId—Dev-only: override client ID
DEV_MCP_SCOPESdevMcpScopes—Dev-only: comma-separated scope overrides

Storage

Env VarAppConfig fieldDefaultNotes
STORAGE_PROVIDER_TYPEstorage.providerTypein-memoryin-memory | filesystem | supabase | cloudflare-r2 | cloudflare-kv | cloudflare-d1; aliases: mem, fs
STORAGE_FILESYSTEM_PATHstorage.filesystemPath./.storageUsed only when providerType is filesystem. Data lives under <path>/_v2/: a directory per tenant, a .json file per key, every name percent-encoded, so each tenant ID has a directory of its own and each key a file of its own. A tenant ID whose encoding passes the 255-byte name limit is named %% and its SHA-256 instead. A path in the earlier layout (tenant directories at its top level) is copied into _v2/ once, when the first provider over it is constructed, and left in place unread; a warning names it. An uppercase letter or . takes three bytes of the filesystem's 255-byte name limit, so a key's last /-separated segment holds at most 250 lowercase or 83 uppercase characters, and a longer one throws ValidationError before any filesystem call (a batch, before its first)

Canvas (DataCanvas primitive — Tier 3, optional peer dep @duckdb/node-api)

Env VarAppConfig fieldDefaultNotes
CANVAS_PROVIDER_TYPEcanvas.providerTypenonenone | duckdb. Set to duckdb to enable core.canvas. Fails closed on Cloudflare Workers (DuckDB has no V8-isolate build).
CANVAS_DEFAULT_MEMORY_LIMIT_MBcanvas.defaultMemoryLimitMb1024Per-canvas DuckDB memory_limit PRAGMA value, in MB; integer ≥ 64.
CANVAS_EXPORT_PATHcanvas.exportRootPath./.canvas-exportsSandbox root for path-targeted exports. Absolute paths and .. traversal are rejected.
CANVAS_TEMP_PATHcanvas.tempRootPathos.tmpdir()Parent of the provider's private scratch directory: on first use the DuckDB provider creates mcp-canvas-XXXXXX inside it (mkdtemp, 0700 on POSIX) for each canvas's own DuckDB temp_directory and the transient files behind stream exports and importFrom; shutdown removes it once the calls still running against it settle. Created if missing, with no ownership or mode check — must not be a directory another local user controls, and on Windows, where the private directory inherits the parent's ACL, must not grant other users access. Never resolves to the process cwd — DuckDB's own cwd-relative .tmp default fails on a non-root or read-only container rootfs.
CANVAS_MAX_CANVASES_PER_TENANTcanvas.maxCanvasesPerTenant500Integer ≥ 1. Active canvas cap per tenant; throws RateLimited when exceeded. Under MCP_AUTH_MODE=none every caller shares one tenant.
CANVAS_TTL_MScanvas.ttlMs86400000Sliding TTL (24 h). Every operation extends the expiry.
CANVAS_ABSOLUTE_CAP_MScanvas.absoluteCapMs604800000Absolute cap from creation (7 d). Sliding window clamps to this.
CANVAS_SWEEPER_INTERVAL_MScanvas.sweeperIntervalMs60000Background sweep interval; integer ms, 0–2147483647. Set to 0 to disable.
CANVAS_DEFAULT_ROW_LIMITcanvas.defaultRowLimit10000Default cap on rows materialized into a query response; a safe integer ≥ 1.
CANVAS_SCHEMA_SNIFF_ROWScanvas.schemaSniffRows100Rows to materialize for schema inference when schema is omitted; integer ≥ 1.

Platform support: Linux, macOS and Windows on x64 and arm64 have published prebuilt DuckDB bindings. See api-canvas for the DataCanvas API and distribution requirements.

Supabase (optional sub-object)

Activated when SUPABASE_URL is set.

Env VarAppConfig fieldNotes
SUPABASE_URLsupabase.urlRequired to activate
SUPABASE_SERVICE_ROLE_KEYsupabase.serviceRoleKeyRequired by the supabase storage provider (admin client)
SUPABASE_ANON_KEYsupabase.anonKeyOptional; for the server's own public client — the framework never reads it

LLM

Env VarAppConfig fieldDefaultNotes
OPENROUTER_API_KEYopenrouterApiKey—Optional; enables LLM provider
OPENROUTER_APP_URLopenrouterAppUrlhttp://localhost:3000Reported to OpenRouter
OPENROUTER_APP_NAMEopenrouterAppNamepackage.json nameReported to OpenRouter
LLM_DEFAULT_MODELllmDefaultModelgoogle/gemini-2.5-flash-preview-05-20OpenRouter model ID
LLM_DEFAULT_TEMPERATUREllmDefaultTemperature—Float
LLM_DEFAULT_TOP_PllmDefaultTopP—Float
LLM_DEFAULT_MAX_TOKENSllmDefaultMaxTokens—Integer ≥ 1; anything else fails startup
LLM_DEFAULT_TOP_KllmDefaultTopK—Integer ≥ 0 (0 considers every token); anything else fails startup
LLM_DEFAULT_MIN_PllmDefaultMinP—Float

Telemetry

Env VarAppConfig fieldDefaultNotes
OTEL_ENABLEDopenTelemetry.enabledfalseEnable OpenTelemetry export
OTEL_SERVICE_NAMEopenTelemetry.serviceNamecreateApp name → package.json nameSeeded from createApp({ name }) when unset; an env value wins
OTEL_SERVICE_VERSIONopenTelemetry.serviceVersionpackage.json version
OTEL_EXPORTER_OTLP_ENDPOINT——OTLP/HTTP base URL; resolves tracesEndpoint to <base>/v1/traces and metricsEndpoint to <base>/v1/metrics (path prefix kept) when the signal-specific variable is unset
OTEL_EXPORTER_OTLP_TRACES_ENDPOINTopenTelemetry.tracesEndpoint—OTLP traces endpoint URL; overrides the base, used as-is
OTEL_EXPORTER_OTLP_METRICS_ENDPOINTopenTelemetry.metricsEndpoint—OTLP metrics endpoint URL; overrides the base, used as-is
OTEL_EXPORTER_OTLP_LOGS_ENDPOINTopenTelemetry.logsEndpoint—OTLP logs endpoint URL; the only switch for log record export, never derived from the base. Needs the optional peers @opentelemetry/sdk-logs and @opentelemetry/exporter-logs-otlp-http
OTEL_TRACES_SAMPLER_ARGopenTelemetry.samplingRatio1.00–1; fraction of traces to export
OTEL_LOG_LEVELopenTelemetry.logLevelINFOOTel SDK internal log level: NONE | ERROR | WARN | INFO | DEBUG | VERBOSE | ALL; aliases warning→WARN, err→ERROR, information→INFO. Diag output goes to stderr at every level

Speech (optional sub-object)

Activated when SPEECH_TTS_ENABLED or SPEECH_STT_ENABLED is set.

TTS (Text-to-Speech)
Env VarAppConfig fieldDefaultNotes
SPEECH_TTS_ENABLEDspeech.tts.enabledfalseEnable TTS
SPEECH_TTS_PROVIDERspeech.tts.providerelevenlabsCurrently only elevenlabs
SPEECH_TTS_API_KEYspeech.tts.apiKey—Provider API key
SPEECH_TTS_BASE_URLspeech.tts.baseUrl—Override provider base URL
SPEECH_TTS_DEFAULT_VOICE_IDspeech.tts.defaultVoiceId—Default voice identifier
SPEECH_TTS_DEFAULT_MODEL_IDspeech.tts.defaultModelId—Default model identifier
SPEECH_TTS_TIMEOUTspeech.tts.timeout—Request timeout; integer ms, 1–2147483647
STT (Speech-to-Text)
Env VarAppConfig fieldDefaultNotes
SPEECH_STT_ENABLEDspeech.stt.enabledfalseEnable STT
SPEECH_STT_PROVIDERspeech.stt.provideropenai-whisperCurrently only openai-whisper
SPEECH_STT_API_KEYspeech.stt.apiKey—Provider API key
SPEECH_STT_BASE_URLspeech.stt.baseUrl—Override provider base URL
SPEECH_STT_DEFAULT_MODEL_IDspeech.stt.defaultModelId—Default model identifier
SPEECH_STT_TIMEOUTspeech.stt.timeout—Request timeout; integer ms, 1–2147483647

Server config (separate schema)

Define your own Zod schema for domain-specific env vars. Never merge with core's schema.

Use the lazy init/accessor pattern — do not parse process.env at module top-level.

// src/config/server-config.ts
import { z } from '@cyanheads/mcp-ts-core';
import { parseEnvConfig } from '@cyanheads/mcp-ts-core/config';

const ServerConfigSchema = z.object({
  apiKey: z.string().describe('External API key'),
  maxResults: z.coerce.number().int().min(1).max(500).default(100),
  verboseLogging: z.stringbool().default(false).describe('Enable verbose logging'),
});

export type ServerConfig = z.infer<typeof ServerConfigSchema>;

let _config: ServerConfig | undefined;

export function getServerConfig(): ServerConfig {
  _config ??= parseEnvConfig(ServerConfigSchema, {
    apiKey: 'MY_API_KEY',
    maxResults: 'MY_MAX_RESULTS',
    verboseLogging: 'MY_VERBOSE_LOGGING',
  });
  return _config;
}

Call getServerConfig() in createApp's setup(). The accessor alone parses on first read, which is usually the first tool call: an invalid value then lets the server report ready and fails every call instead, including tools that never read the bad variable. Calling it in setup() turns that into a startup failure — the ConfigurationError banner naming the variable, exit code 1, before any transport binds. On Workers setup() runs inside the first request, after injectEnvVars(), so the call is safe there too.

setup(core) {
  getServerConfig();
  initMyService(core.config, core.storage);
},

Env booleans — use z.stringbool(), never z.coerce.boolean(). z.coerce.boolean() runs Boolean(value), so "false", "0", and "no" all coerce to true — the flag becomes impossible to disable through the environment except by omitting it entirely. z.stringbool() parses true/false/1/0/yes/no/on/off (case-insensitive) and rejects anything else, so MY_VERBOSE_LOGGING=false actually disables and a typo fails loudly at startup instead of silently coercing. An empty string is not in that accepted set — z.stringbool() rejects '' with Invalid option. What makes a blank .env line take the default is the normalization layer described under Unset means unset below, not the schema type.

Env numbers — bound each one to the range its consumer accepts. z.coerce.number() alone fails startup only on a non-number (abc); -5, 0, 25.5, and 4294967296 all start the server. A value that feeds a timer then fails every call that builds it: AbortSignal.timeout() throws on a negative value (RangeError on Node, TypeError on Bun), Node also rejects a fractional one or one past 2^32 - 1, 0 times out before any request goes out, and setTimeout past 2^31 - 1 ms fires after 1 ms. Give every timer z.coerce.number().int().min(1).max(2_147_483_647) (one shared schema when several variables are timers) and every count or cap .int() with the min/max the code needs, so an out-of-range value stops startup with the banner naming the variable.

Unset means unset. parseEnvConfig and the framework's own config both treat an empty string and a whole-value ${…} placeholder — what an MCPB or plugin host forwards when a user leaves an option blank and nothing substitutes it — as the variable being absent: an optional field stays undefined, a defaulted field takes its default, and a required field fails as missing rather than as a format error against the literal text. A value that merely contains ${…} is kept. No per-field z.preprocess guard is needed for either case.

Why parseEnvConfig? It maps Zod schema paths to env var names so validation errors name the actual variable at fault. A missing MY_API_KEY produces:

Server config validation failed:
  - MY_API_KEY (apiKey): Invalid input: expected string, received undefined

Instead of a raw ZodError dump at startup. The framework catches the resulting ConfigurationError and prints a clean banner (full stack behind DEBUG=true). A failure inside a field names the variable that fed it, with the full schema path in parentheses — an array element a .transform()/.pipe() produced reads MY_ENDPOINTS (endpoints.0.url), a property of an object parsed from one JSON variable reads MY_DB_JSON (db.port). data.issues[].envVar carries the same variable.

Direct ServerConfigSchema.parse(...) still works — the framework intercepts raw ZodError thrown from setup() and converts it — but error messages won't know about env var names, so they show the Zod path (apiKey) instead of the variable name (MY_API_KEY). No normalization runs on that path either, so a blank MY_FLAG= arrives as '' and fails validation. normalizeEnv is exported from /config for exactly that case: normalize the values first, then parse.

Workers: Do not parse process.env at module top-level. In Workers, env bindings are injected at request time via injectEnvVars(), after all static imports. Lazy parsing is required.

Similar Skills

wayfinder

MAmattpocock/skills337k4,978 new stars in the last 7 days

grill-with-docs

MAmattpocock/skills337k4,978 new stars in the last 7 days

to-tickets

MAmattpocock/skills337k4,978 new stars in the last 7 days

loop-me

MAmattpocock/skills337k4,978 new stars in the last 7 days

to-spec

MAmattpocock/skills337k4,978 new stars in the last 7 days

implement-spec

MAmattpocock/skills337k4,978 new stars in the last 7 days