Packages
Typed RPC
Schema-backed procedures and inferred clients over the existing P2P connection.
Content reviewed 16 October 2026
Experimental alpha API
The /rpc entry and /service helpers are available in published 0.6.0-alpha.2. Existing plain packs, peer.call, peer.stream and peer.api remain available. No tRPC or validator package is required.
Define a capability once and share its runtime contract with clients. Query and mutation methods return ordinary promises; stream methods return async iterables. TypeScript infers inputs and results while runtime schemas check peer data.
When to use RPC
Use RPC when a peer owns data or a service and should return a specific result: a receipt, a note or incremental output. Unlike replication, a call does not give the caller a local copy of the whole dataset. Both peers must be reachable for a fresh call.
Your first peer call
Use Node 22.17+ and npm. This quick start uses serve/connect from published 0.6.0-alpha.2. The /service entry handles identity, discovery, encryption and pairing; /rpc defines the shared contract. Your app supplies a service, a storage directory and an invitation.
mkdir rpc-demo
cd rpc-demo
npm init -y
npm install @unstoppable-stack/p2p@0.6.0-alpha.31. Define what the app can do
Save notes.mjs. A capability is a named set of methods. This shared file contains a single query and its contract; it does not start networking when imported.
import { defineCapability, procedure } from '@unstoppable-stack/p2p/rpc'
export const notes = defineCapability({
name: 'notes',
version: 1,
methods: {
get: procedure.query(() => ({ text: 'Hello RPC' }))
}
})
2. Offer the service
Save host.mjs. serve() starts the service and owns its node. invite(['get']) creates a code that permits only that method, usable once and valid for 15 minutes by default. Share it only with the intended peer.
import { serve } from '@unstoppable-stack/p2p/service'
import { notes } from './notes.mjs'
const service = await serve({ storage: './host-data', capability: notes })
try {
console.log(await service.invite(['get']))
} catch (error) {
await service.close()
throw error
}
process.once('SIGINT', () => service.close())
process.once('SIGTERM', () => service.close())
3. Connect and call
Save client.mjs. connect() handles pairing and contract binding. Calls look like ordinary async functions. close() releases the connection and its node; the identity remains on disk.
import { connect } from '@unstoppable-stack/p2p/service'
import { notes } from './notes.mjs'
const connection = await connect({
storage: './client-data',
invite: process.argv[2],
contract: notes.contract
})
try {
console.log((await connection.api.get()).text)
} finally {
await connection.close()
}
Run it
node host.mjs
# In a second terminal, in the same directory:
node client.mjs "PASTE_INVITATION_HERE"Keep the host running and copy its printed code into the client command. These programs use normal public peer discovery, so both need network access; no server account or DHT setup is required. Stop the host with Ctrl+C. Run it again to issue a fresh invitation, or reconnect with the saved host public key as described below.
Expected result
Hello RPCThe host returns a fixed note to make the first call easy to understand. Replace its handler with your app's local data lookup. Session integration tests cover real calls over an isolated local DHT; that evidence does not establish public-network reachability on every network.
Session API
serve({ storage, capability }): start one typed service.service.invite(['method'])returns a scoped code;service.close()shuts down its node.connect({ storage, invite, contract, timeout, signal }): pair and return connection.api. Setup defaults to a 20-second peer lookup timeout. Each method also accepts its own timeout and signal.- For later sessions, persist connection.peer.publicKey and use
connect({ storage, publicKey, contract })with the same client storage. Existing grants still constrain access. - Failed setup closes the node automatically. Call
close()in your application's shutdown path after successful setup. Closing is safe to repeat. - service.node and connection.node expose advanced administration and events. nodeOptions accepts existing transport/profile/limit options; normal apps need none of them. For multiple hosted capabilities or bidirectional services, use
createNodedirectly.
Define and share the contract
Define a capability with a name, version and procedures. A query reads one result; a mutation changes state and returns one result; a stream yields multiple results. Builder calls are immutable. notes.contract contains method descriptions and validators without the handlers. Export that contract from a pure application module so clients do not import server storage.
- Use
procedure.input(schema).output(schema).query(handler),.mutation(handler)or.stream(handler). Validators can be parser functions,parse()objects or Standard Schema implementations. - Input transformations run once on the host. Output schemas must be idempotent JSON wire validators; stripped fields are removed before transmission and clients validate received output again.
- Return JSON values: dates, maps, undefined, cycles and nonfinite numbers are rejected. Use null for an action with no result data.
- Binding checks service version, method presence and kind. Partial grants are valid; ungranted calls still fail with NOT_GRANTED. Type inference does not authorize a peer.
- Calls accept
signaland timeout. Cancellation is cooperative; no mutation or stream is replayed automatically after reconnect. Obtain the replacement peer and bind a fresh client.
Keep contracts and validators in a shared application module. Bind the P2P client in the worker and expose app-owned IPC to the renderer; validator functions cannot be sent as JSON. Streams retain finite request and output budgets and do not implement durable subscriptions.
Validate input and output
Input schemas run on the host. Output schemas validate the host result before sending it and validate the wire value again on the client. Stripped fields never leave the host. Output validators must preserve their own JSON shape: normalization is fine, but incrementing a number on each validation is not. Keep validators pure.
Use parser functions, objects with parse(value), or Standard Schema validators. Standard Schema preserves different pre-transform input and handler types; simple parser functions use their returned type for the caller. Outputs must be JSON-compatible; return null for a successful action with no data.
Permissions and versioning
Binding checks the advertised capability version, method names and method kinds. A matching contract does not grant access: if the invitation grants get but not list, the list call fails with NOT_GRANTED. Change the capability version when changing its contract; schema negotiation is not automatic.
Deadlines and cancellation
Calls and streams accept signal and timeout. The caller's default total deadline is 30 seconds; timeout: 0 disables only that caller deadline, not host limits. Break stream iteration to cancel production, or abort its signal while waiting for an item. Handlers must observe the signal and release resources in finally.
Sessions do not reconnect automatically. Close a disconnected session and call connect again with the saved public key and same storage, or bind a fresh client when using createNode directly. The runtime does not replay operations. A disconnect after a mutation can leave its outcome unknown, so use application idempotency keys before retrying changes. These bounded streams are not durable event subscriptions.
Troubleshooting
- Package subpath
/rpcis not exported: upgrade to @unstoppable-stack/p2p@0.6.0-alpha.3. NOT_GRANTED: inspect the invitation or peer grants; changing a TypeScript type will not authorize the method.INVALID_INPUTor INVALID_OUTPUT: check your validator and JSON wire shape; avoid undefined, BigInt, Dates, Maps, cycles and nonfinite numbers.- INCOMPATIBLE_CAPABILITY or METHOD_KIND_MISMATCH: share a version-matched contract between peers.
REQUEST_TIMEOUT,CANCELLED, CLOSED orRESOURCE_LIMIT: handle the operation state explicitly and do not replay mutations blindly.- PEER_NOT_FOUND: check that the host is running, the code is current and the network permits peer discovery. Retry explicitly; no mutation is replayed for you.