Docs Packages

@procedures/peer

packages/client-server/README.md on GitHub · Package map · Procedures

Transport-agnostic peer for bidirectional RPC - exposes procedures and generates manifests

Overview#

client-server is a comprehensive server infrastructure package that enables transport-agnostic bidirectional RPC communication. It provides a peer-to-peer architecture where each peer can both expose procedures and call procedures on remote peers. The package supports multiple transport layers (HTTP, WebSocket, local) and includes automatic procedure discovery and manifest generation.

Key Features#

  • Transport-Agnostic: Supports HTTP, WebSocket, and in-process transports
  • Bidirectional RPC: Peers can both expose and call procedures
  • Automatic Discovery: Peers exchange procedure manifests on connection
  • Manifest Generation: Generate TypeScript and JSON manifests from registered procedures
  • Connection Management: Track and manage multiple peer connections
  • One procedures host: createProcedureHost() gives the parts of a service of @mark1russell7/service (CLI-7). It has no framework: the listener is the httpTransport of @mark1russell7/service/http.
  • Zero Configuration: Auto-register all procedures from the global registry

Architecture#

Diagram source (Mermaid). GitHub draws it on the page of the file.
graph TB
    subgraph "Peer A"
        PA[Peer Instance]
        PS[Procedure Server]
        REG[Procedure Registry]
        HT[HTTP Transport]
        WT[WebSocket Transport]

        PA --> PS
        PS --> REG
        PS --> HT
        PS --> WT
    end

    subgraph "Peer B"
        PB[Peer Instance]
        CL[Client]
        CT[Client Transport]
        DISC[Discovery]

        PB --> CL
        CL --> CT
        CL --> DISC
    end

    HT -.HTTP.-> CT
    WT -.WebSocket.-> CT
    DISC -.Discovery Protocol.-> PS

    style PA fill:#e1f5ff
    style PB fill:#ffe1f5
    style DISC fill:#fff4e1

Component Hierarchy#

Diagram source (Mermaid). GitHub draws it on the page of the file.
graph TD
    SERVER[client-server] --> PEER[Peer]
    SERVER --> CONN[Connection Manager]
    SERVER --> DISC[Discovery System]
    SERVER --> MAN[Manifest Generator]

    PEER --> PSERV[Procedure Server]
    PEER --> TRANS[Transports]

    TRANS --> HTTP[HTTP Transport]
    TRANS --> WS[WebSocket Transport]
    TRANS --> LOCAL[Local Transport]

    CONN --> CLIENT[Client]
    CONN --> CTRANS[Client Transports]

    DISC --> ANNOUNCE[Announce Procedure]
    DISC --> WATCH[Procedure Watcher]

    MAN --> TS[TypeScript Generator]
    MAN --> JSON[JSON Generator]

    style SERVER fill:#4a90e2
    style PEER fill:#7ed321
    style CONN fill:#f5a623
    style DISC fill:#bd10e0
    style MAN fill:#50e3c2

Installation#

npm install @procedures/peer

Or with pnpm:

pnpm add @procedures/peer

Dependencies#

This package depends on:

  • @procedures/client - Core client/procedure system
  • zod - Schema validation
  • zod-to-json-schema - JSON schema generation
  • @mark1russell7/service - The runner: the contracts of the parts, and httpTransport of ./http
  • @mark1russell7/files - The containment check of the paths of staticFace()

Usage#

The procedures host#

createProcedureHost() builds one procedures server with its faces, and gives the parts of a service. It starts nothing and installs no signal handler. The service of the process declares the parts, and only the entry of the process starts run() (decision D2).

import { localDev, service } from "@mark1russell7/service";
import { hostPolicy, seconds } from "@procedures/client";
import { mcpFace } from "@procedures/mcp-server";
import { createProcedureHost, LOCAL_LISTENER_KNOBS } from "@procedures/peer";

const host = createProcedureHost({
  registry,
  policy: hostPolicy({ token }),
  faces: { http: true, ws: true, mcp: mcpFace() },
  listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
  collections: { notes: storage },
});
const svc = host
  .declare(service("app").profile(localDev))
  .readiness({ type: "debounce", interval: seconds(5), failAfter: 3, recoverAfter: 1 })
  .liveness({ type: "window", failAfter: seconds(45) })
  .startup(seconds(30));
await svc.run();
  • The parts. host.parts are the transports: the procedure server, the stop parts of each face, and an httpTransport for each listener. host.dependencies has one dependency handle for each storage. host.controllers has one route pattern for each face.
  • The faces. http and ws are the faces of this package (httpFace(), wsFace()). mcp takes mcpFace() of @procedures/mcp-server. A face of another package is a function with the same shape.
  • The local face. localFace() gives a face factory and a transport of @procedures/client (CLI-26). A Client on the transport sends its calls to the host from the same process, through the request tracking of the service. Each call has LOCAL_CREDENTIALS, and the drain aborts its signal. The cold mode of mark uses it.
const local = localFace();
const host = createProcedureHost({ registry, faces: { local: local.face } });
const life = await host.declare(service("tool").profile(ephemeral)).run();
const client = new Client({ transport: local.transport });
  • The listeners. The faces of a listener mount on its mount list, so they share one port. Without listen, the app mounts host.handler and host.upgrade on its own listener.
    • A face sets the stage at which its mount stops with the property until of its handler, as a RequestHandler of the service does (CLI-74). The default is stop intake.
    • The MCP face stays until close transports. Thus the listener stays open through the drain, and a call in progress gets the answer of an elicitation and its cancel.
  • The request tracking. Each call goes through life.request, with the route <face> <procedure>. The function of the pattern gives the idempotency of each call: a repeatable procedure, a keyed call, or a call that runs one time (decision D3).
  • The readiness of the calls. The option controller.requires names the dependencies of the service that each call needs. While a check of one of them fails readiness, the service refuses each call with UNAVAILABLE (CLI-45).
  • The streams. Each call is a stream, and a unary call is a stream of one (decision D4). A stream stays in flight until its end. A cut after the first item ends the stream with an error line. Each cut has the code UNAVAILABLE, and its flag retryable tells if a retry is safe (CLI-48). Before the first item, the HTTP face answers 503 for a retryable cut and 500 for another cut.
  • The collections. The option collections gives the storages. The host serves collections.<name>.* for each one.
  • The expose rule. The rule of the policy applies to each procedure that the host serves, also to the collection procedures (CLI-47). A host with an expose rule must list the collection procedures that it serves, for example collections.notes.*. An exclude hides one of them, for example collections.notes.clear. The option expose of the host wins over the rule of the policy, for the server and for each face.
  • Always on. host.health, host.info, host.metrics and events.subscribe stay on, whatever the expose rule says. The host pins them with registerProcedures(procedures, { alwaysOn: true }). The topic rule is the expose rule of events.subscribe.
  • No /health route. The probes come from the runner (probeHandler or probeServer). A client checks a lockfile with host.info and the token of the lockfile.
  • The probes. Each listener of the host answers the probes of the service under /_probes (CLI-9, decision D5). The handler is probeHandler() of @mark1russell7/service/http, and it mounts before the faces.
    • GET /_probes/startup, /_probes/readiness and /_probes/liveness answer 200, or 503 with Retry-After. /_probes/readiness/<controller> gives the readiness of one controller.
    • The probes answer each caller without the token and the browser checks. They give only the status. Each other path goes to the faces, with the token and the browser checks as before.
    • A listener does not answer the report (/_probes/report), because it names the checks and the dependencies. host.health gives the details with the token.
    • The probes stop when the intake stops. Then the listener closes, as without the probes, and a new connection is refused. probes: { until: "close transports" } keeps the listener open through the drain: the probes answer 503, and each other request gets 503 with Retry-After. A face until close transports keeps the listener open in the same way, for example the MCP face (CLI-74).
    • probes: { prefix } changes the prefix. probes: false turns the probes off, for example when the process has a probe server on a port of its own (probeServer(), or the option probes of runProcedureHost()).
    • host.info.probes() gives the base URL of the probes on each listener. Without listen, the app mounts probeHandler() on its own listener.

A read-only face for a browser#

httpFace() and wsFace() take two optional options for the calls of the face (AG1-B). With them, a host serves a second face pair next to its full faces. The server enforces the rules of each face, so a page cannot go around them.

import { createProcedureHost, httpFace, wsFace, LOCAL_LISTENER_KNOBS } from "@procedures/peer";

const read = {
  narrowing: { effects: { writes: [] } },
  expose: ["programs.list", "programs.get", "procedure.get", "client.trace", "api.*"],
};
const host = createProcedureHost({
  registry,
  faces: {
    http: { basePath: "/rpc" },
    ws: { path: "/rpc/ws" },
    readHttp: httpFace({ basePath: "/rpc/read", ...read }),
    readWs: wsFace({ path: "/rpc/read/ws", ...read }),
  },
  listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
});
// The page opens a second WebSocketTransport to /rpc/read/ws for its read calls
  • narrowing (CapabilityRequest or a list of them): a narrower capability for each call of the face, as mcpFace({ narrowing }) (CLI-43). The face adds it as one more source of the narrowing key (CLI-30). The server applies the meet of all the sources, so a Procedure-Narrowing header of the page cannot make the face wider. The nested calls of a call get the narrowed capability. Thus client.chain and a program of procedure.define cannot write through the face. A narrowing that is not valid stops the host with an error.
  • expose (a list of patterns, a tool surface or a function): the procedures that the callers of the face reach, as hostPolicy({ expose }). The server meets it with the expose rule of the host, for the call and for each nested call. A call outside it gets NOT_FOUND, and a nested call of a data-driven procedure outside it gets NOT_EXPOSED. The rule applies to each procedure, also to host.health, host.info, host.metrics and events.subscribe.
  • A face without these options serves the same calls as before. The option objects of faces.http and faces.ws take them too.

The built files of a page#

staticFace() serves the files of a folder, for example the dist folder of a Vite build. Thus an app with a page needs only the one listener of its host.

import { createProcedureHost, staticFace, LOCAL_LISTENER_KNOBS } from "@procedures/peer";

const host = createProcedureHost({
  registry,
  faces: {
    http: true,
    ws: true,
    page: staticFace({ root: "dist", headers: { "Content-Security-Policy": "default-src 'self'; frame-ancestors 'self'" } }),
  },
  listen: [{ port: 3000, knobs: LOCAL_LISTENER_KNOBS }],
});
  • Put the face last. The first face that takes a request serves it, so the procedure faces keep their paths.
  • The face takes each GET and HEAD request under its basePath (default /). The face adds a / at the start of a base path that has none.
  • Each path stays in root. A path that leaves it, also through a symbolic link, gets 404.
  • A path with a segment that starts with . gets 404, so the .env or .git of a root stay hidden. Only .well-known is served.
  • A missing root gives 404. The next request reads the root again, so the files of a later build are served.
  • A folder gives its index.html. A path with no file and no extension is a route of the page. A request that accepts text/html gets the fallback file (default index.html). Another request, for example a probe, gets 404. With fallback: false, each route gets 404.
  • A route with a dot in its last segment, for example /u/john.doe, has an extension. It gets 404, not the fallback.
  • By default, only a page of the same origin can show the files in a frame: DEFAULT_STATIC_HEADERS has Content-Security-Policy: frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN.
  • A header of headers replaces the default header of the same name, in any case. A policy of your own replaces the default policy, so put a frame-ancestors rule in it.
  • Each response also has X-Content-Type-Options: nosniff. A file has an ETag, and the same tag in If-None-Match gets 304.
  • The request tracking of the host tracks each request, so the drain of a stop waits for it.

Creating a Server Peer#

createPeer() is for a process that has no service of its own: a test, or a host that a procedure starts (server.create). The peer builds a host with createProcedureHost(), declares its parts in a service of its own, and starts run() of @mark1russell7/service on a process port that installs no signal handler and never ends the process. stop() asks that lifecycle for its shutdown. A process that has a service of its own uses createProcedureHost() and host.declare(svc) in place of a peer.

A peer has one token, and it starts one time. The WebSocket face refuses an upgrade that the server does not admit: 401 without the token or for a refusal of the request hook, and 403 for a failed browser check.

import { createPeer } from "@procedures/peer";

// Create a peer with HTTP and WebSocket transports
const peer = await createPeer({
  id: "my-server",
  transports: [
    {
      type: "http",
      port: 3000,
      host: "0.0.0.0",
      basePath: "/api",
      cors: true,
    },
    {
      type: "websocket",
      port: 3001,
      host: "0.0.0.0",
      path: "/ws",
    },
  ],
  autoRegister: true, // Auto-register all procedures from global registry
});

// Start all transports
await peer.start();

// Get active endpoints
console.log(peer.getEndpoints());
// [
//   { type: "http", address: "http://localhost:3000/api" },
//   { type: "websocket", address: "ws://localhost:3001/ws" }
// ]

// Stop the peer
await peer.stop();

Using Server Procedures#

import { Client, LocalTransport, PROCEDURE_REGISTRY } from "@procedures/client";
import "@procedures/peer/register"; // registers its procedures

const client = new Client(new LocalTransport({ registry: PROCEDURE_REGISTRY }));

// Create a server
const result = await client.exec(["server", "create"], {
  transports: [
    { type: "http", port: 3000 },
    { type: "websocket", port: 3001 },
  ],
  autoRegister: true,
});

console.log(result);
// {
//   serverId: "peer-1234567890-abc123",
//   endpoints: [
//     { type: "http", address: "http://localhost:3000/api" },
//     { type: "websocket", address: "ws://localhost:3001/ws" }
//   ],
//   procedureCount: 42
// }

Connecting to Remote Peers#

import { connect } from "@procedures/peer";

// Connect to a remote peer
const connection = await connect({
  address: "http://localhost:3000/api",
  transport: "http", // Auto-detected from URL if omitted
  timeout: seconds(10),
  localPeerId: "my-client",
});

console.log(connection.remote);
// {
//   id: "conn-1234567890-xyz789",
//   remotePeerId: "peer-1234567890-abc123",
//   transport: "http",
//   state: "connected",
//   remoteProcedures: [
//     { path: ["git", "status"], description: "Get git status" },
//     { path: ["git", "add"], description: "Stage files" },
//     // ...
//   ],
//   connectedAt: Date
// }

// Call procedures on the remote peer
const gitStatus = await connection.client.call(["git", "status"], { cwd: "/path" });

// Disconnect
await connection.disconnect();

Procedure Discovery#

The discovery system automatically exchanges procedure manifests when peers connect:

import { discoveryAnnounceProcedure, getProcedureInfos, watchProcedures } from "@procedures/peer";

// Get all registered procedures
const procedures = getProcedureInfos();
console.log(procedures);
// [
//   { path: ["git", "status"], description: "Get git status" },
//   { path: ["git", "add"], description: "Stage files" },
//   // ...
// ]

// Watch for procedure changes
const unwatch = watchProcedures((event, info) => {
  console.log(`Procedure ${event}:`, info.path.join("."));
});

// Stop watching
unwatch();

Manifest Generation#

Generate TypeScript declarations or JSON manifests from registered procedures:

import { generateTypeScript, generateJson, generateJsonString } from "@procedures/peer";

// Generate TypeScript declaration
const tsDeclaration = generateTypeScript({
  namespace: ["git"], // Only include git.* procedures
});

console.log(tsDeclaration);
// export interface Procedures {
//   "git.status": { input: { cwd?: string }, output: { ... } };
//   "git.add": { input: { files: string[], all?: boolean }, output: { ... } };
//   // ...
// }

// Generate JSON manifest
const manifest = generateJson({
  namespace: ["git"],
});

console.log(manifest);
// {
//   procedures: [
//     {
//       path: ["git", "status"],
//       description: "Get git status",
//       inputSchema: { ... },
//       outputSchema: { ... }
//     },
//     // ...
//   ],
//   generatedAt: "2025-01-15T10:30:00.000Z",
//   version: "1.0.0"
// }

// Generate JSON string
const jsonString = generateJsonString({ namespace: ["git"] });

Using with Procedure Calls#

// Connect to remote server
await client.exec(["server", "connect"], {
  address: "http://localhost:3000/api",
  transport: "http",
  timeout: 10000, // the input is data: milliseconds
});

// Disconnect from server
await client.exec(["server", "disconnect"], {
  connectionId: "conn-1234567890-xyz789",
});

// Generate manifest
const manifest = await client.exec(["manifest", "generate"], {
  formats: ["json", "typescript"],
  namespace: ["git"],
  outputDir: "./generated",
});

console.log(manifest);
// {
//   json: { procedures: [...], generatedAt: "...", version: "..." },
//   typescript: "export interface Procedures { ... }",
//   filesWritten: ["./generated/manifest.json", "./generated/manifest.d.ts"]
// }

API Reference#

Peer#

createPeer(options: PeerOptions): Promise<Peer>#

Create a new peer instance.

Options:

  • id: string - Unique peer ID
  • transports: TransportConfig[] - Transports to enable
  • autoRegister?: boolean - Auto-register procedures from registry (default: true)
  • registry?: ProcedureRegistry - Custom procedure registry (default: global)

Returns: Peer instance with methods:

  • start(): Promise<void> - Start the parts of the host. A peer starts one time.
  • stop(options?: { grace }): Promise<void> - Stop the parts in the sequence of the stages
  • getEndpoints(): PeerEndpoint[] - Get active endpoints
  • getServer(): ProcedureServer - Get underlying procedure server
  • getHost(): ProcedureHost - The procedures host: its parts, its faces and its info
  • connections(): string[] and clientFor(id): Client - The WebSocket connections, and a client of one

Transport Configurations#

HTTP Transport#
{
  type: "http",
  port?: number,        // Default: 3000
  host?: string,        // Default: "127.0.0.1"
  basePath?: string,    // Default: "/api"
  cors?: boolean,       // Default: false
  corsOrigins?: string[] // Allowed origins
}
WebSocket Transport#
{
  type: "websocket",
  port?: number,        // Default: 3001
  host?: string,        // Default: "127.0.0.1"
  path?: string         // Default: "/ws"
}
Local Transport#
{
  type: "local"         // In-process communication
}

Connection#

connect(options: ConnectOptions): Promise<Connection>#

Connect to a remote peer.

Options:

  • address: string - Remote server URL
  • transport?: TransportType - Transport type (auto-detected from URL)
  • timeout?: number - Connection timeout in ms
  • localPeerId?: string - Local peer ID to identify ourselves

Returns: Connection object with:

  • id: string - Connection ID
  • remote: PeerConnection - Remote peer info
  • client: Client - Client for calling remote procedures
  • disconnect(): Promise<void> - Disconnect from peer

disconnect(connectionId: string): Promise<boolean>#

Disconnect a connection by ID.

getConnection(connectionId: string): Connection | undefined#

Get connection by ID.

getConnectionIds(): string[]#

Get all active connection IDs.

Discovery#

discoveryAnnounceProcedure#

Internal procedure for procedure discovery. Automatically called when peers connect.

getProcedureInfos(): ProcedureInfo[]#

Get information about all registered procedures.

watchProcedures(callback: (event, info) => void): () => void#

Watch for procedure registration/unregistration events.

Manifest Generation#

generateTypeScript(options?): string#

Generate TypeScript declaration from registered procedures.

Options:

  • namespace?: string[] - Filter procedures by namespace

generateJson(options?): ProcedureManifest#

Generate JSON manifest from registered procedures.

Options:

  • namespace?: string[] - Filter procedures by namespace

Returns:

{
  procedures: ProcedureInfo[],
  generatedAt: string,
  version: string
}

generateJsonString(options?): string#

Generate JSON manifest as string.

Procedures#

server.create#

Create a transport-agnostic peer that exposes procedures.

Input:

{
  transports?: TransportConfig[],  // Default: [{ type: "http", port: 3000 }]
  autoRegister?: boolean           // Default: true
}

Output:

{
  serverId: string,
  endpoints: Array<{ type: TransportType, address: string }>,
  procedureCount: number
}

server.connect#

Connect to a remote server and discover procedures.

Input:

{
  address: string,
  transport?: TransportType,  // Auto-detected from URL
  timeout?: number            // Default: 10000
}

Output:

{
  connectionId: string,
  remotePeerId: string,
  remoteProcedures: ProcedureInfo[]
}

server.disconnect#

Disconnect from a remote server.

Input:

{
  connectionId: string
}

Output:

{
  success: boolean
}

manifest.generate#

Generate procedure manifests in various formats.

Input:

{
  formats?: ("json" | "typescript")[],  // Default: ["json"]
  namespace?: string[],                 // Filter by namespace
  outputDir?: string                    // Write files to directory
}

Output:

{
  json?: {
    procedures: ProcedureInfo[],
    generatedAt: string,
    version: string
  },
  typescript?: string,
  filesWritten?: string[]
}

_discovery.announce#

Internal procedure for exchanging procedure manifests (used by connection system).

Types#

Core Types#

export type TransportType = "http" | "websocket" | "local";

export interface ProcedureInfo {
  path: string[];
  description?: string;
  inputSchema?: Record<string, unknown>;
  outputSchema?: Record<string, unknown>;
}

export interface PeerConnection {
  id: string;
  remotePeerId: string;
  transport: TransportType;
  state: "connecting" | "connected" | "disconnected" | "error";
  remoteProcedures: ProcedureInfo[];
  connectedAt?: Date;
}

Configuration#

Auto-Registration#

By default, peers auto-register all procedures from the global PROCEDURE_REGISTRY. Disable this for manual control:

const peer = await createPeer({
  id: "my-server",
  transports: [{ type: "http" }],
  autoRegister: false,
});

// Manually register procedures
peer.getServer().register(myProcedure);

CORS Configuration#

Configure CORS for HTTP transport:

{
  type: "http",
  cors: true,
  corsOrigins: ["http://localhost:3000", "https://example.com"]
}

Integration with Ecosystem#

With bundle-dev#

The bundle-dev package includes client-server for development workflows:

import "@procedures/bundle-dev/register"; // registers its procedures

// server.* procedures are now available
await client.exec(["server", "create"], { ... });

With client packages#

Combine with other client packages for complete functionality:

// Start a server that exposes git procedures
import "@procedures/git/register"; // registers its procedures
import { createPeer } from "@procedures/peer";

const peer = await createPeer({
  id: "git-server",
  transports: [{ type: "http", port: 3000 }],
  autoRegister: true, // Includes all git.* procedures
});

await peer.start();

Advanced Usage#

Custom Transport Configuration#

import express from "express";
import { createPeer } from "@procedures/peer";

// Use existing Express app
const app = express();

const peer = await createPeer({
  id: "custom-server",
  transports: [
    {
      type: "http",
      port: 4000,
      basePath: "/rpc",
      cors: {
        origin: ["http://localhost:3000"],
        credentials: true,
      },
    },
  ],
});

await peer.start();

Multiple Peers#

Run multiple peers in the same process:

import { createPeer } from "@procedures/peer";

const publicPeer = await createPeer({
  id: "public-api",
  transports: [{ type: "http", port: 3000 }],
});

const privatePeer = await createPeer({
  id: "private-api",
  transports: [{ type: "http", port: 4000 }],
});

await publicPeer.start();
await privatePeer.start();

Procedure Filtering#

Generate manifests for specific namespaces:

import { generateJson } from "@procedures/peer";

// Only git procedures
const gitManifest = generateJson({ namespace: ["git"] });

// Only fs procedures
const fsManifest = generateJson({ namespace: ["fs"] });

Error Handling#

import { connect } from "@procedures/peer";

try {
  const connection = await connect({
    address: "http://localhost:3000/api",
    timeout: seconds(5),
  });

  // Use connection
} catch (error) {
  if (error.code === "ECONNREFUSED") {
    console.error("Server is not running");
  } else if (error.message.includes("timeout")) {
    console.error("Connection timed out");
  } else {
    console.error("Connection failed:", error);
  }
}

Performance Considerations#

  • HTTP Transport: Best for RESTful APIs and simple request/response patterns
  • WebSocket Transport: Best for real-time, bidirectional communication with low latency
  • Local Transport: Best for in-process communication with zero network overhead
  • Auto-Registration: Minimal overhead - procedures are registered once at startup
  • Discovery: Procedures are announced once per connection, then cached

The root of the files#

Under the root of a host (mark --fs-root, procedure-server --fs-root, MCP_FS_ROOT), manifest.generate writes its files only in a folder of the root. A relative outputDir starts at the root. The other procedures of this package reach no file.

License#

MIT

Repository#

https://github.com/mark1russell7/client-server

  • @procedures/client - Core client/procedure system
  • @procedures/bundle-dev - Development bundle including server procedures
  • @procedures/git - Git procedure implementations
  • @procedures/fs - Filesystem procedure implementations