Skip to main content

API Reference

Reference for the main integration APIs of @powerduck/openapi-request. The tables summarize contracts; the package TypeScript declarations are the complete source for overloads and optional parameters. Main-entry exports and protocol subpath exports are not identical.

Core​

createClient(options?): ProtoClient​

Builds the UI-first client. The options argument is optional.

Parameters:

NameTypeDescription
optionsCreateClientOptionsOptional configuration
options.writeBackWriteBackOptionsControl how responses are merged back into the spec
options.responseToResponseOptionsControl how response objects are normalized

Returns: ProtoClient with the following methods:

MethodSignatureDescription
prepare(sendOptions: SendOptions) => PreparedRequestPlan a request; returns protocol, display mode, and stream kind
send(sendOptions: SendOptions) => Promise<SendResult>Execute a request
sendMany(spec, targets, shared?) => Promise<SendManyResult>Batch execution; per-target results, failures never discard siblings
connect(connectOptions: ManualSessionOptions) => AnyManualSessionCreate an unopened session for websocket/mcp/grpc; call open() to connect
discover(discoverOptions) => Promise<any>Discover capabilities for MCP and gRPC
writeback(spec, prepared, result, writeOptions?) => OpenApiDocumentMerge observed response back into the document
dispose() => voidCurrently a no-op; callers must close their sessions
probeStreamingResponse(input: RequestInfo | URL, init?: RequestInit) => Promise<{ ok: boolean; status: number; contentType?: string; kind: "none" | "sse" | "ndjson" | "chunked"; response: Response }>Perform a fetch request and classify its response; consume or cancel the returned response body

Example:

import { createClient } from "@powerduck/openapi-request";

const client = createClient({
writeBack: { overwriteExamples: true },
});

const plan = client.prepare({
spec,
target: { operationId: "getUserById" },
});

const result = await client.send({
spec,
target: { operationId: "getUserById" },
values: { path: { id: "42" } },
});

createDebugger(config?): ProtoKit​

Builds the scripted debugger for automation, scripts, and CI.

Parameters:

NameTypeDescription
configDebuggerOptionsOptional configuration
config.adaptersProtocolAdapter[]Custom adapter list (replaces defaults)
config.extraAdaptersProtocolAdapter[]Extra adapters added to the defaults
config.writeBackWriteBackOptionsWrite-back options
config.responseToResponseOptionsResponse normalization options
config.writeBackTruncatedbooleanWrite back schema inferred from truncated streams (default: true)

Returns: ProtoKit with prepare, send, sendMany, toCollection, and more.

Example:

import { createDebugger } from "@powerduck/openapi-request";

const dbg = createDebugger({
writeBackTruncated: true,
});

const result = await dbg.send({
spec,
target: { operationId: "getUserById" },
values: { path: { id: "42" } },
serverUrl: "https://api.example.com",
});

createManualSession(options): AnyManualSession​

Creates a long-lived duplex session for WebSocket, MCP, and gRPC. The factory performs no I/O; connect lazily with open().

Parameters:

NameTypeDescription
options.kind"websocket" | "mcp" | "grpc"Protocol to use
options.urlstringWebSocket connection URL
options.endpointstringMCP Streamable HTTP endpoint
options.transport"streamable-http" | "stdio"MCP transport; default is Streamable HTTP
options.command, options.argsstring, string[]Local executable and arguments for MCP stdio
options.address, options.service, options.methodstringgRPC address, fully-qualified service and method

For gRPC, also provide a descriptor source through protoPaths or reflection. Protocol-specific options are listed in Configuration.

Returns: A session with open(), send(), close(), onEvent(), waitForClose(), events, and state. onEvent() returns a subscription with unsubscribe().

Example:

import { createManualSession } from "@powerduck/openapi-request";

const session = createManualSession({
kind: "websocket",
url: "wss://api.example.com/ws",
});

const subscription = session.onEvent((event) => {
console.log(event.kind, event.data);
});
try {
await session.open();
await session.send({ type: "message", data: "hello" });
} finally {
await session.close();
subscription.unsubscribe();
}

AdapterRegistry​

A registry of ProtocolAdapter instances. A new registry starts empty; createDebugger() registers the built-in HTTP, WebSocket, gRPC, MCP, and GraphQL adapters unless a custom list replaces them. Use register(), unregister(), get(), list(), rank(), and resolve() to manage selection.

ProtoKitError​

The typed error thrown by the debugger and core paths. Use instanceof ProtoKitError to distinguish library errors from unexpected failures.

Core Types​

SendOptions​

The primary input object for prepare() and send(). This is where you pass the spec, target, values, and all request-level configuration.

FieldTypeRequiredDescription
specOpenApiDocumentYesThe complete OpenAPI 3.2 document
targetOperationTargetYesOperation identifier (see below)
valuesRequestValuesNoConcrete values for path/query/header/cookie/body
serverUrlstringNoOverrides spec.servers[0].url
serverVariablesRecord<string, string>NoServer URL template variables
variablesRecord<string, string>NoEnvironment variables referenced as {{name}}
globalsRecord<string, string>NoPostman-style globals
localVariablesRecord<string, string>NoLocal variables
collectionVariablesRecord<string, string>NoCollection-level variables
authAuthConfigNoAuthentication configuration
scriptsScriptConfigNoPre-request and test scripts
runnerRuntimeRunOptionsNoFull postman-runtime option passthrough (highest precedence)
websocketWebSocketOptionsNoWebSocket-specific options
graphqlGraphQLOptionsNoGraphQL-specific options
mcpMcpOptionsNoMCP-specific options
grpcanyNogRPC-specific options
timeoutnumberNoPer-request timeout in ms (convenience shortcut for runner.timeout.request)

SendOptions also accepts these execution and streaming controls:

FieldTypeDescription
fetchtypeof fetchHost-supplied isolated fetch transport where supported; HTTP/SSE still use postman-runtime.
writeBackbooleanSet to false to leave patchedSpec undefined while still producing responseFragment.
signalAbortSignalCancel execution or sampling; a partial result can still be returned.
maxEventsnumberMaximum retained streaming events.
maxStreamMsnumberMaximum streaming sampling duration in milliseconds.
maxResponseSizenumberResponse byte limit.
maxBufferCharsnumberSSE parser buffer limit before an event boundary; default 4194304 characters.
maxEventCharsnumberRetained data limit per SSE event; default 1048576 characters.
inheritEventIdbooleanInherit the last SSE event ID when absent; default true. Set to false for stricter schema inference.
onEvent(event: StreamEvent) => voidReceive streaming events.
onConsole(log: ConsoleLog) => voidReceive script console output.
onAssertion(assertion: AssertionResult) => voidReceive assertion results.
onResponseStart(info: ResponseStartInfo) => voidInspect early HTTP/SSE headers and streaming classification.
onOpen(info) => voidReceive WebSocket connection details: URL, protocol and headers.

Protocol adapters may interpret limits differently. Keep UI callbacks lightweight; throwing callbacks are caught by the execution layer. For HTTP requester settings, use runner.requester; its maxResponseSize must be positive if provided, not zero.

OperationTarget​

Identifies a single operation. Prefer either operationId or method + path. If both are provided, operationId takes precedence.

FieldTypeDescription
operationIdstringAlternative lookup key; takes precedence over path + method
methodstringHTTP method, case-insensitive. Requires path.
pathstringTemplated path, e.g. /users/{id}. Requires method.

RequestValues​

Concrete values injected into the generated request.

FieldTypeDescription
pathRecord<string, unknown>Path parameter values
queryRecord<string, unknown>Query parameter values
headerRecord<string, unknown>Header values
cookieRecord<string, unknown>Cookie values
querystringstringRaw, pre-encoded query string (OpenAPI 3.2 querystring location)
bodyunknownRequest body
contentTypestringForce a specific request media type when the operation declares several
const result = await client.send({
spec,
target: { operationId: "updateUser" },
values: {
path: { id: "42" },
query: { version: "2" },
header: { "X-Request-Id": "abc-123" },
body: { name: "Alice", email: "alice@example.com" },
contentType: "application/json",
},
});

AuthConfig​

FieldTypeDescription
typeAuthConfig["type"]Auth type
tokenstringBearer token (for type: "bearer")
usernamestringBasic auth username (for type: "basic")
passwordstringBasic auth password (for type: "basic")
keystringAPI key name (for type: "apikey")
valuestringAPI key value (for type: "apikey")
in"header" | "query"API key location (for type: "apikey")
// Bearer token
const result1 = await client.send({
spec,
target: { operationId: "getUser" },
auth: { type: "bearer", token: "your-jwt-token" },
});

// Basic auth
const result2 = await client.send({
spec,
target: { operationId: "getUser" },
auth: { type: "basic", username: "admin", password: "secret" },
});

// API key in header
const result3 = await client.send({
spec,
target: { operationId: "getUser" },
auth: { type: "apikey", key: "X-API-Key", value: "key-123", in: "header" },
});

Advanced auth types are digest, oauth1, oauth2, jwt, hawk, aws4, ntlm, asap, and edgegrid. Pass their HTTP/SSE/GraphQL Postman helper fields through parameters: Record<string, string | boolean | number>. The optional oauth2: OAuth2FlowConfig enables token acquisition and refresh for the OAuth 2.0 type; do not assume every auth helper applies to every protocol.

PreparedRequest​

Returned by createClient().prepare(). The debugger has a different planning result: createDebugger().prepare() returns PlanResult with located, adapter, and plan.

FieldTypeDescription
protocolstringResolved protocol (http, websocket, grpc, graphql, mcp)
transportstringResolved transport
targetOperationTargetThe original target
operationanyThe resolved OpenAPI operation object
display.modeDisplayMode"response" | "event-list" | "duplex-session"
stream.kindStreamKindStreaming classification (see below)
stream.expectedbooleanWhether streaming is expected
openapi.extensionsRecord<string, unknown>Resolved OpenAPI extensions
warningsstring[]Warnings encountered during planning

StreamKind​

Precise streaming taxonomy: "none" | "sse" | "ndjson" | "chunked" | "websocket" | "graphql-stream" | "grpc-unary" | "grpc-server-stream" | "grpc-client-stream" | "grpc-bidi" | "mcp-http-stream" | "mcp-stdio"

OpenAPI Helpers​

ExportSignatureDescription
locateOperation(spec, target) => LocatedOperationResolve an operation by OperationTarget
inferSchema(value) => SchemaInfer a JSON Schema from a single observed value
inferSchemaFromMany(values) => SchemaInfer a schema that covers several observed values
mergeSchema(a, b) => SchemaMerge two inferred schemas (union/combination)
sampleFromSchema(schema) => unknownProduce a realistic example value for a schema
toResponseObject(result, options?) => { statusCode: string; response: any }Build an OpenAPI response object from an observed result
writeBackResponse(spec, path, method, fragment, options?) => specMerge an observed response back into the document

Type exports: LocatedOperation, WriteBackOptions, ToResponseOptions.

HTTP / SSE​

The following names are available from the main entry. The @powerduck/openapi-request/http subpath exports HttpAdapter, SseParser, buildCollection, buildEnvironment, resolveServerUrl, buildRunOptions, and runWithPostman; import detection helpers and BUILTIN_CAPTURE_TEST from the main entry.

ExportDescription
HttpAdapterThe default protocol adapter for HTTP/HTTPS
SseParserStreaming parser that turns an SSE byte stream into structured events
isStreamingOperationClassify an operation as streaming from declared content types
isSseContentTypeCheck if a content type indicates SSE
isStreamingContentTypeCheck if a content type indicates any streaming
acceptHeaderForGenerate the appropriate Accept header for an operation
probeStreamingResponsePerform a fetch request and classify its response; consume or cancel the returned response body
BUILTIN_CAPTURE_TESTBuilt-in Postman test script for capturing the last response

WebSocket​

Import from @powerduck/openapi-request/ws.

ExportDescription
WebSocketAdapterProtocol adapter for WebSocket targets
createWsManualSessionBuild a duplex WebSocket manual session (also aliased as runWebSocketSession, wsManualSession)

GraphQL​

Import from @powerduck/openapi-request/graphql.

ExportDescription
GraphQLAdapterProtocol adapter for GraphQL targets
resolveGraphQLConfigResolve GraphQL configuration from an operation
runGraphQLExecute a GraphQL operation
introspectSchemaIntrospect a GraphQL endpoint's schema
INTROSPECTION_QUERYThe standard GraphQL introspection query
generateOperationGenerate a query document from an introspected GraphQL schema and field
generateAllOperationsGenerate query documents for the fields of an introspected GraphQL schema
writeGraphQLOperationsWrite generated GraphQL operations back into the spec
discoverAndWriteGraphQLSchemaDiscover and write a GraphQL schema into the spec

MCP (Model Context Protocol)​

Most entries below are available from @powerduck/openapi-request/mcp. Import initializeMcpSession from the main entry; the subpath names it initializeSession. The subpath also exposes runMcp, createMcpSessionCore, and createMcpStdioConnection.

ExportDescription
McpAdapterProtocol adapter for MCP targets
createMcpManualSessionBuild an MCP manual session (also aliased as mcpManualSession)
createMcpStdioSessionBuild an MCP session over stdio
runMcpManualSessionDeprecated: use createMcpManualSession
resolveMcpConfigResolve MCP configuration from an operation
initializeMcpSessionInitialize an MCP session (aliased from initializeSession)
discoverMcpCapabilitiesDiscover MCP server capabilities
MCP_PROTOCOL_VERSIONThe supported MCP protocol version
generateMcpCallGenerate a single MCP tool call
generateAllMcpCallsGenerate all MCP tool calls
writeMcpOperationsWrite MCP operations back into the spec
discoverAndWriteMcpCapabilitiesDiscover and write MCP capabilities into the spec
createHttpMcpTransportCreate an HTTP transport for MCP
createStdioMcpTransportCreate a stdio transport for MCP

gRPC​

Import low-level discovery, invocation and descriptor helpers from @powerduck/openapi-request/grpc. Import GrpcProtocolAdapter, createGrpcManualSession, grpcManualSession, grpcDiscover, and discoverGrpc from the main entry; the subpath uses discover for discovery. The subpath also provides discoverFromCatalog, describeMethod, and describeFromCatalog so you can reuse a catalog instead of repeating reflection for each method.

ExportDescription
GrpcProtocolAdapterProtocol adapter for gRPC targets (OpenAPI-facing)
GrpcAdapterLow-level gRPC adapter
grpcDiscover / discoverGrpcDiscover gRPC services and methods
createGrpcManualSession / grpcManualSessionBuild a gRPC manual session
grpcCallExecute a single gRPC call
resolveMethodResolve a gRPC method descriptor
buildMessageTemplateBuild a message template from a descriptor
buildCatalogBuild a catalog of services and methods
LOADER_OPTIONSDefault proto loader options
scanProtoFilesScan directories for proto files
deriveIncludeDirsDetailedDerive include directories from proto file paths
fetchDescriptorSetFetch a descriptor set via gRPC reflection
fetchFullDescriptorSetFetch a full descriptor set with all dependencies
listServicesList services from a descriptor set
listServicesDetailedList services with detailed method information
serializeDescriptorSetSerialize a descriptor set to bytes
decodeFileDescriptorProtoDecode a single file descriptor proto
decodeFileDescriptorSetDecode a file descriptor set
buildCredentialsBuild gRPC credentials (synchronous)
buildCredentialsAsyncBuild gRPC credentials (asynchronous)
buildCredentialsCheckedBuild credentials with validation (synchronous)
buildCredentialsCheckedAsyncBuild credentials with validation (asynchronous)
loadGrpcDynamically load the @grpc/grpc-js package
isGrpcAvailableCheck if gRPC dependencies are available
requireCapabilityRequire a specific gRPC capability, throwing if unavailable

The main entry exports the type aliases GrpcDiscoveryResult, GrpcDiscoveredMethod, and GrpcDiscoveredService. The gRPC subpath names them DiscoveryResult, DiscoveredMethod, and DiscoveredService.

Error types: ReflectionProtocolError, ReflectionUnavailableError, DescriptorDecodeError, GrpcDependencyBrokenError, GrpcDependencyMissingError.

Additional utilities​

The main entry also exports OAuth 2.0 helpers: resolveOAuth2Token, acquireOAuth2Token, isOAuth2TokenExpired, oauth2RefreshStatuses, and authFromOAuth2Token; the clone utility toCloneable; the UnifiedSession base class; and gRPC write-back helpers writeGrpcOperations and discoverAndWriteGrpcOperations.

Subpath Exports​

// Main integration entry
import { createClient, createDebugger } from "@powerduck/openapi-request";

// Protocol-specific entries
import { HttpAdapter } from "@powerduck/openapi-request/http";
import { WebSocketAdapter } from "@powerduck/openapi-request/ws";
import { GrpcAdapter } from "@powerduck/openapi-request/grpc";
import { McpAdapter } from "@powerduck/openapi-request/mcp";
import { GraphQLAdapter } from "@powerduck/openapi-request/graphql";