Services and API imports · OpenAPI APIs
Services and API imports · OpenAPI APIs from the built-in skills in Executor 2.0.0-beta.79.
This page covers OpenAPI APIs from the built-in skills shipped with Executor 2.0.0-beta.79. It contains app-authoring/integrations.md.
Previous: Services and API imports · Check an MCP account · Next: Services and API imports · Session cookies
OpenAPI APIs
Call liveOpenapiRouter from apps/openapi with ctx.cache, ctx.fetch,
the signal and an account: each of a provider.many() user requirement’s
accounts through accountRouter, as for MCP, or a plain app requirement’s
ctx.app.accounts.service for one account every caller uses. It returns the router at once, then
downloads and compiles the definition inside the app when its tools are listed
or called, caching each revision; no extra dependency is needed. Pass the
settings the definition cannot be trusted to decide:
source:{ url }for a public definition (up to 40 MB), or{ document }: Swagger 2.0 or OpenAPI 3.0, 3.1 or 3.2. Theurlis fetched without account credentials; see private definitions.allowedOrigin: the origin that may receive credentials, or a list of a service’s own origins, such as its API and upload hosts. Operations on any other origin are left out.baseUrloverrides the definition’s server.securitySchemes: usuallycomponents.securitySchemesfrom the definition. A security alternative naming a scheme not listed here is ignored, so list only the schemesmethodsoroauthfill.methods: which account fields fill each scheme for eachsecretsmethod, e.g.{ apiKey: [{ scheme: "bearerAuth", field: "token", part: "value", prefix: "" }] }. Basic auth bindsusernameandpasswordparts. Anoauth2method can fill a scheme here too, through itsaccess_tokenfield. Use this when the definition declares only an http bearer scheme:{ oauth: [{ scheme: "bearerAuth", field: "access_token", part: "value", prefix: "" }] }. List such a method inmethodsonly, not inoauth.oauth: names ofoauth2provider methods, each named like the OpenAPIoauth2scheme it fills. This fills onlyoauth2and OpenID Connect schemes. Declare those methods as in accounts.md, preferringdiscover.- Optional
fallbackSecuritywhen the definition declares no security, andpatchesfor mistakes in a definition you do not control. Each patch is{ op: "add" | "remove" | "replace", path, value }, withpatha JSON Pointer through objects only: every segment before the last must name an existing object, so a pointer cannot index into an array. Replace the whole array at its key instead.addcreates or overwrites a key;removeandreplaceneed it to exist. - Optional
pathPrefix, such as/projects/{project}, when the definition’s paths omit leading segments. It goes between the server and every path; each{name}becomes a required path parameter of every tool. - Optional
kinds, keyed by operationId, when an operation’s HTTP method misclassifies it as a query or mutation.
Tools are grouped by the operation’s first tag, or its first path segment:
operationId listProjects tagged projects becomes
projects.listProjects, and accounts_connect tagged accounts
becomes accounts.connect. Both parts are camelCased from their words: tag
Team Members with operationId list_team_members becomes
teamMembers.listTeamMembers, and GetUserByID becomes getUserById.
Without an operationId the name comes from the method and path. A fixed query
or fragment in a declared path, as in /search?type=items, is not part of the
name; the query is sent before the operation’s parameters and the fragment is
not sent. Names that
collide, whether or not they come from operationIds, are told apart in this
order: first the path’s version segment, as in users.v2.listUsers; then the
path segments that differ, so GET /builds and GET /builds/{build_num} become
builds.getBuilds and builds.getBuildsByBuildNum; then the whole path; then
the HTTP method; then a stable hash. Each step applies only to names that still
collide. kinds still uses the original operationId. Discover the exact names
with search, or before an account connects as below.
Operations the helper cannot represent, and operations whose security needs
another method, are left out rather than failing the app. One whose every
security alternative names an undeclared scheme is left out with
auth_method. Reading or calling a
left-out operation’s tool fails with why, such as the JSON Pointer of an
invalid schema. When none can be imported, the router’s error lists the
operations left out and why, and the origins the operations use when none
matches allowedOrigin. Both end by offering a
custom tool. Public APIs need no
account: call liveOpenapiRouter without accountRouter and with
methods: {} and oauth: []. openapiRouter is the lower-level helper for
normalized metadata. Use contentType to choose an alternate declared request
media type. Binary request bodies and multipart binary fields take base64
strings. Binary responses return { base64, contentType }; text and JSON
sequences (NDJSON, JSON Lines, json-seq) return text. An operation that can
answer with an event stream or another type asks for the other type; one that
answers only with an event stream is not a tool. Success responses have
a 16 MiB / 30-second read bound. Live SSE
requires an authored subscription.
A call resolves to the response body itself, never { status, body }: parsed
JSON, text, the binary object above, or null for 204 and HEAD. A failure
status rejects the call instead. The output type comes from the definition’s
success responses. When one declares no content, or JSON content without a
schema, the signature says Promise<unknown>. Results are not checked against
the declared schema, so check the fields you use.
OpenAPI apps return documented errors with an exact HTTP status, a required
literal _tag, and either a declared string message or a schema description.
Local component references and plain anyOf alternatives are supported. A matching JSON failure returns its
code, status, and message in MCP’s execution.error.response. The message comes
from the validated response field, or static documentation when the declaration
has no message field. Messages are limited to 4,096 characters. A body recovery
object with non-empty action and instructions strings is also returned as
response.recovery, and error.message ends with Recovery: <action>. A missing
or malformed recovery is ignored. Other payload fields, headers, and stacks are
not forwarded.
Authentication and rate limits keep their existing provider-error handling.
Unknown, malformed, oversized, or stalled error bodies use the generic failure. It
names the operation’s method and templated path, such as GET /items/{item}, and
the response’s status, media type, and declared length, but never its body.
Inside an execute program’s catch, CodeMode exposes only error.message.
For these declared API errors it contains JSON with code, status,
message, and an optional recovery; parse it with JSON.parse. Other failures are ordinary diagnostic
strings, so guard that parse. A failed mutation may already have made changes;
inspect its state before retrying.
Tool names before an account connects
An account’s tools are listed only once it connects. openapiToolNames from
apps/openapi reads the definition with the router’s options, minus cache,
account and parameterDefaults, and resolves to { tools, skipped }. Each
tool has its name as withApprovals receives it, method, path (with any
pathPrefix), kind, and which methods and oauth entries expose it
(public when it needs no credentials). skipped lists only the operations the
compiler left out, and why. An operation that no methods or oauth entry can
authorize is missing from tools and not listed in skipped. To check the
names an approval policy uses before deploying, keep the options and the policy
in their own module:
// openapi.ts; index.ts imports it as "./openapi.js"
import type { OpenapiToolNamesOptions } from "apps/openapi";
import { always } from "apps/operations/approval";
export const options = {
source: { url: "https://api.example.com/openapi.json" },
allowedOrigin: "https://api.example.com",
securitySchemes: {},
methods: {},
oauth: [],
} satisfies OpenapiToolNamesOptions;
export const approvals = new Map([["projects.deleteProject", always()]]);
In index.ts, wrap the router with
withApprovals(liveOpenapiRouter({ ...options, cache, fetch, signal, account }), (_, name) => approvals.get(name)).
After installing the app’s packages as in deploy.md, run this in
the app directory with Bun. Plain node cannot run it once openapi.ts
imports a sibling module as ./patches.js: Node strips types but does not map
.js imports to .ts files. On Node, use npx tsx --input-type=module -e
in place of bun -e.
bun -e '
import { openapiToolNames } from "apps/openapi";
import { approvals, options } from "./openapi.ts";
const names = new Set((await openapiToolNames(options)).tools.map((tool) => tool.name));
const unknown = [...approvals.keys()].filter((name) => !names.has(name));
if (unknown.length) throw new Error(`No tools named ${unknown.join(", ")}`);
console.log([...names].join("\n"));'
Custom tools beside generated ones
Generated tools are a starting point, not a limit. When an operation is left
out, a generated tool is modelled or gated wrongly, or the definition itself is
wrong (such as security: [] on calls that need a key), write a query or
mutation for it in the same app (tools.md). Return it from its own
accountRouter callback, so it calls the API with the account the generated
tools use (accounts is ctx.user?.accounts.service ?? [] here):
tools: router({
api: await accountRouter(
accounts,
(account) => liveOpenapiRouter({ ...options, cache, fetch, signal, account }),
{ signal },
),
custom: await accountRouter(
accounts,
(account) =>
router({
uploadFile: mutation(
{ description: "Upload a file", input: object({ name: string(), base64: string() }) },
async ({ fetch }, input) =>
decodeJson(
await fetch("https://api.example.com/v1/files", {
method: "POST",
headers: { Authorization: `Bearer ${account.fields.token}` },
body: JSON.stringify(input),
}),
object({ id: string() }),
),
),
}),
{ signal },
),
}),
Give it its own approval. To hide the generated tool it replaces, remove that
operation with patches. The same works beside mcpRouter and
graphqlRouter, but an MCP OAuth token often works only for its MCP server:
call the service’s REST API through a provider of its own.
The key renames every generated tool: projects.listProjects becomes
api.projects.listProjects. Update skills and callers that use the old names.
Private definitions
When the definition itself needs the account’s credentials, load it in a cache
scoped to the account and pass it as source: { document }. record(json())
from apps accepts any JSON object:
async (account) => {
const url = "https://api.example.com/openapi.json";
const document = await cache.forAccount(account).get({
key: ["openapi-definition", url],
schema: record(json()),
freshFor: "1 hour",
load: async ({ fetch, signal }) =>
decodeJson(
await fetch(url, { signal, headers: { Authorization: `Bearer ${account.fields.token}` } }),
record(json()),
),
});
return liveOpenapiRouter({ ...options, source: { document }, cache, fetch, signal, account });
};
A cache entry holds up to 2 MB. Reconnecting the account starts an empty scope.