Protocols and Fetch handlers
Integrate non-page endpoints with the same runtime.
Protocol gateway#
api.protocols() registers JSON-RPC, MCP tools/resources, Connect and tRPC handlers and publishes SSE events. Gateway routes include /rpc, /mcp, /events and /trpc/<name>. MCP implements a JSON transport subset, not every MCP transport.
Gateway authorization#
Protocol endpoints are local-only by default. Requests carrying proxy forwarding headers are rejected unless protocols.authorize explicitly authorizes them. Set authentication, trusted proxy rules and allowedOrigins for real deployments.
Fetch integration#
registerFetchRoutes and createFetchRoute adapt standard Fetch handlers. The adapter preserves statuses, safe end-to-end headers and streaming cancellation; it does not add authorization.
import { registerFetchRoutes } from "zeruxjs/fetch-route";
export default (api) => registerFetchRoutes(api, [{
pattern: "/ping",
handler: () => Response.json({ ok: true })
}]);Configure first, register explicitly#
Protocol options configure origins, request bounds and authorization. The application still registers the methods/tools/resources it intends to expose. A name or schema is not an authorization boundary, and a tool call generated by a model is untrusted input.
import type { ZeruxPluginApi } from 'zeruxjs';
export default function register(api: ZeruxPluginApi): void {
const protocols = api.protocols();
const removeHealth = protocols.rpc('health', () => ({ ok: true }));
// Preserve the disposer in the actual owning lifecycle when registrations can be removed.
}The gateway is obtained lazily and can be disabled by protocols.enabled false. Set a real request authorization callback before external exposure; origin restrictions and loopback defaults are not a user session policy. The callback request type is the gateway's Node request contract, not automatically a Fetch Request.
Types, errors and verification#
Use the public ZeruxProtocols type and registered handler signatures. Validate schema-bound arguments before filesystem, database or network effects and return bounded public errors. Do not forward arbitrary tool arguments into shell commands or a database executor.
Test actual transport framing, wrong methods, denied origins, missing identity, oversized bodies and cancellation. Handler unit calls do not exercise the gateway boundary. Close the owning gateway and unregister dynamic resources during teardown; a static Pages export cannot host this server gateway.
One protocol owner#
MCP is part of zhost, imported through zhost/protocols (also re-exported by the root). The separate @zeruxjs/mcp package is removed; there is no automatic package discovery or replacement package to install. See MCP migration for public imports and teardown.