You can add paid services to a custom agent through a small server-side HTTP adapter. Use it to discover a capability, inspect the required inputs, and turn an approved task into a tracked invocation. The same interface can serve research, extraction, or media features without a separate transport client for every provider.
This guide builds that adapter in Bun, then explains how to place a domain tool around it and recover pending work. Your application keeps the decisions that make the result useful: which task is authorized, which account it uses, and what output passes review.
Keep the integration on the server
The browser should call your application’s authenticated endpoint. That endpoint determines the workspace, user access, and permitted task before using the execution credential. Do not embed an o11 application key in client-side JavaScript.
Use the public POST /v1/{operation} contract with the configured HTTPS origin and scoped key for your environment. Paid execution also needs an activated supplier path, reviewed pricing, and explicit limits. The examples here are based on the implemented contract; live-verification limits are stated below.
The model should receive a narrow domain tool such as “retrieve evidence for this approved URL.” It does not need an unrestricted HTTP proxy or the ability to select arbitrary supplier credentials. Keep the mapping from domain action to tool identifier in trusted configuration.
Use separate credentials for development and production, and for applications with different authority. A shared transport module can be reusable without sharing one unrestricted credential across every project.
For the broader architecture, see one API key for multiple tools. The important distinction is between a common interface and unlimited authority.
Create a minimal HTTP adapter
Save the following as o11-http.ts in your server project. Bun provides the Fetch API used by this adapter. Bun Fetch.
export class O11HttpError extends Error {
constructor(
readonly status: number,
readonly detail: unknown,
) {
super(`o11 request failed with HTTP ${status}`);
}
}
export function createO11Http(origin: string, apiKey: string) {
const base = new URL(origin);
if (base.protocol !== "https:") throw new Error("HTTPS required");
const operations = new Set([
"discover", "inspect", "quote", "invoke", "get_invocation",
"get_configuration", "connections", "balance", "cancel",
]);
return async function call(operation: string, input: unknown) {
if (!operations.has(operation)) throw new Error("Unsupported operation");
const response = await fetch(new URL(`/v1/${operation}`, base), {
method: "POST",
redirect: "error",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify(input),
});
const detail: unknown = await response.json();
if (!response.ok) throw new O11HttpError(response.status, detail);
return detail;
};
} This adapter deliberately returns unknown. Validate the fields you consume with your application’s schemas. It does not add automatic retries, because retrying accepted external work requires the original intent and lifecycle context.
The operation allowlist also prevents accidental path construction from arbitrary model output. It is a client-side guard, not a replacement for server authorization.
Discover and inspect the operation
Create a separate setup script that uses your environment values:
import { createO11Http } from "./o11-http";
const origin = process.env.O11_TOOLS_URL;
const key = process.env.O11_API_KEY;
if (!origin || !key) throw new Error("Missing configuration");
const call = createO11Http(origin, key);
const candidates = await call("discover", { query: "search" });
console.log(candidates);
// After choosing an actual returned identifier:
// const definition = await call("inspect", { id: selectedId }); Run it with bun discover-tools.ts. The request searches the caller’s allowed catalog. Inspect an actual returned identifier and record its input contract, account requirements, pricing evidence, and lifecycle.
Do not hardcode an invented supplier tool identifier from a blog example. Tool names and contracts need to come from the environment you are using. A source alias or catalog definition also does not prove live supplier activation.
Discovery responses contain items and may contain a continuation cursor. Each item includes an identifier, name, provider, and price reference. Preserve the cursor when your setup screen needs more results; do not silently treat a first-page miss as a complete catalog search.
Keep discovery out of the hot path when the application already knows its approved operation. Production can use a reviewed configuration and rediscover during deliberate updates. The tool discovery guide explains that boundary.
Define a domain tool the model can use
Expose an application-owned input, such as a URL and a requested evidence type. Validate the URL and task against your own product rules. Then map it into the inspected supplier contract on the server.
Keep account mode, connection identifier, maximum cost, and write permissions outside model-selected parameters unless the product has a specific authorized reason to expose them. The model should not be able to expand its authority by changing a JSON field.
A domain output should include result state and provenance. For example, return a completed evidence record, a pending invocation reference, or a clear unsupported result. Avoid returning a raw provider object and expecting every downstream prompt to infer its meaning.
This adapter is also your portability boundary. If you change providers or adopt a gateway later, the model-facing operation can remain stable while the supplier mapping changes. Our reusable tool layer guide develops that pattern across projects.
Prepare and persist one execution intent
The o11 invocation envelope includes toolId, idempotencyKey, input, credentialMode, and maxCostMicros. Inputs use pathParams, queryParams, optional body, and headers. Customer-account mode may also need an allowed connectionId.
Before dispatch, persist the approved input and a stable idempotency key in your application’s durable task record. Use the same key and request when recovering that intent after a lost response. A changed input represents a new intent and needs its own authorization decision.
Do not generate the key inside a function that a framework may replay. Generating a new key on every retry defeats deduplication. Bind the key to a specific approved operation and retain it for the operation’s lifetime.
Money uses integer micro-USD strings. One dollar is 1000000. The maximum is a ceiling, not a quote or a predicted charge. If pricing is variable, retain the estimate and later settlement separately.
Submit only after the operation’s supplier access and rate are ready. The API contract’s existence is not permission to make an unreviewed paid request.
Handle receipts as state
After invoke, validate and store the receipt identifier and state. A successful HTTP response can contain queued, waiting, or failed work. Check the actual lifecycle before presenting a result.
Use get_invocation with the stored identifier to retrieve existing work. For an asynchronous operation, your application can stop an interactive wait and continue in a background task without starting a replacement purchase.
An unknown state should stop automatic replacement. Retain the original invocation and use the supported reconciliation process. A supplier may have accepted work even when your application did not receive its response.
When the result succeeds, validate it against the domain output contract. A completed extraction that lacks the required table is a task-quality failure even if the supplier call succeeded. Preserve both facts rather than overwriting the execution record.
The failure recovery guide gives a fuller state classification for application code.
Keep errors actionable
Use the typed HTTP error to distinguish transport rejection from a valid invocation receipt. For example, input validation requires correcting the request, while forbidden access requires configuration or administrator action.
Do not parse human-readable error text to decide whether a purchase is safe to repeat. Use status, structured error information, and the existing task record. Preserve sanitized details for debugging while excluding credentials.
Set your own waiting and retry policy at the workflow boundary. An HTTP timeout is not supplier cancellation. A known pre-dispatch rejection and an uncertain post-dispatch result should never share an unconditional “retry with new ID” handler.
Keep optional steps independent. A brief can be delivered while narration remains pending. A failed image should not force repeated research. Persist completed domain outputs so resumption begins at the right step.
Verify the adapter at the right level
First review request shapes against the current contract. Use local response fixtures to verify parsing, state handling, and error classification. Inject or wrap fetch in your project if that makes controlled verification simpler.
Then exercise discovery and inspection against an authorized configured environment. These establish access and catalog behavior. They do not prove paid supplier execution or settlement.
Finally, when supplier accounts and pricing are ready, authorize one bounded live operation and verify the result and receipt. Record the environment, exact operation, account mode, inputs, and observed outcome. Include unsuccessful attempts in the record.
No paid supplier calls were performed for this article. The code is based on the implemented REST contract. Framework-specific integrations can reuse this adapter: continue with Vercel AI SDK or LangGraph for the runtime boundary.





