Docs Packages
@procedures/peer
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 thehttpTransportof@mark1russell7/service/http. - Zero Configuration: Auto-register all procedures from the global registry
Architecture#
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:#fff4e1Component Hierarchy#
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:#50e3c2Installation#
npm install @procedures/peer
Or with pnpm:
pnpm add @procedures/peer
Dependencies#
This package depends on:
@procedures/client- Core client/procedure systemzod- Schema validationzod-to-json-schema- JSON schema generation@mark1russell7/service- The runner: the contracts of the parts, andhttpTransportof./http@mark1russell7/files- The containment check of the paths ofstaticFace()
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.partsare the transports: the procedure server, the stop parts of each face, and anhttpTransportfor each listener.host.dependencieshas one dependency handle for each storage.host.controllershas one route pattern for each face. - The faces.
httpandwsare the faces of this package (httpFace(),wsFace()).mcptakesmcpFace()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). AClienton the transport sends its calls to the host from the same process, through the request tracking of the service. Each call hasLOCAL_CREDENTIALS, and the drain aborts its signal. The cold mode ofmarkuses 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 mountshost.handlerandhost.upgradeon its own listener.- A face sets the stage at which its mount stops with the property
untilof its handler, as aRequestHandlerof the service does (CLI-74). The default isstop 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.
- A face sets the stage at which its mount stops with the property
- 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.requiresnames the dependencies of the service that each call needs. While a check of one of them fails readiness, the service refuses each call withUNAVAILABLE(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 flagretryabletells 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
collectionsgives the storages. The host servescollections.<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.*. Anexcludehides one of them, for examplecollections.notes.clear. The optionexposeof the host wins over the rule of the policy, for the server and for each face. - Always on.
host.health,host.info,host.metricsandevents.subscribestay on, whatever the expose rule says. The host pins them withregisterProcedures(procedures, { alwaysOn: true }). The topic rule is the expose rule ofevents.subscribe. - No
/healthroute. The probes come from the runner (probeHandlerorprobeServer). A client checks a lockfile withhost.infoand 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 isprobeHandler()of@mark1russell7/service/http, and it mounts before the faces.GET /_probes/startup,/_probes/readinessand/_probes/livenessanswer 200, or 503 withRetry-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.healthgives 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 withRetry-After. A face untilclose transportskeeps the listener open in the same way, for example the MCP face (CLI-74). probes: { prefix }changes the prefix.probes: falseturns the probes off, for example when the process has a probe server on a port of its own (probeServer(), or the optionprobesofrunProcedureHost()).host.info.probes()gives the base URL of the probes on each listener. Withoutlisten, the app mountsprobeHandler()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(CapabilityRequestor a list of them): a narrower capability for each call of the face, asmcpFace({ 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 aProcedure-Narrowingheader of the page cannot make the face wider. The nested calls of a call get the narrowed capability. Thusclient.chainand a program ofprocedure.definecannot 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, ashostPolicy({ expose }). The server meets it with the expose rule of the host, for the call and for each nested call. A call outside it getsNOT_FOUND, and a nested call of a data-driven procedure outside it getsNOT_EXPOSED. The rule applies to each procedure, also tohost.health,host.info,host.metricsandevents.subscribe.- A face without these options serves the same calls as before. The option objects of
faces.httpandfaces.wstake 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
GETandHEADrequest under itsbasePath(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.envor.gitof a root stay hidden. Only.well-knownis 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 acceptstext/htmlgets thefallbackfile (defaultindex.html). Another request, for example a probe, gets 404. Withfallback: 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_HEADERShasContent-Security-Policy: frame-ancestors 'self'andX-Frame-Options: SAMEORIGIN. - A header of
headersreplaces the default header of the same name, in any case. A policy of your own replaces the default policy, so put aframe-ancestorsrule in it. - Each response also has
X-Content-Type-Options: nosniff. A file has anETag, and the same tag inIf-None-Matchgets 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 IDtransports: TransportConfig[]- Transports to enableautoRegister?: 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 stagesgetEndpoints(): PeerEndpoint[]- Get active endpointsgetServer(): ProcedureServer- Get underlying procedure servergetHost(): ProcedureHost- The procedures host: its parts, its faces and its infoconnections(): string[]andclientFor(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 URLtransport?: TransportType- Transport type (auto-detected from URL)timeout?: number- Connection timeout in mslocalPeerId?: string- Local peer ID to identify ourselves
Returns: Connection object with:
id: string- Connection IDremote: PeerConnection- Remote peer infoclient: Client- Client for calling remote proceduresdisconnect(): 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
Related Packages#
@procedures/client- Core client/procedure system@procedures/bundle-dev- Development bundle including server procedures@procedures/git- Git procedure implementations@procedures/fs- Filesystem procedure implementations