registerGlobalRoutingCallback

View as MarkdownOpen in Claude

Register a custom routing callback on every registered agent at the specified path. When a request arrives at that path on any agent, the callback is invoked to determine whether to redirect the request to a different agent route.

Use this alongside or instead of setupSipRouting() when you need custom routing logic — for example, routing based on request body content, tenant IDs, or feature flags.

The callback is also applied to agents registered after this method is called. The server stores each callback internally so new agents automatically receive it.

Parameters

callbackFn
RoutingCallbackRequired

A function that receives the parsed request body and returns a route string (e.g., "/sales") to redirect the request, or null / undefined to let the current agent handle it. May return a Promise for asynchronous routing decisions. Signature: (body: Record<string, unknown>) => string | null | undefined | Promise<string | null | undefined>.

path
stringRequired

The URL path where the callback is triggered (e.g., "/route"). Leading slashes are added and trailing slashes are stripped automatically.

Returns

void

Example

1import { AgentBase, AgentServer } from '@signalwire/sdk';
2
3function routeByLanguage(body: Record<string, unknown>): string | undefined {
4 const lang = (body['lang'] as string | undefined) ?? 'en';
5 if (lang.startsWith('es')) return '/spanish-agent';
6 if (lang.startsWith('fr')) return '/french-agent';
7 return undefined;
8}
9
10const english = new AgentBase({ name: 'english', route: '/english-agent' });
11english.setPromptText('You are a helpful assistant. Respond in English.');
12const spanish = new AgentBase({ name: 'spanish', route: '/spanish-agent' });
13spanish.setPromptText('You are a helpful assistant. Respond in Spanish.');
14const french = new AgentBase({ name: 'french', route: '/french-agent' });
15french.setPromptText('You are a helpful assistant. Respond in French.');
16
17const server = new AgentServer({ port: 3000 });
18server.register(english);
19server.register(spanish);
20server.register(french);
21server.registerGlobalRoutingCallback(routeByLanguage, '/route');
22await server.run();