Helper Functions & Utilities

View as MarkdownOpen in Claude

The SignalWire Agents SDK exports helper functions and utilities at the top level for common tasks like creating standalone contexts, building server-side API tools, managing environment variable expansion, security, and type inference. All are imported directly from @signalwire/sdk.

1import {
2 createSimpleContext,
3 createSimpleApiTool,
4 createExpressionTool,
5 setAllowedEnvPrefixes,
6 getAllowedEnvPrefixes,
7 safeAssign,
8 filterSensitiveHeaders,
9 redactUrl,
10 inferSchema,
11 registerBuiltinSkills,
12} from '@signalwire/sdk';

createSimpleContext

1createSimpleContext(name?: string): Context

Create a standalone Context object without needing a full ContextBuilder. Useful for quick single-context agents.

Parameters

name
stringDefaults to default

Context name. For single-context agents this is typically "default".

Returns

Context — A new Context object ready for adding steps.

Example

1import { createSimpleContext } from '@signalwire/sdk';
2
3const ctx = createSimpleContext();
4ctx.addStep('greet', { task: 'Say hello to the caller.' });
5ctx.addStep('help', { task: 'Ask how you can help today.' });

createSimpleApiTool

1createSimpleApiTool(opts: {
2 name: string;
3 url: string;
4 responseTemplate: string;
5 parameters?: Record<string, {
6 type?: string;
7 description?: string;
8 required?: boolean;
9 }>;
10 method?: string;
11 headers?: Record<string, string>;
12 body?: Record<string, unknown>;
13 errorKeys?: string[];
14}): DataMap

Create a server-side API tool with minimal configuration. Returns a configured DataMap that executes an HTTP request on the SignalWire server without requiring a webhook endpoint.

Parameters

opts.name
stringRequired

The name for the SWAIG tool.

opts.url
stringRequired

API endpoint URL. Supports $&#123;args.paramName&#125; substitution for injecting parameter values (e.g., "https://api.example.com/search?q=$&#123;args.query&#125;").

opts.responseTemplate
stringRequired

Template string for formatting the API response. Uses $&#123;response.field&#125; syntax to reference fields from the API response JSON.

opts.parameters
Record<string, object>

Parameter definitions. Each key is a parameter name, and each value is an object with type (default "string"), description, and optionally required.

opts.method
stringDefaults to GET

HTTP method for the API call.

opts.headers
Record<string, string>

HTTP headers to include in the request.

opts.body
Record<string, unknown>

Request body for POST/PUT requests.

opts.errorKeys
string[]

JSON keys whose presence in the response indicates an error.

Returns

DataMap — A configured DataMap ready to be registered with an agent.

Example

1import { AgentBase, createSimpleApiTool } from '@signalwire/sdk';
2
3const weatherTool = createSimpleApiTool({
4 name: 'get_weather',
5 url: 'https://api.weather.com/v1/current?key=API_KEY&q=${args.location}',
6 responseTemplate:
7 'Weather in ${args.location}: ${response.current.condition.text}, ${response.current.temp_f}F',
8 parameters: {
9 location: {
10 type: 'string',
11 description: 'City name',
12 required: true,
13 },
14 },
15});
16
17const agent = new AgentBase({ name: 'weather-agent' });
18weatherTool.registerWithAgent(agent);

For more complex API integrations with multiple webhooks, fallback outputs, or array processing, use the DataMap builder directly.


createExpressionTool

1createExpressionTool(opts: {
2 name: string;
3 patterns: Record<string, [string, FunctionResult]>;
4 parameters?: Record<string, {
5 type?: string;
6 description?: string;
7 required?: boolean;
8 }>;
9}): DataMap

Create a pattern-matching tool that evaluates expressions locally on the SignalWire server without making any HTTP requests. Useful for command routing and conditional responses.

Parameters

opts.name
stringRequired

The name for the SWAIG tool.

opts.patterns
Record<string, [string, FunctionResult]>Required

A record mapping test values to [pattern, FunctionResult] tuples. The key is a template string (e.g., "$&#123;args.command&#125;"), and the pattern is a regex string matched against it.

opts.parameters
Record<string, object>

Parameter definitions, same format as createSimpleApiTool.

Returns

DataMap — A configured DataMap with expression-based routing.

Example

1import { AgentBase, FunctionResult, createExpressionTool } from '@signalwire/sdk';
2
3const routingTool = createExpressionTool({
4 name: 'route_command',
5 patterns: {
6 '${args.command}': [
7 'play.*',
8 new FunctionResult('Starting playback.'),
9 ],
10 },
11 parameters: {
12 command: { type: 'string', description: 'The command to route', required: true },
13 filename: { type: 'string', description: 'File to play' },
14 },
15});
16
17const agent = new AgentBase({ name: 'router' });
18routingTool.registerWithAgent(agent);

Since object keys must be unique, you cannot map multiple patterns against the same test value using createExpressionTool. For that case, use the DataMap builder and call .expression() multiple times.


setAllowedEnvPrefixes

1setAllowedEnvPrefixes(prefixes: string[]): void

Set the global allowed environment variable prefixes for $&#123;ENV.*&#125; expansion in DataMap URLs, bodies, and outputs. Only environment variables whose names start with one of these prefixes will be expanded.

The default prefixes are ['SIGNALWIRE_', 'SWML_', 'SW_'].

Parameters

prefixes
string[]Required

Array of prefix strings to allow. Pass an empty array to allow all environment variables (escape hatch — use with caution).

Example

1import { setAllowedEnvPrefixes } from '@signalwire/sdk';
2
3// Allow custom prefixes in addition to defaults
4setAllowedEnvPrefixes(['SIGNALWIRE_', 'SWML_', 'SW_', 'MY_APP_']);

getAllowedEnvPrefixes

1getAllowedEnvPrefixes(): string[]

Get a copy of the current global allowed environment variable prefixes.

Returns

string[] — A copy of the current prefix list.

Example

1import { getAllowedEnvPrefixes } from '@signalwire/sdk';
2
3const prefixes = getAllowedEnvPrefixes();
4console.log(prefixes);
5// ['SIGNALWIRE_', 'SWML_', 'SW_']

safeAssign

Copy properties from source to target, filtering out prototype-pollution keys (__proto__, constructor, prototype). Drop-in replacement for Object.assign() where source is untrusted.

Parameters

target
Record<string, unknown>Required

The object to assign into.

source
Record<string, unknown>Required

The object to copy properties from.

Returns

The target object.

Example

1import { safeAssign } from '@signalwire/sdk';
2
3const target = { a: 1 };
4safeAssign(target, { b: 2, __proto__: 'blocked' });
5console.log(target); // { a: 1, b: 2 }

filterSensitiveHeaders

Return a copy of headers with sensitive entries removed (authorization, cookie, x-api-key, proxy-authorization, set-cookie).

Parameters

headers
Record<string, string>Required

Original header record.

Returns

Record<string, string> — A new record with sensitive headers removed.

Example

1import { filterSensitiveHeaders } from '@signalwire/sdk';
2
3const raw = { 'content-type': 'application/json', authorization: 'Bearer secret' };
4const safe = filterSensitiveHeaders(raw);
5console.log(safe); // { 'content-type': 'application/json' }

redactUrl

Redact credentials embedded in a URL. Replaces the password portion with ****.

Parameters

url
stringRequired

The URL string to redact.

Returns

string — The URL with the password replaced by ****.

Example

1import { redactUrl } from '@signalwire/sdk';
2
3console.log(redactUrl('https://admin:secret@example.com/api'));
4// "https://admin:****@example.com/api"

MAX_SKILL_INPUT_LENGTH

Maximum allowed input length for skill handler arguments (characters). Value: 1000.

Example

1import { MAX_SKILL_INPUT_LENGTH } from '@signalwire/sdk';
2
3console.log(MAX_SKILL_INPUT_LENGTH); // 1000

inferSchema

Infer a JSON Schema from a function’s source code by parsing parameter names and default values. Used internally by defineTypedTool().

Parameters

fn
FunctionRequired

The function to analyze.

Returns

InferredSchema | null — The inferred schema with parameters, required, paramNames, and hasRawData fields, or null if inference fails.

Example

1import { inferSchema } from '@signalwire/sdk';
2
3const schema = inferSchema((city: string, units = 'metric') => {});
4console.log(schema?.parameters);
5// { city: { type: 'string' }, units: { type: 'string' } }
6console.log(schema?.required); // ['city']

parseFunctionParams

Parse function parameter names and default values from source code text.

Parameters

source
stringRequired

The function source code string (via fn.toString()).

Returns

ParsedParam[] — Array of { name: string; defaultValue?: string } objects.


createTypedHandlerWrapper

Create a wrapper function that unpacks a Record<string, unknown> args dict into named positional parameters for a typed handler.

Parameters

fn
FunctionRequired

The original typed handler function.

paramNames
string[]Required

Ordered parameter names to extract from args.

hasRawData
booleanRequired

Whether the handler accepts a rawData parameter.

Returns

SwaigHandler — A wrapped handler with the standard (args, rawData) signature.


PomSection

A single section in a Prompt Object Model, with a title, body, bullets, and nested subsections. Returned by PomBuilder.getSection() and PomBuilder.findSection().

Properties

title
string | null

Section heading text, or null if untitled.

body
string

Section body paragraph text.

bullets
string[]

List of bullet point strings.

subsections
PomSection[]

Nested child sections.

numbered
boolean | null

Whether this section is numbered when rendered.

numberedBullets
boolean

Whether bullet points are rendered as a numbered list.


registerBuiltinSkills

Register all 19 built-in skills with the global SkillRegistry. Call this once at startup if you want to use SkillRegistry.create('datetime') style registration.

Parameters

None.

Returns

void

Example

1import { registerBuiltinSkills, SkillRegistry } from '@signalwire/sdk';
2
3registerBuiltinSkills();
4const registry = SkillRegistry.getInstance();
5console.log(registry.listRegistered()); // ['datetime', 'math', 'joke', ...]