Remote Procedure Call (RPC) allows participants to invoke predefined methods on other participants. This is useful for agent-to-client communication.
Registering a method
Use room.localParticipant.registerRpcMethod(methodName, handler) to define a method that this participant can handle. The handler receives RpcInvocationData (containing callerIdentity and payload) and a responseTimeout indicating how long you have to respond.
Performing a request
Use room.localParticipant.performRpc({ destinationIdentity, method, payload }) to call a method on a specific participant. You can pass a responseTimeout to control how long the caller waits.
Error Handling
- If you throw an
RpcError with a message in your handler, the caller receives that exact message. - Other errors are caught and returned to the caller as error code
1500 ("Application Error").
// Registering an RPC method
room.localParticipant?.registerRpcMethod(
'greet',
async (data: RpcInvocationData) => {
console.log(`Received greeting from ${data.callerIdentity}: ${data.payload}`);
return `Hello, ${data.callerIdentity}!`;
},
);
// Performing an RPC request
try {
const response = await room.localParticipant!.performRpc({
destinationIdentity: 'recipient-identity',
method: 'greet',
payload: 'Hello from RPC!',
});
console.log('RPC response:', response);
} catch (error) {
console.error('RPC call failed:', error);
}