import { type Server as HttpServer, type IncomingMessage, type ServerResponse } from "node:http"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { buildMcpServer, type ServeOptions, type ServerDeps } from "./index.js"; /** * Configuration for the HTTP transport. Extends ServeOptions so every * stdio-mode flag (--enable-write, --persistent-index, --watch, etc.) is * available over HTTP too. */ export interface HttpServeOptions extends ServeOptions { /** TCP port to listen on. */ port: number; /** * Bind host. Default 127.0.0.1 — explicit because remote-MCP must * opt-in to bind 0.0.0.0. Most users should keep it on localhost and * front it with Tailscale Funnel / Cloudflare Tunnel for remote access * (auth-and-encryption-in-depth). See docs/http-transport.md. */ host: string; /** * Bearer token. Comparing constant-time. Required: a missing token * fails closed at startup (we refuse to bind without auth). Generate * with: `node -e "console.log(require('crypto').randomBytes(32).toString('base64url'))"`. */ bearerToken: string; /** URL path prefix for the MCP endpoint. Default `/mcp`. */ mcpPath?: string; /** Max requests per minute per bearer token. Default 120. 0 disables. */ rateLimitPerMinute?: number; /** * CORS origin allowlist. Repeatable. Default empty (no * Access-Control-Allow-Origin sent). Bearer-credentialed requests work * cross-origin only when the origin is in this list. */ corsOrigins?: string[]; /** Optional path-prefix to match a /health probe under (e.g. for Tailscale). Default `/health`. */ healthPath?: string; /** * v2.14.0 — when `true`, the HTTP transport runs in stateful mode: * sessions are keyed by the `Mcp-Session-Id` header, each session has * its own `McpServer` + `StreamableHTTPServerTransport` pair, and * server-initiated notifications stream over a long-lived `GET /mcp` * SSE connection. Required for ChatGPT custom GPT actions and other * clients that expect persistent state across requests. Off by default * (stateless mode is the right choice for short-running tools and * minimizes attack surface). */ stateful?: boolean; /** * v2.14.0 — when stateful, evict sessions idle longer than this many * milliseconds. Default 30 minutes. Sweep runs lazily on every * request (no separate timer). Idle = time since the last * `handleRequest` for that session. */ sessionIdleTimeoutMs?: number; /** * v2.14.0 — max concurrent sessions. New sessions beyond this cap are * rejected with 503 + `Retry-After`. Default 100; protects against * memory exhaustion under adversarial create-and-abandon traffic. */ maxSessions?: number; /** * When `true` (default), registers SIGINT/SIGTERM/beforeExit listeners * for graceful shutdown of the HTTP server, vault, FTS5 index, watcher, * and persistent cache. Tests pass `false` to avoid leaking listeners * when spawning many `startHttpServer()` instances in one process — * cleanup happens via `httpServer.close()` which still triggers the * underlying resource cleanup. */ installSignalHandlers?: boolean; } /** * Sliding-window rate limiter. Per-token. Window is rolling 60 seconds. * Uses a tiny circular buffer of timestamps per token — O(burst-size) * memory per token, no GC churn (we trim when we check). * * NOT distributed. If the user runs multiple processes behind a load * balancer they'd want a shared store (Redis); deferred to v2.7+. */ declare class RateLimiter { private readonly perMinute; private readonly windows; constructor(perMinute: number); /** Returns true if request allowed; false if over budget. */ consume(tokenId: string, nowMs?: number): boolean; /** Test-only: reset all windows. */ reset(): void; } /** * Constant-time bearer-token compare. The Authorization header is * `Bearer ` per RFC 6750. We compare against the raw token * supplied at startup — both sides padded to a hash so timingSafeEqual * doesn't leak length. * * Returns the SHA-256 digest of the token (used as the rate-limit key) * if valid, or null if not. We never use the raw token as the key — a * compromised log dump would expose it. */ declare function verifyBearer(authHeader: string | undefined, expectedToken: string): string | null; /** Read the entire request body (UTF-8 JSON). Returns undefined for empty. */ declare function readJsonBody(req: IncomingMessage, maxBytes: number): Promise; /** * v3.7.13 H2 — detect a JSON-RPC 2.0 `initialize` request without parsing * the full envelope. The body can be either a single message or a batch * (JSON-RPC permits arrays); we accept both, requiring AT LEAST ONE * element in a batch to be `method: "initialize"`. Returns false on * anything else (including malformed bodies — the caller has already * parsed JSON, so the shape is unknown but not parse-error territory). * * @internal — exported only for tests. */ export declare function isInitializeRequest(body: unknown): boolean; /** * Build the request handler. Factored out of the listener-creation path * so tests can drive it without binding a TCP port. */ /** * v2.14.0 — one entry in the stateful-session map. Each session pairs an * `McpServer` instance with a `StreamableHTTPServerTransport` (in * stateful mode the SDK keys requests by the session id we assign at * `initialize` time) and tracks the last activity timestamp for * idle-eviction. * * v3.8.7 P2-10 — added `inFlight` refcount + `closing` flag to make * session lifecycle safe under concurrent requests: * - `inFlight > 0` means at least one HTTP handler is currently * awaiting `transport.handleRequest` on this session. The idle sweep * skips such sessions even if their `lastActivityMs` is past the * cutoff — closing a transport with an in-flight SSE/POST mid-stream * produces broken responses and dangling McpServer state. * - `closing` is set by the explicit shutdown paths (DELETE + sweep + * `closeAll`) right before we begin teardown. Once true, the entry * is also removed from `registry.sessions` so new gets return 404 — * concurrent requests that already hold a `session` reference can * finish naturally but won't be joined by new ones. */ interface StatefulSession { server: ReturnType; transport: InstanceType; /** Epoch-ms of the last `handleRequest` for this session. */ lastActivityMs: number; /** * v3.8.7 — count of ALL handlers currently inside `transport.handleRequest` * for this session (POST tool calls, the initialize handler, AND the * long-lived GET SSE stream). Incremented by `runWithRefcount`. `sweepIdle` * waits for this to be 0 before evicting — so a session with an open SSE * notification stream is never idle-evicted (it's an active client). */ inFlight: number; /** * v3.11.6-rc.21 (rc.20 re-sweep F1) — count of DRAINABLE requests only: POST * tool calls + the initialize handler, i.e. the requests whose responses / * mutations must be allowed to COMPLETE before teardown. Deliberately EXCLUDES * the long-lived GET SSE stream, which `handleRequest` keeps pending for the * entire stream lifetime (it resolves only when the stream ends). DELETE + * `closeAll` drain THIS counter, not `inFlight` — draining `inFlight` (rc.20) * made every clean DELETE with an open SSE block the full `DELETE_DRAIN_MS` * (the SSE never self-completes; the DELETE is precisely what terminates it), * a 5s regression on the flagship stateful path. Draining `inFlightCalls` * instead lets the DELETE tear the SSE down immediately while still waiting * for a genuine in-flight tool call. */ inFlightCalls: number; /** * v3.8.7 — once set, the session is being torn down. The entry has * already been removed from `registry.sessions`; new requests will * 404. Existing in-flight requests are allowed to finish. */ closing: boolean; } /** * v2.14.0 — exported for tests so they can poke at the session map * directly (idle eviction, max-cap, etc.) without spinning up a real * HTTP server. * * v3.8.7 P2-10/P2-11 — extended: * - `pendingInits` makes the maxSessions cap-check atomic across * concurrent initialize POSTs. The check is now * `sessions.size + pendingInits >= maxSessions`. Each init handler * increments before allocating server+transport and decrements in a * finally. Without this, N concurrent inits could all pass the * plain `size()` check and create N+ sessions. * - `closeAll(timeoutMs)` is the graceful-shutdown drain: waits for * in-flight requests up to `timeoutMs`, then closes every transport * + McpServer pair. Used by `shutdownHttpServer` so tests + * production both leave a clean process state (no leaked SQLite * handles via the per-session embedder + watcher hooks). */ export interface SessionRegistry { readonly sessions: Map; /** Sweep idle sessions older than `idleTimeoutMs`. Returns evicted count. */ sweepIdle(nowMs?: number): number; /** Total sessions currently tracked. */ size(): number; /** * v3.8.7 — count of in-flight `initialize` POSTs that have passed the * cap-check but not yet been inserted into `sessions`. Used by the * cap-check to prevent the TOCTOU race where N concurrent inits all * see `size() < maxSessions` and overshoot. Public so tests can * assert it stays balanced (always returns to 0 after init resolves). */ pendingInits: number; /** * v3.8.7 — graceful drain: mark all sessions as `closing`, wait up to * `timeoutMs` for in-flight requests to finish, then close every * transport + McpServer pair and clear the map. Returns the number of * sessions actually closed. Idempotent (second call is a no-op). */ closeAll(timeoutMs?: number): Promise; } export declare function createSessionRegistry(idleTimeoutMs: number): SessionRegistry; /** * v3.10.0-rc.65 (round-3 audit) — wrap the stateful fresh-initialize body with the * `pendingInits` reservation so the decrement runs in a `finally` on EVERY exit path, * including a throw from `buildMcpServer` or the `StreamableHTTPServerTransport` * constructor. Pre-rc.65 the `pendingInits += 1` and both constructors sat OUTSIDE the * try/finally, so a constructor throw skipped the decrement → the counter leaked * permanently, lowering the effective `maxSessions` cap by one each time until every * `initialize` returned 503 even with zero live sessions (the documented "always returns * to 0 after init" invariant was violated). Exported so the balance is unit-testable * with an injected throwing `fn` (NEGATIVE control). */ export declare function runWithPendingInit(registry: SessionRegistry, fn: () => Promise): Promise; /** * v3.7.12 M4 — parse the `maxFileBytes` ServeOptions field WITHOUT calling * back into `prepareServerDeps` (we only need the parsed number, not the * full vault). Returns `undefined` for unset / malformed / non-positive * input so the caller falls back to `DEFAULT_MAX_FILE_BYTES`. * * @internal — exported only for tests. */ export declare function parseMaxFileBytes(raw: string | undefined): number | undefined; /** * v3.7.12 M4 — derive the HTTP body-size cap from the vault's `maxFileBytes` * (or `DEFAULT_MAX_FILE_BYTES` when unset). Scales 1.5× to leave headroom * for the JSON-RPC envelope + string-escaping overhead, with a 4 MB floor * so tiny vaults don't shrink the cap below `tools/list` response size. * * @internal — exported only for tests. */ export declare function deriveHttpBodyCap(maxFileBytes: string | undefined): number; export declare function createHttpHandler(deps: ServerDeps, opts: HttpServeOptions, /** * v3.8.7 P2-11 — optional out-param. If provided, the function * assigns `.registry` to the stateful-mode `SessionRegistry` (or * `null` in stateless mode). `startHttpServer` uses this to wire the * registry into the `shutdownHttpServer` helper via the * `httpServerExtras` WeakMap. Existing call sites that don't pass * `out` are unaffected (backwards compatible). */ out?: { registry: SessionRegistry | null; }): (req: IncomingMessage, res: ServerResponse) => Promise; /** * Generate a fresh 32-byte base64url bearer token. Used by the * `enquire-mcp gen-token` subcommand. */ export declare function generateBearerToken(): string; /** Close an `http.Server` with a bounded grace (see {@link HTTP_CLOSE_GRACE_MS}). * Resolves as soon as `close()` completes, or after `graceMs` once stragglers * are force-closed — never hangs on a lingering keep-alive connection. * `graceMs` is injectable for tests; production callers use the default. */ export declare function closeServerBounded(server: HttpServer, graceMs?: number): Promise; /** * v3.8.7 P2-11 — graceful shutdown helper for an `http.Server` returned * by {@link startHttpServer}. Drains stateful sessions (if any), closes * the underlying TCP listener, then closes vault/fts/watcher/embed-db * handles owned by `prepareServerDeps`. * * Without this, callers that pass `installSignalHandlers: false` (the * test path, plus anyone managing the process lifecycle externally) * would silently leak: `httpServer.close()` alone closes only the TCP * accept loop, NOT the per-session McpServer + transport pairs in * stateful mode, and NOT the vault/fts/embed-db SQLite handles that * `prepareServerDeps` opens once at boot. * * Order matters: * 1. `registry.closeAll()` — bounded wait for in-flight requests to * finish, then close every transport + McpServer in stateful mode. * 2. `httpServer.close()` — stop accepting new connections + wait for * existing ones to drain. Node's http.Server doesn't actively * terminate keep-alive sockets unless we ask it to. * 3. Close vault, fts5 index, watcher, watcherEmbedDb — same order * as the SIGINT cleanup chain in startHttpServer. * * Idempotent: a second call on the same server is a no-op once extras * are unset. */ export declare function shutdownHttpServer(server: HttpServer): Promise; /** * v3.10.0-rc.19 (audit M3) — single SIGINT/SIGTERM orchestrator for the HTTP * transport. Returns a handler that awaits the FULL graceful teardown * ({@link shutdownHttpServer}: drain in-flight stateful sessions up to * `closeAll`'s bound → close the TCP listener → flush the persistent cache → * close fts/watcher/embed-db) and only THEN calls `exit`. * * Before rc.19, SIGINT/SIGTERM had FOUR separate listeners registered on the * same signal: a cache-`flush` handler, a `closeWatcher` handler, a `closeFts` * handler, AND the `shutdownHttpServer` handler. The flush handler called * `process.exit(0)` the moment its (fast) `saveDiskCache` resolved — racing * ahead of `shutdownHttpServer`'s up-to-5s session drain and cutting off * in-flight requests. The other three handlers were also pure redundancy: * `shutdownHttpServer` already flushes the cache and closes fts/watcher/embed-db * itself. Consolidating to ONE handler that awaits the whole chain removes the * race and the duplication. * * `exit` is injectable for tests (default `process.exit`). The returned handler * guards re-entry so a SIGINT-then-SIGTERM (or a double signal) can't kick off * two concurrent teardowns or two `exit` calls. */ export declare function makeHttpShutdownHandler(server: HttpServer, exit?: (code: number) => void): () => void; /** * Bind and start the HTTP transport. Returns the underlying http.Server * so callers (tests + CLI) can listen for `listening` / close it. */ export declare function startHttpServer(opts: HttpServeOptions): Promise; export { RateLimiter, readJsonBody, verifyBearer }; //# sourceMappingURL=http-transport.d.ts.map