Docs Client library

Server API

packages/client/docs/SERVER.md on GitHub

The Universal Server provides protocol-agnostic RPC handling with middleware support.

Quick Start#

import { Server } from "@procedures/client";
import { HttpServerTransport, WebSocketServerTransport } from "@procedures/client/node";

// Create server with multiple transports
const server = new Server({
  transports: [
    new HttpServerTransport({ port: 3000 }),
    new WebSocketServerTransport({ port: 3001 }),
  ],
  onError: (error, request) => console.error("Error:", error),
  onRequest: (request) => console.log("Request:", request.method),
});

// Register handlers
server.register(
  { service: "users", operation: "get" },
  async (request) => ({
    id: request.id,
    status: { type: "success", code: 200 },
    payload: { id: request.payload.id, name: "John Doe" },
    metadata: {},
  })
);

// Start server
await server.start();

Server Class#

Constructor#

const server = new Server({
  transports: [transport1, transport2],  // optional, can add later
  onError: (error, request) => { ... },  // global error handler
  onRequest: (request) => { ... },       // request logger
  onResponse: (response) => { ... },     // response logger
  errors: { expose: "coded" },           // the error policy (CLI-80), "all" by default
});

Methods#

register(matcher, handler)#

Register a handler for a method.

// Exact match
server.register(
  { service: "users", operation: "get" },
  async (request) => ({ ... })
);

// With version
server.register(
  { service: "users", operation: "get", version: "v2" },
  async (request) => ({ ... })
);

// Pattern match (regex)
server.register(
  { service: "users", operation: /.*/ },  // All operations for users service
  async (request) => ({ ... })
);

// Catch-all
server.register(
  { service: /.*/, operation: /.*/ },
  async (request) => ({ ... })
);

use(middleware)#

Add middleware to the server.

server.use(loggingMiddleware);
server.use(authMiddleware);
server.use(validationMiddleware);

Middleware executes in registration order.

addTransport(transport)#

Add a transport after construction.

server.addTransport(new HttpServerTransport({ port: 3000 }));

start(): Promise<void>#

Start all transports and begin listening.

await server.start();
console.log("Server listening");

stop(): Promise<void>#

Gracefully shut down all transports.

await server.stop();
console.log("Server stopped");

handle(request): Promise<response>#

Process a request (called internally by transports).

const response = await server.handle<RequestPayload, ResponsePayload>(request);

Request/Response Types#

ServerRequest#

interface ServerRequest<TPayload = unknown> {
  id: string;                    // Correlation ID
  method: Method;                // { service, operation, version? }
  payload: TPayload;             // Request body
  metadata: Metadata;            // Headers, auth, tracing, etc.
}

ServerResponse#

interface ServerResponse<TPayload = unknown> {
  id: string;                    // Correlation ID (matches request)
  status: Status;                // Success or error status
  payload?: TPayload;            // Response body (optional for errors)
  metadata: Metadata;            // Response headers
}

Status#

type Status =
  | { type: "success"; code: number }
  | { type: "error"; code: string; message: string; retryable: boolean };

Handler Function#

Handlers receive a request and return a response:

type ServerHandler<TReq = unknown, TRes = unknown> = (
  request: ServerRequest<TReq>
) => Promise<ServerResponse<TRes>>;

// Example
const getUserHandler: ServerHandler<{ id: string }, User> = async (request) => {
  const user = await db.users.findById(request.payload.id);

  if (!user) {
    return {
      id: request.id,
      status: { type: "error", code: "NOT_FOUND", message: "User not found", retryable: false },
      metadata: {},
    };
  }

  return {
    id: request.id,
    status: { type: "success", code: 200 },
    payload: user,
    metadata: {},
  };
};

Server Middleware#

Server middleware wraps handler execution:

type ServerMiddleware = (
  next: ServerRunner
) => ServerRunner;

type ServerRunner<TReq = unknown, TRes = unknown> = (
  context: ServerContext<TReq>
) => Promise<ServerResponse<TRes>>;

interface ServerContext<TReq = unknown> {
  request: ServerRequest<TReq>;
  state: Record<string, unknown>;  // Middleware state
}

Example Middleware#

// Logging middleware
const loggingMiddleware: ServerMiddleware = (next) => async (context) => {
  const start = Date.now();
  console.log("Request:", context.request.method);

  const response = await next(context);

  console.log(`Response: ${response.status.type} in ${Date.now() - start}ms`);
  return response;
};

// Auth middleware. The token comes from the credentials of the request: a network face keeps the
// metadata key `auth` out of the metadata (roadmap R18)
const authMiddleware: ServerMiddleware = (next) => async (context) => {
  const token = context.request.credentials?.bearer;

  if (!token) {
    return {
      id: context.request.id,
      status: { type: "error", code: "UNAUTHORIZED", message: "Missing token", retryable: false },
      metadata: {},
    };
  }

  // Verify token and add user to state
  const user = await verifyToken(token);
  context.state.user = user;

  return next(context);
};

// Usage
server.use(loggingMiddleware);
server.use(authMiddleware);

Error Handling#

Built-in Errors#

import { HandlerNotFoundError, ServerError } from "client/server";

// Handler not found (returns 404)
throw new HandlerNotFoundError({ service: "users", operation: "unknown" });

// Custom server error
throw new ServerError("VALIDATION_ERROR", "Invalid input", false);

Error Responses#

Errors are automatically converted to responses:

Error TypeCodeRetryable
HandlerNotFoundError404false
ServerErrorcustomcustom
Other errors500false

The error policy#

The option errors tells what an error tells the caller (roadmap CLI-80). handle() applies it, so each face sends the same error.

  • expose: "all" is the default. Each error goes to the caller with its code and its message.
  • expose: "coded" sends an error with a known code (isKnownErrorCode) as it is. Each other error goes to the caller as INTERNAL_ERROR with the message internal error and its real retryable flag. onError gets the real error one time.
  • codes adds the codes of the application that go out as they are under "coded".
  • The server applies map(error, { path, transport }) first. Its result goes to the caller as it is, with its wait.
  • The last-resort catch of each face applies the same policy, for example when handle() throws.
const server = new ProcedureServer({
  errors: {
    expose: "coded",
    // A ServerError with the code QUOTA_EXCEEDED goes to the caller as it is
    codes: ["QUOTA_EXCEEDED"],
    map: (error) => (isPoolExhausted(error) ? Object.assign(new ServerError("Try again soon", "TOO_MANY_REQUESTS", true), { retryAfterMs: 1000 }) : undefined),
  },
});

Refer to the error policy of a server.


Server Transports#

The server uses transports to listen for requests:

HttpServerTransport#

import { HttpServerTransport } from "@procedures/client/node";

const transport = new HttpServerTransport({
  port: 3000,
  host: "0.0.0.0",
  // Express app or custom HTTP server
});

server.addTransport(transport);

WebSocketServerTransport#

import { WebSocketServerTransport } from "@procedures/client/node";

const transport = new WebSocketServerTransport({
  port: 3001,
  // Auth handler for connections
  onAuth: async (token) => verifyToken(token),
});

server.addTransport(transport);

The handlers of @procedures/client/node#

An application with its own node:http server mounts the procedures with two functions. They make no server and do not listen.

import { procedureHandler, upgradeHandler } from "@procedures/client/node";

const procedures = procedureHandler(server, { basePath: "/api/proc" });
const sockets = upgradeHandler(server, { path: "/ws" });
http.on("request", (req, res) => procedures(req, res) || appRoutes(req, res));
http.on("upgrade", (req, socket, head) => sockets(req, socket, head) || socket.destroy());

Each handler gives false for a request of another path, and does not touch it.

The request hook#

The option principalOf of ProcedureServer (and of hostPolicy) reads the credentials of each network request. The credentials have the bearer token, the cookies, each header and the query.

const server = new ProcedureServer({
  principalOf: async ({ cookies = {} }) => {
    const user = await sessions.userOf(cookies["session"]);
    return user ? { principal: { id: `user:${user.id}`, via: "session" } } : {};
  },
});
  • The hook gives a bearer token for the token check, a principal, and a narrowing of the capability.
  • The procedure reads the principal as ctx.principal. The nested calls get the same principal.
  • Undefined, or an error, refuses the request with UNAUTHORIZED.

Local requests#

Each face sets the credentials of its requests, or the local marker LOCAL_CREDENTIALS (CLI-1). The token and the request hook do not apply to a local request.

  • The local faces are MCP over stdio, an SDK transport of McpServerTransport and PortTransport.
  • A network face never sets the marker. The key of the marker is a symbol, so a request from the network cannot carry it.
  • A server with a token or a request hook refuses a request without credentials with UNAUTHORIZED. The hook does not operate for it. A direct handle() of the application gives credentials: LOCAL_CREDENTIALS.

Cookies and CSRF#

A browser sends the cookies of a server by itself, also for a request that a page of another site starts. Thus a server that reads cookies trusts a request only from a named origin.

  • With principalOf, the server reads the cookies of each request. A face then accepts a browser request only from its own origin or from a named origin.
  • A request with a Cookie header gets the same check on procedureHandler and upgradeHandler. "*" does not permit another origin for it. A list or a function of origins does.
  • principalOf with the origin "*" and no named allowedOrigins is refused at construction. The error names the fix.
  • A request without an Origin header and without Sec-Fetch-Site comes from a program, not from a page. It passes.
  • HttpServerTransport and WebSocketServerTransport keep their former checks for a server that reads no cookies. With authenticate, a request with a cookie needs a named origin. The server option ambientCredentials: false turns this off for an authenticate function that reads only the bearer token.
  • Give a session cookie SameSite=Lax or SameSite=Strict, and HttpOnly. A cookie with SameSite=None goes with each request of another site, so only the origin check stops such a request.

Complete Example#

import { Server } from "@procedures/client";
import { HttpServerTransport } from "@procedures/client/node";

// Create server
const server = new Server({
  onError: (error, request) => {
    console.error(`Error handling ${request.method.service}.${request.method.operation}:`, error);
  },
});

// Add transport
server.addTransport(new HttpServerTransport({ port: 3000 }));

// Logging middleware
server.use((next) => async (context) => {
  const start = Date.now();
  const response = await next(context);
  console.log(`${context.request.method.service}.${context.request.method.operation}: ${Date.now() - start}ms`);
  return response;
});

// Register handlers
server.register({ service: "users", operation: "get" }, async (req) => ({
  id: req.id,
  status: { type: "success", code: 200 },
  payload: await db.users.findById(req.payload.id),
  metadata: {},
}));

server.register({ service: "users", operation: "create" }, async (req) => ({
  id: req.id,
  status: { type: "success", code: 201 },
  payload: await db.users.create(req.payload),
  metadata: {},
}));

server.register({ service: "users", operation: "list" }, async (req) => ({
  id: req.id,
  status: { type: "success", code: 200 },
  payload: await db.users.findAll(req.metadata.pagination),
  metadata: { pagination: { page: 1, total: 100 } },
}));

// Start
await server.start();
console.log("Server listening on port 3000");

// Graceful shutdown
process.on("SIGTERM", async () => {
  await server.stop();
  process.exit(0);
});