Skip to content

Latest commit

 

History

History
280 lines (228 loc) · 13.9 KB

File metadata and controls

280 lines (228 loc) · 13.9 KB

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
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
parseSSE function parse an SSE Response into an async generator — guide
SocketIOClient type the client handle
SocketIOClientConfig type config for createSocketIOClient
SocketEventMap type the shape of an event map
ParseSSEOptions type options for parseSSE

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
ALL_TRANSPORTS constant ['HTTP', 'MCP', 'AGENT']
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
TransportSource type http | mcp | agent — 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

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_FOUNDguide
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

Pagination

Export Kind Summary
paginatedSchema function the { items, nextCursor } Zod schema — guide
Paginated type the cursor-pagination envelope

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.serveguide
createHandler function the router as a bare (req) => Responseguide
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
ServerConfig type config for createServer / createHandler
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
createBearerResolver function a bearer-token identity resolver
verifyJwt function verify an HS256 JWT
extractToken function read a bearer token from header or cookie
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

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
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

Primitives

Export Kind Summary
streamSSE function an async generator → SSE Responseguide
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
getClientInfo function caller IP + user-agent
EventBus type the createEventBus handle
RateLimitConfig type config for createRateLimiter
ParseSSEOptions type options for parseSSE

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
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

stitchkit/tools

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 McpServerguide
implementRemote function bind a contract to a remote HTTP API — guide
mountAgent function a Vercel AI SDK ToolSet from a service — 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
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
ToolExtend type extra-args extension for mountMcp / mountAgent
ToolLifecycle type beforeHandle / afterHandle gate for tool calls — guide
ToolCallHooks type beforeToolCall / afterToolCall observability hooks
ToolResult type the result of one tool call
IncompatibleSchemaPolicy type 'throw' | 'skip' | 'warn'
McpMediaContent type a multimodal MCP content item

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
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.