Guides

Directory sync

Poll an upstream Okta, Entra ID, Google Workspace or SCIM directory into ulex: connection setup, provider quirks, filters, attribute mapping, deprovisioning, sync-run state, and how to keep the MCP call budget under control.

Directory sync is the outbound direction: ulex polls someone else's directory and pulls users and groups into your tenant. SCIM provisioning (the inbound direction) is the other half.

#1. Register the directory

bash
curl -sS -X POST "$BASE/directories" \
  -H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
  -H "Idempotency-Key: 3c9d1f77-0b2e-4a58-9d61-5e7a2c40b913" \
  -d '{
    "name": "Acme (Okta)",
    "provider": "okta",
    "domain": "acme.example",
    "organization_id": "org_01M3PSV8HGTKQFCAYF9GDWGN3C",
    "scim_base_url": "https://acme.okta.com/scim/v2",
    "scim_token": "env:ULEX_TEST_OKTA_SCIM_TOKEN",
    "scim_poll_interval_seconds": 900,
    "user_filter": "active eq true",
    "group_filter": null,
    "deprovision_upstream_removals": true
  }'
json
{
  "id": "dir_01M3PSVBF8038RK2MW2N263Q2B",
  "object": "directory",
  "organization_id": "org_01M3PSV8HGTKQFCAYF9GDWGN3C",
  "name": "Acme (Okta)",
  "provider": "okta",
  "state": "active",
  "domain": "acme.example",
  "scim_base_url": "https://acme.okta.com/scim/v2",
  "inbound_scim_enabled": false,
  "scim_poll_interval_seconds": 900,
  "has_scim_token": true,
  "has_inbound_scim_token": false,
  "has_client_secret": false,
  "last_synced_at": null,
  "last_sync_status": "never",
  "last_sync_error": null
}
Warning

Use "scim_token": "env:ULEX_TEST_OKTA_SCIM_TOKEN" rather than a literal. ulex reads the value from its own environment at request time and stores only the ciphertext, so the secret never appears in the API surface, the audit log, or an agent's transcript.

#2. Providers

providerTransportNotes
oktaSCIM 2.0/Users and /Groups; honours userFilter and groupFilter; 1 s minimum between pages
entra_idMicrosoft Graph via SCIM bridgeuses externalId as the stable key; active arrives as a string
azure_adSCIM 2.0legacy alias for Entra
google_workspaceAdmin SDKpaginates with a page token; 300 s minimum interval; users arrive with external_id = the immutable Google user id
oneloginSCIM 2.0
jumpcloudSCIM 2.0
scim_genericSCIM 2.0any standards-compliant server; this is the right default if you are unsure
ulex_mockin-processsynthetic directory with deterministic data. No external dependency at all

ulex_mock is the one to use for tests. It produces a stable, known population so your fixtures do not depend on someone else's directory being reachable.

#3. Filters

json
{ "user_filter": "department eq \"Customer Success\" and active eq true" }
FilterEffect
user_filter: "active eq true"only current employees. Almost always what you want
user_filter: "userName sw \"ext-\""contractors only
group_filter: "displayName ne \"All Users\""skip the catch-all group
no filterthe whole directory, including service and disabled accounts
Warning

A missing user_filter can sync many accounts that do not need access. Pricing is usage-based, so filter to the users you intend to provision and avoid unnecessary data transfer. Resource counts are not plan quotas.

#4. Attribute mapping

json
{
  "attribute_mapping": {
    "email": "emails[type eq \"work\"].value",
    "first_name": "name.givenName",
    "last_name": "name.familyName",
    "display_name": "displayName",
    "job_title": "title",
    "department": "department",
    "external_id": "id"
  }
}

The defaults are already correct for a standards-compliant SCIM server. Override only where a provider deviates:

ProviderDeviationOverride
Entrano emails array; email is in userName or mail"email": "userName"
Entragroups are object idsnot mappable here; resolve in your app from the groups claim
Google Workspacedepartment is an org-unit path"department": "orgUnitPath" and flatten it yourself
Oktaid changes on re-importset external_id from a custom attribute, not id

external_id is the join key across syncs. If it changes, ulex creates a new user instead of updating the old one, and you end up with a duplicate. For Okta, use a custom attribute; for Google, the immutable user id is fine; for Entra, the objectId is fine.

#5. Run a sync

json
{ "name": "ulex_sync_directory", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B" } }
json
{
  "id": "job_01M3PSVQ68YGZREJKDVZSMQ64T",
  "object": "directory_sync",
  "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B",
  "state": "running",
  "trigger": "manual",
  "stats": { "users_created": 0, "users_updated": 0, "users_deactivated": 0, "users_failed": 0, "groups_synced": 0 },
  "error": null,
  "started_at": "2026-09-29T14:50:00.000Z",
  "finished_at": null
}

This call returns immediately. It is fire-and-forget. A 200 here does not mean the sync worked.

json
{ "name": "ulex_get_sync_status", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B", "sync_id": "job_01M3PSVQ68YGZREJKDVZSMQ64T" } }
json
{
  "id": "job_01M3PSVQ68YGZREJKDVZSMQ64T",
  "object": "directory_sync",
  "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B",
  "state": "succeeded",
  "trigger": "manual",
  "stats": { "users_created": 12, "users_updated": 3, "users_deactivated": 1, "users_failed": 0, "groups_synced": 4 },
  "error": null,
  "started_at": "2026-09-29T14:50:00.000Z",
  "finished_at": "2026-09-29T14:50:04.000Z"
}
stateMeaningWhat to do
pendingqueuedpoll
runningin progresspoll every 2 s
succeededeverything workedread stats
partialsome users failedread error and stats.users_failed; do not treat this as success
failedcould not completeread error; usually credentials or filter syntax
cancelledstoppedre-trigger
ts
export async function syncAndWait(directoryId: string, timeoutMs = 120_000) {
  const { id: syncId } = await tools.ulex_sync_directory({ directory_id: directoryId });
  const deadline = Date.now() + timeoutMs;
  for (;;) {
    await new Promise((r) => setTimeout(r, 2000));
    const run = await tools.ulex_get_sync_status({ directory_id: directoryId, sync_id: syncId });
    if (run.state === "succeeded" || run.state === "partial" || run.state === "failed") {
      if (run.state !== "succeeded") {
        throw new Error(`sync ${syncId} ${run.state}: ${run.error} (${run.stats.users_failed} users failed)`);
      }
      return run;
    }
    if (Date.now() > deadline) throw new Error(`sync ${syncId} timed out in state ${run.state}`);
  }
}

partial throws. A directory that is 97% synced is a directory where three people cannot log in, and that is a support ticket, not a success.

#6. What a sync does per user

SituationActionEmittedstats
external_id or email unknowncreate the user and a member membershipdsync.user.created, user.createdusers_created
Known, attributes differupdate the changed fieldsdsync.user.updated, user.updatedusers_updated
Known, active: false upstreamsuspend, revoke sessionsdsync.user.updated, user.suspendedusers_deactivated
Missing upstream, deprovision_upstream_removals: truesuspend, revoke sessionsdsync.user.deleted, user.deleted, user.suspendedusers_deactivated
Unparseable recordskip and count—users_failed

Deprovisioning is suspend, never delete. The record is retained for the audit trail, the user is immediately locked out, and it is reversible. Full hard deletion is a tenant retention decision, not a sync decision.

Users the directory owns are found at GET /directories/{id}/users; it is the directory_id-scoped view of GET /users.

#7. Schedule and triggers

triggerWhen
scheduledevery scim_poll_interval_seconds (60–86,400; default 900, the RFC 7644 §3.1 recommendation)
manualulex_sync_directory
webhooka POST from the customer's system, via a scim_push connection
scim_pusha scim strategy connection whose upstream pushes rather than ulex polling
bash
curl -sS -X PATCH "$BASE/directories/dir_01M3PSVBF8038RK2MW2N263Q2B" \
  -H "Authorization: Bearer $ULEX_API_KEY" -H "Content-Type: application/json" \
  -d '{"scim_poll_interval_seconds": 3600}'

The upstream must tolerate your poll rate. Okta rate-limits per token; 900 seconds is safe for everyone. Going faster gets you 429 from the customer, not from ulex.

#8. Keeping the call budget sane

A 500-user directory synced naively at five MCP calls per user is 2,500 calls — over four times the 600/minute tenant budget.

NaiveBatched
ulex_create_user × 5005 × POST /scim/v2/Bulk with 100 operations each
ulex_add_organization_member × 5003 × ulex_list_users({ organization_id, limit: 200 })
Poll sync status every 500 msevery 2 s, or subscribe to the dsync.* webhooks
ulex_simulate_login per assertionulex_mint_access_token when you only need a valid token
json
{ "name": "ulex_get_usage", "arguments": {} }
json
{
  "usage": { "organizations": 2, "users": 37, "connections": 2, "active_deployments": 0 },
  "plan_limits_enforced": false
}

#9. Verifying

bash
curl -sS -G "$BASE/directories/dir_01M3PSVBF8038RK2MW2N263Q2B/users" \
  -H "Authorization: Bearer $ULEX_API_KEY" --data-urlencode 'limit=5' | jq '.data[] | {email, status, external_id, job_title}'

curl -sS -G "$BASE/directories/dir_01M3PSVBF8038RK2MW2N263Q2B/syncs?limit=5" \
  -H "Authorization: Bearer $ULEX_API_KEY" | jq '.data[] | {state, trigger, stats, error}'

curl -sS -G "$BASE/audit-events" -H "Authorization: Bearer $ULEX_API_KEY" \
  --data-urlencode 'action_prefix=directory.' --data-urlencode 'limit=10' | jq '.data[] | {action, outcome, error_code}'

Healthy looks like:

text
directory.sync_started   success
directory.sync_completed success

A directory.sync_failed in the audit log means a scheduled run failed without anyone watching. Subscribe to it.

#10. Troubleshooting

SymptomCauseFix
state: failed, error: "401" from upstreamwrong or expired scim_tokenPATCH /directories/{id} with a new one, using env:
state: failed, 400 invalidFilteruser_filter is not valid SCIM filteringvalidate it against GET {scim_base_url}/Users?filter=… yourself
users_created grows every runexternal_id changed, or user_filter excludes the filter attributepin external_id; check the filter does not filter on a mutated field
Duplicates on every runsame person with two emails, or two directory entriesreconcile on email, quarantine the loser
users_deactivated every run, users_created toomembership flaps because active is compared as a stringset active_value for a saml connection, or normalise in a scim connection's mapping
Timeout against a large directory12,000 users at 1,000 per pollnarrow user_filter; do not raise scim_max_users_per_poll past what the upstream tolerates
Upstream 429spolling too fastraise scim_poll_interval_seconds
directory_not_synced on a readyou read before the first run finishedtrigger a sync and wait for a terminal state

#Reference