HTTP and streaming SDK
The HTTP broker performs approved requests for your extension. Supply a typed request through generated WIT imports; Glixo checks the installed manifest, current connection grants, credential slot and limits before contacting the endpoint. The SDK never supplies an ambient fetch, socket or HttpClient transport.
Connect the generated imports
For TypeScript, adapt the imported WIT result behavior to Broker:
import { httpStart, httpStatus, httpResponseHeaders, httpRead,
httpCancel, httpDrop } from 'glixo:http/broker@3.0.0';
import { captureWitResult } from '@glixo/extension-sdk/wit';
import type { Broker } from '@glixo/extension-sdk/http';
export const broker: Broker = {
httpStart: request => captureWitResult(() => httpStart({
...request, headers: [...request.headers],
})),
httpStatus: handle => captureWitResult(() => httpStatus(handle)),
httpResponseHeaders: handle => captureWitResult(() => httpResponseHeaders(handle)),
httpRead: (handle, maxBytes) => captureWitResult(() => httpRead(handle, maxBytes)),
httpCancel, httpDrop,
};
Keep this in a component entry point built with the HTTP broker import. The public Ollama adapter demonstrates the same mapping. C# uses IBroker, Go uses httpbroker.Broker, and Rust uses http::Broker; their language guides describe result and EOF differences.
The SDK treats headers as readonly; the generated WIT request expects an array. The adapter copies the array before calling the import. Generate types from your actual WIT world when typechecking adapters so shape mismatches are caught before componentization.
Request fields
Field in TypeScript BrokerRequest |
Meaning |
|---|---|
url, method, headers |
Required request data. Host validates the exact target, method and headers. |
body |
Optional bytes, usually new TextEncoder().encode(JSON.stringify(value)). |
contentType |
Optional body media type, such as application/json. |
timeoutMs |
Requested timeout; host limits still apply. |
maxResponseBytes |
Maximum response size for this operation, bounded by host policy. |
acceptedStatusMin, acceptedStatusMax |
Inclusive accepted HTTP status range. |
endpointHandle |
Opaque authority for a host-approved endpoint in this invocation. |
secretHandle |
Slot name, such as oauth; not a password, token value or opaque lease ID. |
authHeader, authScheme |
Where the host attaches approved credentials, e.g. Authorization and Bearer. |
See HTTP request WIT and TypeScript types. C# uses PascalCase fields, Rust snake_case, and Go the field names in its Request struct. Bindings adapt these to WIT fields.
For a local Ollama account, select the endpoint named ollama from context.endpoints and use its baseUrl and handle. Append only the allowed path such as /api/chat. The manifest declares the named endpoint, methods and paths; the user approves the actual account connection. A raw URL alone cannot authorize local-network access. Read the complete Ollama manifest.
For Mail Watch, the credential slot is oauth. It checks that the invocation has that resource, then requests with secretHandle: 'oauth', authHeader: 'Authorization' and authScheme: 'Bearer'. The host attaches credentials. See Mail Watch's complete request and permissions and handler. Never copy resourceHandles.oauth into the HTTP slot-name field or put the token in headers yourself.
Response lifecycle
| WIT function | Behavior |
|---|---|
http-start(request) |
Opens a checked request and returns an invocation-local integer response handle. |
http-status(handle) |
Returns the upstream status after response headers arrive. |
http-response-headers(handle) |
Returns safe metadata headers; credential-bearing headers are filtered by the host. |
http-read(handle,max-bytes) |
Returns bytes up to the limit, or the WIT none value at EOF. Empty bytes are an empty chunk. |
http-cancel(handle) |
Stops upstream work and makes the handle unreadable. |
http-drop(handle) |
Releases completed, failed or abandoned response state. |
Source: broker WIT. Always drop a successfully opened response, including on parse failures. Cancel early when the consumer stops. Do not persist response handles or share them across invocations. Set byte, page and line limits so your handler cannot buffer unbounded upstream data.
Read NDJSON
NDJSON contains one JSON value per line. NdjsonStream supports lines split across broker reads, multiple lines in one read, CRLF, and a final line without a newline. It removes the line terminator but does not parse JSON. TypeScript defaults to 16 KiB reads and a 1 MiB line limit; an oversized line throws ndjson_line_too_large.
This reusable function accepts your imported broker and a checked request:
import { NdjsonStream, type Broker, type BrokerRequest }
from '@glixo/extension-sdk/http';
export function readRecords(broker: Broker, request: BrokerRequest): unknown[] {
const stream = new NdjsonStream(broker, request, 64 * 1024);
const records: unknown[] = [];
const decoder = new TextDecoder('utf-8', {fatal: true});
try {
const status = stream.status();
if (status < 200 || status > 299) throw new Error('upstream_status_invalid');
for (;;) {
const line = stream.nextLine();
if (line === undefined) break;
if (line.length === 0) continue;
if (records.length >= 100) throw new Error('record_limit_exceeded');
records.push(JSON.parse(decoder.decode(line)));
}
return records;
} catch (error) {
stream.cancel();
throw error;
} finally {
stream.close();
}
}
Use a small maxResponseBytes and timeout in the request too. This sample collects at most 100 records for a bounded operation. A model provider instead emits one event at a time from its stream table, as described in the provider SDK. An NDJSON reader does not parse Server-Sent Events; protocols like MCP need their own framing and safe response headers. See Issue Lookup's MCP implementation.
Methods and cleanup across languages
| Language | Open/read | Completion and cleanup |
|---|---|---|
| TypeScript | new NdjsonStream(broker,request,maxLineBytes); nextLine(): Uint8Array | undefined |
close() drops once; cancel() cancels and closes |
| C# | new NdjsonStream(broker,request,maxLineBytes); ReadLine(): byte[]? |
using / Dispose(); Cancel() |
| Go | httpbroker.Open(broker,request,maxLineBytes); NextLine() ([]byte,error) |
io.EOF is clean completion; defer stream.Close(); Cancel() |
| Rust | NdjsonStream::open(broker,request,max_line_bytes); next_line() |
Ok(None) is EOF; Drop releases; close() / cancel() |
The TypeScript and C# constructors, and Rust open, clamp a nonpositive line limit to at least one byte. Go chooses its default for a nonpositive limit. Pass an explicit positive limit. The helper controls buffering; host permissions and total response limits remain separate.
Errors and verification
Host denial is an error result, not an empty body. Expected HTTP and parse failures should become bounded contribution/provider error codes. Avoid blindly retrying mutating requests; verify idempotency and checkpoint behavior in your protocol. Don't return full upstream errors if they may contain credentials or personal data.
Test split UTF-8 bytes, CRLF, final lines, empty chunks, oversize lines, invalid JSON, denied starts and cancellation. Verify both cancel and drop counts. Then test the actual approved account and endpoint through Glixo, including permission removal. See installed-app checks.