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
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
}'{
"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
}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
provider | Transport | Notes |
|---|---|---|
okta | SCIM 2.0 | /Users and /Groups; honours userFilter and groupFilter; 1 s minimum between pages |
entra_id | Microsoft Graph via SCIM bridge | uses externalId as the stable key; active arrives as a string |
azure_ad | SCIM 2.0 | legacy alias for Entra |
google_workspace | Admin SDK | paginates with a page token; 300 s minimum interval; users arrive with external_id = the immutable Google user id |
onelogin | SCIM 2.0 | |
jumpcloud | SCIM 2.0 | |
scim_generic | SCIM 2.0 | any standards-compliant server; this is the right default if you are unsure |
ulex_mock | in-process | synthetic 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
{ "user_filter": "department eq \"Customer Success\" and active eq true" }| Filter | Effect |
|---|---|
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 filter | the whole directory, including service and disabled accounts |
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
{
"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:
| Provider | Deviation | Override |
|---|---|---|
| Entra | no emails array; email is in userName or mail | "email": "userName" |
| Entra | groups are object ids | not mappable here; resolve in your app from the groups claim |
| Google Workspace | department is an org-unit path | "department": "orgUnitPath" and flatten it yourself |
| Okta | id changes on re-import | set 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
{ "name": "ulex_sync_directory", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B" } }{
"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.
{ "name": "ulex_get_sync_status", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B", "sync_id": "job_01M3PSVQ68YGZREJKDVZSMQ64T" } }{
"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"
}state | Meaning | What to do |
|---|---|---|
pending | queued | poll |
running | in progress | poll every 2 s |
succeeded | everything worked | read stats |
partial | some users failed | read error and stats.users_failed; do not treat this as success |
failed | could not complete | read error; usually credentials or filter syntax |
cancelled | stopped | re-trigger |
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
| Situation | Action | Emitted | stats |
|---|---|---|---|
external_id or email unknown | create the user and a member membership | dsync.user.created, user.created | users_created |
| Known, attributes differ | update the changed fields | dsync.user.updated, user.updated | users_updated |
Known, active: false upstream | suspend, revoke sessions | dsync.user.updated, user.suspended | users_deactivated |
Missing upstream, deprovision_upstream_removals: true | suspend, revoke sessions | dsync.user.deleted, user.deleted, user.suspended | users_deactivated |
| Unparseable record | skip 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
trigger | When |
|---|---|
scheduled | every scim_poll_interval_seconds (60–86,400; default 900, the RFC 7644 §3.1 recommendation) |
manual | ulex_sync_directory |
webhook | a POST from the customer's system, via a scim_push connection |
scim_push | a scim strategy connection whose upstream pushes rather than ulex polling |
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.
| Naive | Batched |
|---|---|
ulex_create_user × 500 | 5 × POST /scim/v2/Bulk with 100 operations each |
ulex_add_organization_member × 500 | 3 × ulex_list_users({ organization_id, limit: 200 }) |
| Poll sync status every 500 ms | every 2 s, or subscribe to the dsync.* webhooks |
ulex_simulate_login per assertion | ulex_mint_access_token when you only need a valid token |
{ "name": "ulex_get_usage", "arguments": {} }{
"usage": { "organizations": 2, "users": 37, "connections": 2, "active_deployments": 0 },
"plan_limits_enforced": false
}#9. Verifying
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:
directory.sync_started success
directory.sync_completed successA directory.sync_failed in the audit log means a scheduled run failed without anyone watching. Subscribe to it.
#10. Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
state: failed, error: "401" from upstream | wrong or expired scim_token | PATCH /directories/{id} with a new one, using env: |
state: failed, 400 invalidFilter | user_filter is not valid SCIM filtering | validate it against GET {scim_base_url}/Users?filter=… yourself |
users_created grows every run | external_id changed, or user_filter excludes the filter attribute | pin external_id; check the filter does not filter on a mutated field |
| Duplicates on every run | same person with two emails, or two directory entries | reconcile on email, quarantine the loser |
users_deactivated every run, users_created too | membership flaps because active is compared as a string | set active_value for a saml connection, or normalise in a scim connection's mapping |
| Timeout against a large directory | 12,000 users at 1,000 per poll | narrow user_filter; do not raise scim_max_users_per_poll past what the upstream tolerates |
| Upstream 429s | polling too fast | raise scim_poll_interval_seconds |
directory_not_synced on a read | you read before the first run finished | trigger a sync and wait for a terminal state |