API reference
Every public export of stitchkit, grouped by entrypoint. Each entry links to the
guide page that explains it in context. Types are marked type; everything else
is a value (a function, a class, a constant).
The root stitchkit entrypoint is browser-safe; stitchkit/server and
stitchkit/tools are server-only. See
Getting started → entrypoints.
stitchkit
The browser-and-server entrypoint. Re-exports everything from
stitchkit/contract, plus the client and browser realtime.
Client
| Export |
Kind |
Summary |
createClient |
function |
build a typed client from a contract — guide |
createClients |
function |
build one typed client per contract from a registry |
ClientConfig |
type |
config for createClient’s bare-fetch mode (2nd arg, no HttpClient) |
ContractClientConfig |
type |
per-tenant / resource-scoped client config — dynamic pathPrefix + stripPrefixKeys (guide) |
createHttpClient |
function |
the Ky-based HTTP transport — guide |
ApiError |
class |
a non-2xx response, with code / status / details / hint |
HttpClient |
type |
the transport interface createClient builds on |
HttpClientConfig |
type |
config for createHttpClient |
RequestOptions |
type |
per-call options — params, timeout, response type |
HeaderProvider |
type |
static or per-request headers |
ApiEvent |
type |
a client event — unauthorized / network_error / logout |
ApiEventListener |
type |
an ApiEvent handler |
Realtime (client) & streaming
| Export |
Kind |
Summary |
createSocketIOClient |
function |
the typed Socket.IO client — guide |
createRetainedTopics |
function |
retained last-value store for sticky events — guide |
parseSSE |
function |
parse an SSE Response into an async generator — guide |
SocketIOClient |
type |
the client handle |
SocketIOClientConfig |
type |
config for createSocketIOClient (incl. retain) |
SocketEventMap |
type |
the shape of an event map |
RetainedTopics |
type |
the createRetainedTopics handle |
ParseSSEOptions |
type |
options for parseSSE |
Trace (client)
Browser-safe W3C trace helpers — the same functions as on
stitchkit/observability, re-exported so a client
can emit / propagate a traceparent (see HttpClientConfig.trace).
| Export |
Kind |
Summary |
createTraceContext |
function |
a fresh root trace |
formatTraceparent |
function |
render a traceparent header value |
parseTraceparent |
function |
parse a traceparent header |
childSpan |
function |
a child span of a parent trace |
TraceContext |
type |
{ traceId, spanId, parentSpanId? } |
stitchkit/contract
The contract layer alone — browser-and-server safe. All of this is also exported
from the root stitchkit.
Contract
| Export |
Kind |
Summary |
defineContract |
function |
declare a contract — guide |
createContractFactory |
function |
a defineContract with a required, typed scope — guide |
ScopedDefineContract |
type |
the defineContract createContractFactory returns |
ALL_TRANSPORTS |
constant |
['HTTP', 'MCP', 'AGENT', 'CLI'] |
ContractDef |
type |
a defined contract |
ContractMeta |
type |
a contract’s prefix + optional scope |
EndpointDef |
type |
a single endpoint definition |
HttpMethod |
type |
GET | POST | PUT | PATCH | DELETE |
Transport |
type |
HTTP | MCP | AGENT | CLI |
TransportSource |
type |
http | mcp | agent | cli — the value of ctx.source |
RuntimeContext |
type |
the loose context seen by transport and hooks |
HandlerContext |
type |
the typed context seen by a handler |
EndpointFn |
type |
the call signature of one client method |
TypedClient |
type |
the full typed client for a contract |
TypedHttpClient |
type |
the typed client, HTTP endpoints only (= ScopedHttpClient<C, unknown>) |
ScopedHttpClient |
type |
a client whose stripPrefixKeys become required args (guide) |
ScopedEndpointFn |
type |
one method’s signature with the consumed keys folded in |
MultipartFile |
type |
a multipart file field — Blob | FileDescriptor |
FileDescriptor |
type |
a React Native / Expo file — { uri, name, type } |
EndpointToolAnnotations |
type |
MCP behavioural hints on an endpoint (readOnlyHint / destructiveHint / title) |
EndpointUiMeta |
type |
MCP Apps widget metadata on an endpoint |
Errors
| Export |
Kind |
Summary |
AppError |
class |
the framework error — code / status / details / hint |
ErrorEnvelope |
type |
the JSON shape of an error response |
notFound |
function |
throw 404 NOT_FOUND — guide |
badRequest |
function |
throw 400 BAD_REQUEST |
unauthorized |
function |
throw 401 UNAUTHORIZED |
forbidden |
function |
throw 403 FORBIDDEN |
conflict |
function |
throw 409 CONFLICT |
rateLimited |
function |
throw 429 RATE_LIMITED |
appError |
function |
throw an AppError for any code |
defineErrors |
function |
declare domain error codes → typed throwers + a code table — guide |
DefinedErrors |
type |
the { errors, codes, isCode } handle defineErrors returns |
ErrorThrower |
type |
one defineErrors thrower — (message?, details?, hint?) => never |
STITCH_ERROR_STATUS |
const |
code → HTTP status map for stitchkit’s own error codes — guide |
StitchErrorCode |
type |
a code stitchkit itself emits (keyof STITCH_ERROR_STATUS) |
isStitchErrorCode |
function |
type guard — is a code one of stitchkit’s own? |
| Export |
Kind |
Summary |
paginatedSchema |
function |
the { items, nextCursor } Zod schema — guide |
Paginated |
type |
the cursor-pagination envelope |
encodeCursor |
function |
encode a keyset value into an opaque nextCursor string (base64url, UTF-8-safe) |
decodeCursor |
function |
decode + Zod-validate a cursor back to its value (null if missing/invalid) |
stitchkit/server
Server-only. Builds and runs the HTTP server, and carries the server primitives.
Also re-exports the error helpers from stitchkit/contract.
Server & handlers
| Export |
Kind |
Summary |
createServer |
function |
build the router and start Bun.serve — guide |
createHandler |
function |
the router as a bare (req) => Response — guide |
implement |
function |
bind a contract to typed handlers — guide |
createImplement |
function |
fix the handler context type once |
staticRoute |
function |
a raw route that serves a directory |
serveFile |
function |
serve a file with Range / 304 / HEAD — guide |
parseByteRange |
function |
parse a single Range header → range / unsatisfiable / null |
weakETag |
function |
a weak ETag from size + mtime |
ServeFileOptions |
type |
options for serveFile |
ByteRange |
type |
an inclusive { start, end } byte range |
respondJson |
function |
a raw route’s JSON response (204 for null/undefined) |
errorResponse |
function |
any thrown value → the framework error envelope + x-request-id |
normalizeError |
function |
any thrown value → an AppError (ZodError → VALIDATION_ERROR 400 with structured details.issues, else generic 500) — the framework’s canonical classification, for a bespoke onError |
errorCode |
function |
the stable error code for a thrown value (side-effect-free — for log attribution) |
formatZodError |
function |
a ZodError → a readable, field-summarised string |
zodIssues |
function |
a ZodError → structured { path, code, message }[] — the machine-readable sibling of formatZodError |
ZodIssueSummary |
type |
one structured validation issue ({ path, code, message }) |
parseBody |
function |
parse + Zod-validate a JSON body → data or null (no throw) |
HandlerConfig |
type |
config for createHandler (runtime-agnostic) |
BunServerConfig |
type |
config for createServer (Bun) |
ServiceDef |
type |
the result of implement |
MethodDef |
type |
one resolved endpoint inside a service |
Handlers |
type |
the typed handler map implement expects |
LifecycleHooks |
type |
onRequest / beforeHandle / afterHandle / onError |
RouteGroup |
type |
a prefixed group of services with its own hooks |
RawRoute |
type |
a non-contract Request → Response route |
RawRouteContext |
type |
the routing context a raw handler receives |
BunServer |
type |
the Bun.serve instance type |
ServerPassthrough |
type |
extra Bun.serve options |
StitchLogger |
type |
the custom-logger interface |
Auth
| Export |
Kind |
Summary |
createAuthHook |
function |
a scope-enforcing beforeHandle hook — guide |
createErrorHook |
function |
an onError hook from a code map + envelope renderer — guide |
ErrorHookConfig |
type |
config for createErrorHook |
ResolvedError |
type |
the normalised error handed to createErrorHook’s render |
createBearerResolver |
function |
a bearer-token identity resolver |
signJwt |
function |
sign an HS256 JWT |
verifyJwt |
function |
verify an HS256 JWT |
extractToken |
function |
read a bearer token from header or cookie |
deriveCodeChallenge |
function |
PKCE — derive the code_challenge from a verifier |
verifyPkce |
function |
PKCE — verify a verifier against a stored challenge |
AuthHook |
type |
the hook createAuthHook returns |
AuthHookConfig |
type |
config for createAuthHook |
AuthRule |
type |
'public' | 'authenticated' | predicate |
BearerResolverConfig |
type |
config for createBearerResolver |
JwtPayload |
type |
a decoded JWT payload |
SignJwtOptions |
type |
options for signJwt (expiry, claims) |
PkceMethod |
type |
the PKCE challenge method — 'S256' | 'plain' |
Cookies & CORS
| Export |
Kind |
Summary |
defineCookie |
function |
a typed cookie get / set / clear handle — guide |
parseCookies |
function |
parse a Cookie header to a record |
serializeCookie |
function |
build a Set-Cookie value |
corsHeaders |
function |
compute CORS response headers |
corsPreflightResponse |
function |
build a preflight Response |
DEFAULT_CORS_ALLOW_HEADERS |
const |
the default Access-Control-Allow-Headers (incl. traceparent) — extend it when overriding cors.headers |
CookieDef |
type |
the defineCookie handle |
CookieOptions |
type |
cookie attributes |
CorsConfig |
type |
CORS policy |
Realtime (server)
| Export |
Kind |
Summary |
createSocketIOServer |
function |
the typed Socket.IO server — guide |
SocketIOServerConfig |
type |
config for createSocketIOServer |
SocketIOServerHandle |
type |
the { io, websocket, route } handle |
composeWebSocketHandlers |
function |
compose one Bun websocket from N lanes — a raw binary lane beside Socket.IO (guide) |
webSocketLane |
function |
a typed, cast-free lane for composeWebSocketHandlers |
socketIoLane |
function |
the Socket.IO catch-all lane for composeWebSocketHandlers |
ComposedLane |
type |
a lane bridged to the loose data type |
WebSocketLane |
type |
a typed lane ({ match, handlers }) |
WebSocketComposeConfig |
type |
server-wide tuning for the composed handler |
Primitives
| Export |
Kind |
Summary |
streamSSE |
function |
an async generator → SSE Response — guide |
parseSSE |
function |
parse an SSE Response (also on the root entrypoint) |
parseMultipart |
function |
parse a multipart/form-data request — guide |
createRateLimiter |
function |
token-bucket rate limiting — guide |
createCache |
function |
an in-memory TTL cache |
cacheHeaders |
function |
build a Cache-Control header |
createEventBus |
function |
typed in-process pub/sub — guide |
generateTraceId |
function |
a fresh trace id |
resolveTraceId |
function |
the default per-request trace-id resolver |
extractIp |
function |
the caller IP from a request |
resolveSocketIp |
function |
the caller IP for a Socket.IO handshake (proxy-aware) |
getClientInfo |
function |
caller IP + user-agent |
EventBus |
type |
the createEventBus handle |
RateLimitConfig |
type |
config for createRateLimiter |
ClientIpOptions |
type |
trusted-proxy config for extractIp / resolveSocketIp |
ParseSSEOptions |
type |
options for parseSSE |
OpenAPI
| Export |
Kind |
Summary |
generateOpenApiDocument |
function |
an OpenAPI 3.1 document from contract services — ADR 0018 |
openApiRoute |
function |
a RawRoute that serves the document as JSON |
OpenApiConfig |
type |
config for generateOpenApiDocument (incl. includeMethod — curate a public subset) — guide |
OpenApiDocument |
type |
the generated document |
OpenApiInfo |
type |
the spec info block |
OpenApiServer |
type |
a spec servers entry |
stitchkit/observability
Server-only. The audit layer one level above the raw hooks — W3C trace context,
an AsyncLocalStorage request context, payload sanitisation and a normalised
audit event. See the Observability guide.
Audit
| Export |
Kind |
Summary |
createAuditHook |
function |
wire both surfaces into one sink — guide |
RequestEvent |
type |
the normalised audit event handed to the sink |
AuditConfig |
type |
config for createAuditHook |
AuditHook |
type |
the { http, toolCall } the hook returns |
Request context
| Export |
Kind |
Summary |
wrapInRequestContext |
function |
run a fetch handler inside a request context — guide |
getRequestContext |
function |
the active request context |
getTraceId |
function |
the active trace id — pass as traceId to createServer |
getUserId |
function |
the active user id, once auth has resolved it |
setRequestUser |
function |
attach the resolved user to the active context |
setRequestEndpoint |
function |
attach the resolved endpoint identity to the active context |
setRequestDimensions |
function |
attach custom audit dimensions to the active context |
setRequestError |
function |
record the error outcome on the active context |
runWithRequestContext |
function |
run a function inside a given context |
RequestContext |
type |
the per-request record |
Trace context
| Export |
Kind |
Summary |
resolveTraceContext |
function |
the trace for a request — traceparent continued or fresh |
parseTraceparent |
function |
parse a traceparent header |
formatTraceparent |
function |
render a traceparent header value |
createTraceContext |
function |
a fresh root trace |
childSpan |
function |
a child span of a parent trace |
TraceContext |
type |
{ traceId, spanId, parentSpanId? } |
Sanitisation
| Export |
Kind |
Summary |
sanitizePayload |
function |
redact secrets and cap size — guide |
redact |
function |
mask secret-named keys, drop binary blobs |
truncatePreview |
function |
cap a value by serialised size |
measureSize |
function |
item count + byte size of a result |
JsonValue |
type |
a JSON-serialisable value |
SanitizeOptions |
type |
tuning for redact / sanitizePayload |
SizeMeasure |
type |
the result of measureSize |
Server-only. Turns contracts into MCP and AI-agent tools. Needs the
@modelcontextprotocol/sdk peer (for MCP) and the ai peer (for agents).
| Export |
Kind |
Summary |
createMcpHandler |
function |
a complete Streamable-HTTP MCP server — guide |
createStdioMcpServer |
function |
a complete stdio MCP server — guide |
buildMcpServer |
function |
build an McpServer from contracts — the transport-neutral core |
mountMcp |
function |
add contract tools to an existing McpServer — guide |
implementRemote |
function |
bind a contract to a remote HTTP API — guide |
mountAgent |
function |
a Vercel AI SDK ToolSet from a service — guide |
createCli |
function |
a command-line program from contracts — guide (also on stitchkit/cli) |
createToolkit |
function |
context-typed tool mounts — guide |
mountViewFile |
function |
a native multimodal “view file” MCP tool |
resolveMedia |
function |
resolve a media reference for a tool result |
validateMcpSchemas |
function |
assert every tool schema is JSON Schema-compatible — guide |
listToolNames |
function |
every mounted tool name with its (service, method) identity — for name-baseline snapshots — guide |
McpHandlerConfig |
type |
config for createMcpHandler |
StdioMcpServerConfig |
type |
config for createStdioMcpServer |
McpServerBuildConfig |
type |
shared config for buildMcpServer |
ImplementRemoteOptions |
type |
options for implementRemote |
McpMountConfig |
type |
config for mountMcp |
AgentMountConfig |
type |
config for mountAgent |
AgentContext |
type |
the context merged into agent tool handlers |
CliConfig |
type |
config for createCli |
CliWaitConfig |
type |
--wait polling config |
ExitCodeMap |
type |
ToolResult.code → process exit code |
Toolkit |
type |
the context-pinned tool surface from createToolkit |
ToolExtend |
type |
extra-args extension for mountMcp / mountAgent |
ToolLifecycle |
type |
beforeHandle / afterHandle gate for tool calls — guide |
ToolCallHooks |
type |
beforeToolCall / afterToolCall observability hooks |
ErrorHintFn |
type |
(toolName, errorCode) => string | null — a per-tool recovery hint, shared by every mount |
ToolResult |
type |
the result of one tool call |
ToolNameEntry |
type |
one listToolNames row — { name, service, method, transports } |
IncompatibleSchemaPolicy |
type |
'throw' | 'skip' | 'warn' |
McpMediaContent |
type |
a multimodal MCP content item |
Generic host-supplied tools mounted onto a server — not derived from a contract.
| Export |
Kind |
Summary |
mountDownload |
function |
a “download a URL to disk” tool (SSRF-guarded, size-capped) |
mountUpload |
function |
an “upload a local file” tool |
mountWait |
function |
a generic --wait-style polling tool |
DownloadToolConfig |
type |
config for mountDownload |
UploadToolConfig |
type |
config for mountUpload |
WaitToolConfig |
type |
config for mountWait |
OAuth 2.1 provider
A native remote-connector auth surface for MCP — guide.
| Export |
Kind |
Summary |
mountOAuthProvider |
function |
the OAuth 2.1 provider routes (DCR, PKCE, token) |
oauthProtectedResourceRoute |
function |
the RFC 9728 protected-resource-metadata route |
protectedResourceMetadataUrl |
function |
build the metadata URL for a resource |
wwwAuthenticateHeader |
function |
build the WWW-Authenticate challenge header |
PROTECTED_RESOURCE_PATH |
const |
the well-known metadata path |
OAuthProviderConfig |
type |
config for mountOAuthProvider |
ProtectedResourceConfig |
type |
config for oauthProtectedResourceRoute |
ApplicationType |
type |
DCR application_type — 'native' (loopback allowed) | 'web' (https only) |
AuthCodeData |
type |
a stored authorization-code record |
AuthRequest |
type |
a parsed authorization request |
ClientMetadata |
type |
dynamic-client-registration metadata |
RefreshData |
type |
a stored refresh-token record |
RegisteredClient |
type |
a registered OAuth client |
Interactive MCP resources — ADR 0019.
| Export |
Kind |
Summary |
mountMcpResource |
function |
mount an MCP Apps widget resource |
inlineMcpAppBundle |
function |
inline a built widget bundle into a resource |
EXT_APPS_BUNDLE_PLACEHOLDER |
const |
the placeholder token inlineMcpAppBundle replaces |
RESOURCE_MIME_TYPE |
const |
the MCP Apps resource MIME type |
McpResourceDef |
type |
an MCP Apps resource definition |
McpAppResourceMeta |
type |
resource _meta for an MCP App |
McpAppCsp |
type |
the widget content-security policy |
Introspection & internals
Advanced building blocks — the shared machinery the mounts are built on.
| Export |
Kind |
Summary |
collectTools |
function |
resolve a service’s methods to mountable tools (the shared resolver) |
createToolLogger |
function |
a ready afterToolCall that logs every tool call — guide |
summarizeTransports |
function |
per-transport operation counts for a boot-time summary |
buildToolManifest |
function |
a searchable { name, description, inputSchema } manifest for a tool_search tool |
ToolLoggerConfig |
type |
config for createToolLogger |
ToolCallRecord |
type |
the structured record createToolLogger passes to onRecord |
TransportSummary |
type |
the result of summarizeTransports |
TransportCounts |
type |
per-transport counts ({ HTTP, MCP, AGENT, CLI }) |
coerceJsonArgs |
function |
coerce JSON-stringified array/object tool arguments |
flattenDiscriminatedUnion |
function |
flatten one discriminated union into a single object schema |
flattenUnionsDeep |
function |
flatten discriminated unions at every depth (advertised schema only) |
MountableTool |
type |
one contract method resolved for mounting |
ToolManifestEntry |
type |
one buildToolManifest row |
stitchkit/node
Server-only, for Node ≥ 22 (Bun uses stitchkit/server). The runtime-agnostic
core plus a Node HTTP adapter — ADR 0013,
deployment guide. Re-exports the
runtime-agnostic pieces of stitchkit/server and the error helpers.
| Export |
Kind |
Summary |
serveNode |
function |
build the router and start a Node HTTP server (via srvx) |
createHandler |
function |
the router as a bare (req) => Response (same as /server) |
createSocketIOServer |
function |
the typed Socket.IO server (same as /server) |
implement / createImplement |
function |
bind a contract to typed handlers (same as /server) |
NodeServerConfig |
type |
config for serveNode |
NodeServerHandle |
type |
the serveNode handle ({ port, stop }) |
HandlerConfig / ServiceDef / RawRoute / RawRouteContext / SocketIOServerConfig / SocketIOServerHandle |
type |
re-exported from /server |
AppError + appError / badRequest / unauthorized / forbidden / notFound / conflict / rateLimited |
— |
error helpers (same as /contract) |
stitchkit/cli
Server-only. Turns contracts into a command-line program — the fourth transport.
Light by design: needs neither the MCP SDK nor the ai peer.
| Export |
Kind |
Summary |
createCli |
function |
build and run a CLI from contracts — guide |
parseCliArgs |
function |
argv → typed tool args against a schema (advanced) |
pollUntilDone |
function |
the generic --wait poller (advanced) |
emitResult |
function |
write a ToolResult to stdout/stderr + exit code (advanced) |
DEFAULT_EXIT_CODES |
const |
the default ToolResult.code → exit-code map |
CliConfig |
type |
config for createCli |
CliRunOptions |
type |
parsed global flags (--json, --wait, …) |
ParsedCliArgs |
type |
result of parseCliArgs |
CliWaitConfig |
type |
per-command --wait polling config |
ExitCodeMap |
type |
ToolResult.code → process exit code |
PollParams |
type |
params for pollUntilDone |
CliWriters |
type |
stdout/stderr sinks for emitResult |
EmitOptions |
type |
options for emitResult |
stitchkit/react
Browser-only. The React data-layer helpers. Needs the @tanstack/react-query
and react-query-kit peers.
| Export |
Kind |
Summary |
createCursorQuery |
function |
a cursor-paginated infinite query — guide |
createCacheBridge |
function |
sync socket events into the Query cache — guide |
createEntityCacheHandlers |
function |
created/updated/deleted cache handlers for one entity — guide |
EntityCacheConfig |
type |
config for createEntityCacheHandlers |
EntityCacheHandlers |
type |
the { created, updated, deleted } handlers it returns |
DeletedPayload |
type |
a deleted event payload — the entity or a bare { id } |
CursorQueryConfig |
type |
config for createCursorQuery |
CacheBridge |
type |
the createCacheBridge handle |
CacheBridgeConfig |
type |
config for createCacheBridge |
CacheBridgeContext |
type |
the ctx a bridge handler receives |
CacheBridgeHandler |
type |
one event-to-cache handler |
CacheBridgeHandlers |
type |
the handler map |
CacheBridgeSocket |
type |
the minimal emitter a bridge accepts |
For the rationale behind these APIs — why Bun.serve and not a framework, why
two context types, why thin wrappers — see the
Architecture Decisions.