# Sarj.ai > Voice AI platform — build production AI-powered phone calls > ## Agent Instructions > Use OpenAPI for fields and errors; the Python guide and PyPI for SDK capabilities and availability. Scenario IDs are dashboard UUIDs. Bound polling; reports may stay null. Reconcile ambiguous call creation before retrying. Docs MCP reads docs and accepts feedback; API MCP performs authenticated call actions. # Cancel a scheduled call Source: https://platform-docs.sarj.ai/api-reference/calls/cancel-a-pending-scheduled-sarjai-call /api-reference/openapi.json post /calls/{call_id}/cancel Cancel a pending call or retry, ending its retry chain. # Get a call Source: https://platform-docs.sarj.ai/api-reference/calls/fetch-sarjai-voice-call-details-by-call_id /api-reference/openapi.json get /calls/{call_id} Get a call's details and latest outcome. # Reschedule a call Source: https://platform-docs.sarj.ai/api-reference/calls/move-a-pending-scheduled-sarjai-call-to-a-new-time /api-reference/openapi.json post /calls/{call_id}/reschedule Move a pending call to a new dial time. # Create a call Source: https://platform-docs.sarj.ai/api-reference/calls/place-an-outbound-sarjai-voice-call /api-reference/openapi.json post /calls Start or schedule an outbound call. # Get a recording Source: https://platform-docs.sarj.ai/api-reference/calls/redirect-to-a-fresh-download-url-for-a-sarjai-call-recording /api-reference/openapi.json get /calls/{call_id}/recording Redirect to a fresh recording download. API keys take precedence; invalid keys never fall back to tokens. # API overview Source: https://platform-docs.sarj.ai/api-reference/overview Base URL, authentication, and errors. ## Base URL ```text theme={null} https://platform-api.sarj.ai/api/v1 ``` ## Authentication Send your dashboard API key as a Bearer token on API operations. `GET /health` is public, and recording links can also use the call-scoped token embedded in the link. ```bash theme={null} Authorization: Bearer $SARJ_API_KEY ``` Create and copy an API key from the [Sarj.ai dashboard](https://platform.sarj.ai/api-keys). The key is shown only once. ## Responses and errors JSON success responses contain `data` and `meta`; errors contain `error` and `meta`. The generated reference documents each endpoint's fields and responses. Branch on `error.type`, not the human-readable message. Retain `meta.request_id` for support, falling back to the `X-Request-ID` header when it is null. Follow the [quickstart](/getting-started) for a first call and the [SDK recovery guide](/python-sdk#errors-timeouts-and-retries) for errors, timeouts, and retries. [Download OpenAPI](/api-reference/openapi.json). # Create a retry policy Source: https://platform-docs.sarj.ai/api-reference/schedule-configs/create-a-sarjai-schedule-config-retry-policy-for-outbound-calls /api-reference/openapi.json post /schedule-configs Create a reusable dial-retry policy. This API is create-only. # Check health Source: https://platform-docs.sarj.ai/api-reference/system/health-check /api-reference/openapi.json get /health No authentication required. # Receive a call outcome Source: https://platform-docs.sarj.ai/api-reference/webhooks/receive-a-call-outcome /api-reference/openapi.json webhook callEnded Sent to your webhook URL, not a Sarj API endpoint. Use its optional configured credential, not your API key. Persist and deduplicate by `call_id`, then acknowledge within 5 seconds. `complete` includes voicemail; inspect `payload.call_data.status` for its outcome. # Getting Started Source: https://platform-docs.sarj.ai/getting-started REST quickstart — API key, health check, first call. ## Prerequisites * A Sarj.ai account * An API key — see Step 1 below * Python: `pip install sarj-platform-sdk` (recommended over raw `requests`) > [!NOTE] > > If you're using the [MCP Server](/mcp-server) with an OAuth-capable client instead of the REST API, skip Step 1. The client receives an API key through Sarj sign-in on first connect. Other MCP clients need a dashboard API key. **1. Get your API key** 1. Sign in at [platform.sarj.ai](https://platform.sarj.ai/api-keys) 2. Click **Generate Key** 3. Copy the key and store it securely > [!WARNING] > > Your API key is shown **only once**. Replace `...` with it and store it as an environment variable: > > ```bash theme={null} > export SARJ_API_KEY="..." > ``` **2. Verify your setup** Confirm the API is reachable with a health check. This endpoint is public, so a successful response does not validate your API key. ```python Python (SDK) theme={null} from sarj_platform_sdk import SDK with SDK(timeout_ms=10_000) as sdk: print(sdk.system.get_health().data.status) # "ok" ``` ```bash curl theme={null} curl --fail-with-body --max-time 10 https://platform-api.sarj.ai/api/v1/health ``` ```python Python (requests) theme={null} import requests response = requests.get("https://platform-api.sarj.ai/api/v1/health", timeout=10) response.raise_for_status() print(response.json()) ``` ```typescript TypeScript theme={null} const response = await fetch("https://platform-api.sarj.ai/api/v1/health", { signal: AbortSignal.timeout(10_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const data = await response.json(); console.log(data); ``` Expected result: `data.status` is `"ok"`. **3. Create your first call** Trigger an outbound voice call. Requires your API key and a scenario ID. Run the TypeScript example on Node.js 22 or newer, in a server or trusted local script. Keep your API key out of browser code. > [!TIP] > > Create an active scenario at [platform.sarj.ai/scenarios](https://platform.sarj.ai/scenarios?status=active) and copy its UUID. Set `SARJ_SCENARIO_ID` to that value and `TEST_PHONE_NUMBER` to a number you intend to call, in E.164 format. The UUID below is illustrative; replace it with your own scenario. ```bash theme={null} export SARJ_SCENARIO_ID="550e8400-e29b-41d4-a716-446655440000" export TEST_PHONE_NUMBER="+966512345678" ``` ```python Python (SDK) theme={null} import os from sarj_platform_sdk import SDK with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: res = sdk.calls.create_call( phone_number=os.environ["TEST_PHONE_NUMBER"], scenario_id=os.environ["SARJ_SCENARIO_ID"], language="ar", ) print(f"Call ID: {res.data.id}") ``` ```bash curl theme={null} curl --fail-with-body --max-time 10 https://platform-api.sarj.ai/api/v1/calls \ -H "Authorization: Bearer $SARJ_API_KEY" \ -H "Content-Type: application/json" \ -d "{\"phone_number\":\"$TEST_PHONE_NUMBER\",\"scenario_id\":\"$SARJ_SCENARIO_ID\",\"language\":\"ar\"}" ``` ```python Python (requests) theme={null} import os import requests response = requests.post( "https://platform-api.sarj.ai/api/v1/calls", headers={"Authorization": f"Bearer {os.environ['SARJ_API_KEY']}"}, json={ "phone_number": os.environ["TEST_PHONE_NUMBER"], "scenario_id": os.environ["SARJ_SCENARIO_ID"], "language": "ar", }, timeout=10, ) response.raise_for_status() call = response.json() print(f"Call ID: {call['data']['id']}") ``` ```typescript TypeScript theme={null} const apiKey = process.env.SARJ_API_KEY; const response = await fetch("https://platform-api.sarj.ai/api/v1/calls", { method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json", }, body: JSON.stringify({ phone_number: process.env.TEST_PHONE_NUMBER, scenario_id: process.env.SARJ_SCENARIO_ID, language: "ar", }), signal: AbortSignal.timeout(10_000), }); if (!response.ok) throw new Error(`HTTP ${response.status}`); const call = await response.json(); console.log(`Call ID: ${call.data.id}`); ``` A successful request returns `202 Accepted`. Save `data.id`; see the [response schema](/api-reference/calls/place-an-outbound-sarjai-voice-call). **4. Track the call** Fetch the returned ID with [GET /calls/](/api-reference/calls/fetch-sarjai-voice-call-details-by-call_id), or use [webhooks](/webhooks) for push delivery. Reports are generated asynchronously for `completed` and `max_duration_reached` calls. Other terminal states never receive a report; rare generation failures can leave an eligible call without one too. Bound your polling and handle a missing report. Prefer `permanent_recording_url`; during its rollout, fall back to `recording_url` when the permanent field is null. See the [Python SDK guide](/python-sdk) for an inspection example and future-call scheduling. For response envelopes, authentication, and request IDs, see the [API overview](/api-reference/overview). Use the [SDK recovery guide](/python-sdk#errors-timeouts-and-retries) to decide when to retry. # Sarj.ai Developer API Source: https://platform-docs.sarj.ai/index REST API and MCP server for outbound voice calls. > [card] [Get started](/getting-started) > > REST quickstart — API key, health check, first call. > [card] [API Reference](/api-reference/overview) > > Interactive endpoint docs with request/response schemas + Try It. > [card] [MCP Server](/mcp-server) > > Connect Claude Code, Cursor, or any MCP-compatible agent. > [card] [Python SDK](/python-sdk) > > `pip install sarj-platform-sdk` > [card] [Support](mailto:support@sarj.ai) > > Email support. # MCP Server Source: https://platform-docs.sarj.ai/mcp-server Expose the Sarj.ai API as MCP tools for AI agents. Connect an [MCP](https://modelcontextprotocol.io) client to place and inspect calls. **Server URL:** `https://platform-api.sarj.ai/api/v1/mcp` Use the server that matches the task: | Server | Purpose | Authentication | | - | - | - | | `https://platform-docs.sarj.ai/mcp` | Search and read documentation | Public | | `https://platform-api.sarj.ai/api/v1/mcp` | Create, inspect, cancel, and reschedule calls | Your Sarj account | The documentation server cannot place calls. Mintlify also exposes a documentation-feedback tool; it does not control calls. The [published agent skill](/skill.md) explains identifiers, result readiness, and retry constraints. ## Prerequisites * A Sarj.ai account — [sign in at platform.sarj.ai](https://platform.sarj.ai) * An MCP-compatible client (Claude Code, Cursor, or any MCP SDK) **1. Connect your MCP client** Add the Sarj.ai MCP server to your client. ```bash Claude Code theme={null} # Add the server (run once) claude mcp add sarj-voice \ --transport http \ https://platform-api.sarj.ai/api/v1/mcp # Verify it was added claude mcp list ``` ```json Cursor / JSON config theme={null} { "mcpServers": { "sarj-voice": { "type": "http", "url": "https://platform-api.sarj.ai/api/v1/mcp" } } } ``` **2. Authenticate** OAuth-capable clients open Sarj.ai sign-in on first connect and cache the issued API key. Other clients must send a [dashboard API key](https://platform.sarj.ai/api-keys) as `Authorization: Bearer ` using their HTTP-header configuration. > [!WARNING] > > Keys are scoped to your account and organization. Generate a separate [dashboard key](https://platform.sarj.ai/api-keys) for direct API or SDK access. **3. Prompt your agent** Example prompts: ```text Trigger a call theme={null} Call +966512345678 using scenario 550e8400-e29b-41d4-a716-446655440000 with language set to Arabic. ``` ```text Track status theme={null} Check the status of 8f9b2c1e-4a5d-4f6e-8b1a-2c3d4e5f6a7b. Tell me if it completed and how long it lasted. ``` ```text Batch calls theme={null} Trigger calls to all numbers in this list using scenario 550e8400-e29b-41d4-a716-446655440000: +966512345678, +966598765432, +966501234567 Check each call for up to five minutes, then report its status and any available results. ``` Replace the illustrative UUID with an active scenario ID copied from your dashboard. Confirm the recipient numbers before asking the agent to place real calls. ## Available tools | Tool | Description | | - | - | | `createCall` | Place an outbound voice call (see [POST /calls](/api-reference/calls/place-an-outbound-sarjai-voice-call)) | | `getCall` | Fetch call details by `call_id` (see [GET /calls/](/api-reference/calls/fetch-sarjai-voice-call-details-by-call_id)) | | `cancelScheduledCall` | Cancel a pending scheduled call or retry attempt | | `rescheduleScheduledCall` | Move a pending scheduled call to another time | Schedule-config creation is currently a REST/SDK operation, not an action MCP tool. Reports are asynchronous and can remain null; do not poll indefinitely or infer webhook outcome types from call-status names. # Python SDK Source: https://platform-docs.sarj.ai/python-sdk Typed Python client with sync and async methods. `sarj-platform-sdk` supports Python 3.10+ and defaults to `https://platform-api.sarj.ai/api/v1`. ## Install ```bash pip theme={null} pip install --upgrade sarj-platform-sdk ``` ```bash uv theme={null} uv add sarj-platform-sdk ``` Store `SARJ_API_KEY` in your environment or a secret manager. Set `SARJ_SCENARIO_ID` to an active [dashboard](https://platform.sarj.ai/scenarios?status=active) scenario UUID and `TEST_PHONE_NUMBER` to an intended recipient. ## Create and inspect a call ```python theme={null} import os from sarj_platform_sdk import SDK with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: created = sdk.calls.create_call( phone_number=os.environ["TEST_PHONE_NUMBER"], scenario_id=os.environ["SARJ_SCENARIO_ID"], language="ar", ) call = sdk.calls.get_call(call_id=created.data.id) print(call.data.id, call.data.status) ``` `create_call` returns on acceptance. Save `created.data.id`; fetch it again or use [webhooks](/webhooks). Reports arrive asynchronously and may remain null permanently; [the response reference](/api-reference/calls/fetch-sarjai-voice-call-details-by-call_id) explains eligibility and recording availability. Bound polling by elapsed time. `with SDK(...)` and `async with SDK(...)` close clients owned by the SDK. There are no public `close()` or `aclose()` methods. Your application owns supplied HTTPX `client=` or `async_client=` instances and must close them. Reuse the SDK within its context. ## Async calls Await each operation's `_async` variant: ```python theme={null} import asyncio import os from sarj_platform_sdk import SDK async def main(): async with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: call = await sdk.calls.get_call_async(call_id=os.environ["SARJ_CALL_ID"]) print(call.data.status) asyncio.run(main()) ``` Set `SARJ_CALL_ID` to a returned call ID. In an existing event loop, use `await main()` instead of `asyncio.run()`. ## Schedule a call Scheduling requires SDK 0.4.0 or newer. Check [PyPI](https://pypi.org/project/sarj-platform-sdk/) for availability; use the REST reference until that version is published. Compute `scheduled_at` as a timezone-aware `datetime` when sending: 10 minutes to 30 days ahead. Policy `timezone` belongs beside `retry_window`, not inside it. Omit `scheduled_at` or pass `None` for an immediate call. Validate untyped input: `{}` can be treated as an omitted timestamp. ```python theme={null} from datetime import datetime, timedelta, timezone import os from sarj_platform_sdk import SDK with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: policy = sdk.schedule_configs.create_schedule_config( max_retries=2, wait_between="PT2H", retry_window={ "start_edge": {"hour": 9, "minute": 0}, "end_edge": {"hour": 17, "minute": 0}, }, timezone="Asia/Riyadh", expire_after="P3D", ) call = sdk.calls.create_call( phone_number=os.environ["TEST_PHONE_NUMBER"], scenario_id=os.environ["SARJ_SCENARIO_ID"], scheduled_at=datetime.now(timezone.utc) + timedelta(hours=1), schedule_config_id=policy.data.id, ) print(call.data.id, call.data.status) ``` `max_retries=2` permits up to two policy retries after eligible unsuccessful outcomes; infrastructure failure redials do not consume this budget. Policy expiry is one hour to seven days. Scheduling must be enabled for your organization/deployment (`scheduling_disabled`). Cancel or reschedule only while pending; after release for dialing, expect `409 call_not_pending`. Infrastructure redials use a separate delay and bypass policy windows and expiry; the seven-day platform ceiling still applies. For `call.data.booking_outcome` of `rescheduled_existing` or `kept_existing`, use the returned ID and time: they identify an existing pending booking for the same scenario and number. Omitted `schedule_config_id` uses the scenario's default policy, if configured. Save policy IDs: the policy API is create-only (no fetch, list, update, or disable). Set `SARJ_CALL_ID` to the returned booking ID. These actions are alternatives; cancelling after rescheduling cancels the moved booking: ```python theme={null} from datetime import datetime, timedelta, timezone import os from sarj_platform_sdk import SDK with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: moved = sdk.calls.reschedule_scheduled_call( call_id=os.environ["SARJ_CALL_ID"], scheduled_at=datetime.now(timezone.utc) + timedelta(hours=2), ) print(moved.data.id, moved.data.scheduled_at) ``` ```python theme={null} import os from sarj_platform_sdk import SDK with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: cancelled = sdk.calls.cancel_scheduled_call(call_id=os.environ["SARJ_CALL_ID"]) print(cancelled.data.id, cancelled.data.status) ``` ## Errors, timeouts, and retries ```python theme={null} import os import httpx from sarj_platform_sdk import SDK, errors try: with SDK(api_key_auth=os.environ["SARJ_API_KEY"], timeout_ms=10_000) as sdk: call = sdk.calls.get_call(call_id=os.environ["SARJ_CALL_ID"]) print(call.data.status) except errors.ErrorResponse as exc: request_id = exc.data.meta.request_id or exc.headers.get("x-request-id") print(exc.data.error.type, request_id) except errors.SDKError as exc: print(exc.status_code, exc.headers.get("x-request-id")) except httpx.TimeoutException: print("Request timed out; reconcile any write before resubmitting.") except httpx.RequestError: print("Transport failed; reconcile any write before resubmitting.") ``` Branch on `error.type`, retain the request ID, and handle HTTPX failures separately. Unknown HTTP response shapes can raise `SDKError`. If `meta.request_id` is null, as with some authentication rejections, use `X-Request-ID`. | Result | Next action | | - | - | | `401 unauthorized` | Check the key, organization, and revocation. `/health` does not validate keys. | | `403 phone_number_blocked`, `scenario_forbidden`, or `no_organization` | Resolve access or policy before retrying. | | `403 scheduling_disabled` | Contact support; backoff cannot enable scheduling. | | `404 call_not_found`, `scenario_not_found`, or `schedule_config_not_found` | Check the ID and owning organization. | | `409 call_not_pending` | Fetch current state. Calls released for dialing cannot be moved or cancelled. | | `422 validation_error`, `invalid_schedule_time`, or `scenario_invalid_config` | Correct input/scenario; inspect `field_violations` for validation errors. | | `429 call_limit_exceeded` | Respect the per-number limit; backoff alone does not make another dial eligible. | | Other `429`, `500`, `502`, `503`, `504`, or a transport failure | Retry reads with bounded backoff; reconcile ambiguous writes before resubmitting. | `timeout_ms` sets a per-request HTTPX network timeout in milliseconds. Without an SDK setting, it inherits the HTTPX client's timeout: **5 seconds for clients created by the SDK**; supplied clients may differ. A method's non-null `timeout_ms` overrides the SDK setting; `None` inherits it. Set an explicit workload timeout. It does not bound total retries, call duration, or polling. HTTP retries are off by default. Enabled retries cover `429`, `500`, `502`, `503`, `504`; `retry_connection_errors=True` also covers HTTPX network errors and timeouts. Method `retries=` overrides client `retry_config=`; `retries=None` disables that method's retries. Configure reads individually: ```python theme={null} from sarj_platform_sdk import SDK from sarj_platform_sdk.utils import BackoffStrategy, RetryConfig with SDK(timeout_ms=10_000) as sdk: result = sdk.system.get_health( retries=RetryConfig( strategy="backoff", backoff=BackoffStrategy(500, 5_000, 2, 10_000), retry_connection_errors=True, ), ) print(result.data.status) ``` Backoff intervals and `max_elapsed_time` use milliseconds. The SDK honors positive `Retry-After`; otherwise it jitters exponential backoff. `max_elapsed_time` is checked after failed attempts, so a sleep or request can exceed it. Use an application deadline to bound total time. Immediate `create_call` requests have no documented idempotency guarantee. After a timeout or connection loss, the call may already be accepted; reconcile before resubmitting to avoid duplicate calls. HTTP retries and scheduled dial retries are separate. ## Resources * [API reference](/api-reference/overview) * [PyPI package](https://pypi.org/project/sarj-platform-sdk/) # Speech-to-Text Source: https://platform-docs.sarj.ai/speech-to-text Transcribe Arabic audio with Sarj STT. Sarj STT transcribes Arabic speech. Its file-transcription endpoint supports an OpenAI SDK-compatible request format. | Base URL | Model | | :- | :- | | `https://stt-rnnt-ar.sarj.ai/openai/v1` | `sarj-stt` | ## Transcribe audio Send `multipart/form-data` to `POST /audio/transcriptions` with your STT API key in the `Authorization` header. ```bash theme={null} curl --fail-with-body https://stt-rnnt-ar.sarj.ai/openai/v1/audio/transcriptions \ -H "Authorization: Bearer $SARJ_STT_API_KEY" \ -F "file=@recording.wav" \ -F "model=sarj-stt" \ -F "language=ar" \ -F "response_format=json" ``` ## Request parameters | Parameter | Description | | :- | :- | | `file` | Required. The audio file to transcribe. | | `model` | `sarj-stt`, the only supported model and the default. | | `language` | `ar` (Arabic), the supported value and the default. | | `response_format` | `json` (default), `text`, or `verbose_json`. | For predictable input quality, use mono PCM WAV at 16 kHz. Keep the recording clear and avoid clipping or background noise. ## Real-time streaming For live audio, connect to `wss://stt-rnnt-ar.sarj.ai/stream` with `Authorization: Bearer YOUR_STT_API_KEY` in the WebSocket handshake headers. This endpoint is separate from the `/openai/v1` HTTP base URL. 1. Send `{"sample_rate": 16000}` as JSON and wait for the `session_id` response. 2. Send mono, signed 16-bit little-endian PCM audio in binary frames, without a WAV header. Receive partial and final transcript events while sending audio. 3. Send `{"action": "end_stream"}` as JSON when finished. Continue reading final events until the server closes the connection. Transcript events contain `Transcript.Results`. Each result has `IsPartial` and an `Alternatives` array; the recognized text is in `Alternatives[0].Transcript` when an alternative is present. This WebSocket interface is not listed in the HTTP OpenAPI schema. For uploaded files, the separate `stream=true` form option returns transcription events over Server-Sent Events (SSE); it is not a live-audio upload interface. ## API schema See the [STT OpenAPI schema](https://stt-rnnt-ar.sarj.ai/openapi.json) for the full HTTP request and response schema, including the `stream` option for file transcription. ## File transcription response ```json theme={null} { "text": "يا مرحبا، كيف نقدر نساعدك اليوم؟" } ``` The API returns the transcription in the requested response format. The default response format is `json`. # Text-to-Speech Source: https://platform-docs.sarj.ai/text-to-speech Generate speech with Sarj TTS, choose a voice, and control its delivery. Sarj TTS converts text into speech using built-in voices or your own reference recording. The speech endpoint supports an OpenAI SDK-compatible request format. | Base URL | Model | | :- | :- | | `https://sarj-omni-tts.sarj.ai/v1` | `sarj-tts` | ## Generate speech Send a JSON request to `POST /audio/speech` with your TTS API key in the `Authorization` header. The response is binary audio. ```bash theme={null} curl --fail-with-body https://sarj-omni-tts.sarj.ai/v1/audio/speech \ -H "Authorization: Bearer $SARJ_TTS_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "sarj-tts", "voice": "ars_male", "input": "يا مرحبا، كيف نقدر نساعدك اليوم؟", "response_format": "wav" }' \ --output speech.wav ``` ## Voices and samples These five Saudi voices use the same sentence, generated with each voice's production defaults. يا مرحبا، تقدر تتابع طلبك من التطبيق، وإذا احتجت أي مساعدة حنا موجودين. قل لي وش تحتاج، ونرتبها لك خطوة بخطوة.