Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

260 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SignalWire SDK for Rust

Build AI voice agents, control live calls over WebSocket, and manage every SignalWire resource over REST -- all from one crate.

Documentation · Report an Issue · crates.io

Discord MIT License GitHub Stars

Open in GitHub Codespaces Run on Replit


What's in this SDK

Capability What it does Quick link
AI Agents Build voice agents that handle calls autonomously -- the platform runs the AI pipeline, your code defines the persona, tools, and call flow Agent Guide
RELAY Client Control live calls and SMS/MMS in real time over WebSocket -- answer, play, record, collect DTMF, conference, transfer, and more RELAY docs
REST Client Manage SignalWire resources over HTTP -- phone numbers, SIP endpoints, Fabric AI agents, video rooms, messaging, and the full namespaced API surface REST docs
cargo add signalwire-sdk

Published as signalwire-sdk on crates.io. The library import path is still signalwire, so use signalwire::... works unchanged.


AI Agents

Each agent is a self-contained microservice that generates SWML (SignalWire Markup Language) and handles SWAIG (SignalWire AI Gateway) tool calls. The SignalWire platform runs the entire AI pipeline (STT, LLM, TTS) -- your agent just defines the behavior.

use serde_json::json;
use signalwire::agent::{AgentBase, AgentOptions};
use signalwire::swaig::FunctionResult;

fn main() {
    let mut agent = AgentBase::new(AgentOptions::new("my-agent"));

    agent.add_language("English", "en-US", "rime.spore");
    agent.prompt_add_section("Role", "You are a helpful assistant.", vec![]);

    agent.define_tool(
        "get_time",
        "Get the current time",
        json!({}),
        Box::new(|_args, _raw| {
            let now = chrono::Local::now().format("%H:%M:%S");
            FunctionResult::with_response(&format!("The time is {now}"))
        }),
        false,
    );

    agent.run();
}

Test locally without binding a port -- introspect an example by name, or point at a running SWAIG endpoint:

# Introspect a SWMLService example in-process (by example name)
cargo run --bin swaig-test -- --example swmlservice_swaig_standalone --list-tools

# Exercise a live SWAIG endpoint over HTTP
cargo run --bin swaig-test -- --url http://user:pass@localhost:3000/ --list-tools
cargo run --bin swaig-test -- --url http://user:pass@localhost:3000/ --dump-swml
cargo run --bin swaig-test -- --url http://user:pass@localhost:3000/ --exec get_time

Agent Features

  • Prompt Object Model (POM) -- structured prompt composition via prompt_add_section()
  • SWAIG tools -- define functions with define_tool() that the AI calls mid-conversation, with native access to the call's media stack
  • Skills system -- add capabilities with one-liners: agent.add_skill("datetime", json!({}))
  • Contexts and steps -- structured multi-step workflows with navigation control
  • DataMap tools -- tools that execute on SignalWire's servers, calling REST APIs without your own webhook
  • Dynamic configuration -- per-request agent customization for multi-tenant deployments
  • Call flow control -- pre-answer, post-answer, and post-AI verb insertion
  • Prefab agents -- ready-to-use archetypes (InfoGatherer, Survey, FAQ, Receptionist, Concierge)
  • Multi-agent hosting -- serve multiple agents on a single server with AgentServer
  • SIP routing -- route SIP calls to agents based on usernames
  • Session state -- persistent conversation state with global data and post-prompt summaries
  • Security -- auto-generated basic auth, function-specific HMAC tokens, SSL support
  • Serverless -- deploy to Lambda, Cloud Functions, Azure Functions

Agent Examples

The examples/ directory contains working examples:

Example What it demonstrates
simple_agent.rs POM prompts, SWAIG tools, multilingual support, LLM tuning
contexts_demo.rs Multi-persona workflow with context switching and step navigation
data_map_demo.rs Server-side API tools without webhooks
skills_demo.rs Loading built-in skills (datetime, math)
call_flow_and_actions_demo.rs Call flow verbs, debug events, FunctionResult actions
session_and_state_demo.rs OnSummary, global data, post-prompt summaries
multi_agent_server.rs Multiple agents on one server
lambda_agent.rs AWS Lambda deployment
comprehensive_dynamic_agent.rs Per-request dynamic configuration, multi-tenant routing

See examples/README.md for the full list organized by category.


RELAY Client

Real-time call control and messaging over WebSocket. The RELAY client connects to SignalWire via the Blade protocol and gives you imperative control over live phone calls and SMS/MMS. The client runs its event loop on a background thread, so the handler closures are synchronous.

use signalwire::relay::Client;
use std::sync::Arc;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Reads SIGNALWIRE_PROJECT_ID / SIGNALWIRE_API_TOKEN / SIGNALWIRE_SPACE.
    let client = Arc::new(Client::from_env()?);

    client.on_call(|call, _event| {
        // Verbs return `Result<_, RelayError>` — a rejected verb surfaces as Err.
        let _ = call.answer();
        if let Ok(action) = call.play(serde_json::json!({
            "play": [{
                "type": "tts",
                "params": {"text": "Welcome to SignalWire!"}
            }]
        })) {
            let _ = action.is_done();
        }
        let _ = call.hangup();
    });

    println!("Waiting for inbound calls ...");
    client.connect()?;
    client.receive(&["default".to_string()]);

    // Block while the relay loop runs in the background.
    loop {
        std::thread::sleep(std::time::Duration::from_secs(60));
    }
}
  • 50+ calling methods (play, record, collect, detect, tap, stream, AI, conferencing, and more)
  • SMS/MMS messaging with delivery tracking
  • Action objects with is_done(), state(), result(), on_completed(), stop()
  • Caller-driven reconnect() with exponential backoff (on connection loss the client stops — is_running() returns false and pending requests fault — rather than reconnecting silently)

See the RELAY documentation for the full guide, API reference, and examples.


REST Client

Blocking (synchronous) REST client for managing SignalWire resources and controlling calls over HTTP. No WebSocket and no async runtime required.

use serde_json::json;
use signalwire::rest::RestClient;
use signalwire::rest::namespaces::generated::calling_resources_generated::CallingDialRequest;
use std::collections::HashMap;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Reads SIGNALWIRE_PROJECT_ID / SIGNALWIRE_API_TOKEN / SIGNALWIRE_SPACE.
    let client = RestClient::from_env().expect("missing SIGNALWIRE_* env vars");

    client.fabric().ai_agents().create(
        &json!({
            "name": "Support Bot",
            "prompt": {"text": "You are helpful."}
        }),
        None,
    )?;

    client.calling().dial(
        CallingDialRequest::new("+15559876543", "+15551234567")
            .url("https://example.com/call-handler"),
        None,
    )?;

    let query = HashMap::from([("areacode".to_string(), "512".to_string())]);
    let results = client.phone_numbers().search(&query, None)?;
    println!("{results:#?}");

    Ok(())
}
  • Namespaced API surfaces: Fabric, Calling, Video, Datasphere, Phone Numbers, SIP, Queues, Recordings, and more
  • Backed by ureq (blocking HTTP) with a reusable ureq::Agent for connection pooling
  • serde_json::Value returns -- raw JSON, no wrapper objects; errors surface as SignalWireRestError

See the REST documentation for the full guide, API reference, and examples.


Installation

Pre-release note. This README documents the 4.x surface. The latest version currently published to crates.io lags the source, so cargo add signalwire-sdk may resolve an older crate that lacks the APIs below. Until 4.x is published, install from source (the git dependency shown last) to get the surface this README describes.

Add to your Cargo.toml:

[dependencies]
signalwire = { package = "signalwire-sdk", version = "4" }

The crate is published as signalwire-sdk (the bare signalwire name is held by an unofficial wrapper); the package = rename keeps the import path as use signalwire::....

Or with cargo:

cargo add signalwire-sdk

Install from source (current 4.x surface)

Point the dependency at the git repository to build the exact surface this README documents before the 4.x crate is published:

[dependencies]
signalwire = { package = "signalwire-sdk", git = "https://github.com/signalwire/signalwire-rust", branch = "main" }

Or clone and build locally:

git clone https://github.com/signalwire/signalwire-rust
cd signalwire-rust
cargo build

Requires Rust edition 2024 with a minimum supported rustc of 1.88 (let-chains, enforced via rust-version in Cargo.toml).

Documentation

Full reference documentation is available at developer.signalwire.com/sdks/agents-sdk.

Guides are also available in the docs/ directory:

Getting Started

  • Agent Guide -- creating agents, prompt configuration, dynamic setup
  • Architecture -- SDK architecture and core concepts
  • SDK Features -- feature overview, SDK vs raw SWML comparison

Core Features

Skills and Extensions

  • Skills System -- built-in skills and the modular framework
  • Third-Party Skills -- creating and publishing custom skills
  • MCP Integration -- Model Context Protocol integration (add external MCP servers, expose tools as an MCP server)

Deployment

Reference

Environment Variables

Your SIGNALWIRE_PROJECT_ID, SIGNALWIRE_API_TOKEN, and SIGNALWIRE_SPACE come from the API section of your SignalWire Dashboard (create a free account at signalwire.com if you don't have one).

Variable Used by Description
SIGNALWIRE_PROJECT_ID RELAY, REST Project identifier
SIGNALWIRE_API_TOKEN RELAY, REST API token
SIGNALWIRE_SPACE RELAY, REST Space hostname (e.g. example.signalwire.com)
SIGNALWIRE_REST_BASE_URL REST Override the REST base URL (RestClient::from_env); replaces the https://{SIGNALWIRE_SPACE} resolution when set
SWML_BASIC_AUTH_USER Agents Basic auth username (default: auto-generated)
SWML_BASIC_AUTH_PASSWORD Agents Basic auth password (default: auto-generated)
SWML_PROXY_URL_BASE Agents Base URL when behind a reverse proxy
SWML_SSL_ENABLED Agents Enable HTTPS (true, 1, yes)
SWML_SSL_CERT_PATH Agents Path to SSL certificate
SWML_SSL_KEY_PATH Agents Path to SSL private key
SIGNALWIRE_LOG_LEVEL All Logging level (debug, info, warn, error)
SIGNALWIRE_LOG_MODE All Set to off to suppress all logging

Testing, Linting, Formatting

Format, lint, and test go through three canonical scripts under scripts/. They self-bootstrap the Rust toolchain (adding rustfmt/clippy if missing) and resolve the repo from their own path, so they run identically from any working directory. scripts/run-ci.sh's FMT/LINT/TEST gates call these same scripts — no drift between a local run and CI.

# Run the test suite (optional filter passes through to cargo)
bash scripts/run-tests.sh
bash scripts/run-tests.sh test_connect_returns_protocol_string

# Lint (cargo clippy --all-targets, -D warnings); --fix applies clippy autofixes
bash scripts/run-lint.sh

# Format in place; --check for verify-only (the CI FMT gate)
bash scripts/run-format.sh
bash scripts/run-format.sh --check

Direct cargo invocations still work when you want them:

# Run with verbose output
cargo test -- --nocapture

# Coverage (requires cargo-tarpaulin)
cargo tarpaulin --out html

License

MIT -- see LICENSE for details.

About

SignalWire Rust SDK

Resources

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages