Agent manual
The operating manual for agents using ulex: ten rules, scope selection, error and retry semantics, idempotency, cursor pagination, rate limits, when to use mock_sso versus a real strategy, the get-a-token-in-three-calls recipe, and a full end-to-end build-and-report recipe.
You are reading this because you are about to call ulex tools. This page is the contract. Everything else in the docs is reference material you should look up when this page says to.
#Ten rules
- Never pass a secret as a tool argument. API keys come from the
ULEX_API_KEYenvironment variable or the OAuth 2.1 protected-resource flow. A key inside an argument lands in the audit log, in your transcript, and in your vendor's logs. - Never pass
environment. It is derived from the credential. A tool that takes one is a bug — reject it. - Read
retryable, not the HTTP status.retryable: truemeans back off and retry the identical request.retryable: falsemeans the request is wrong; retrying it will never work. This single field replaces all retry heuristics. - Always send
Idempotency-Keyon a POST that creates. A 500 after a successful create is normal. Without the key you will duplicate users; with it you get the original back. - Prefer
ulex_bootstrap_appover assembling primitives. It is idempotent on(application_name, organization_domain)and it is the only path that gets themock_ssoseed users right. - Prefer
ulex_simulate_loginover driving/oauth2/authorizeyourself. It runs the same transaction server-side, produces a real grant, and hands back a real code. There is no browser. - Paginate until
has_moreisfalse. Do not guess a count, do not stop at the first page, do not readnext_cursorand then re-derive it. It is an opaque resource id; pass it straight back asstarting_after. - Create then activate.
POST /connectionsreturnsstate: "draft". Untilstate === "active", every login on that connection fails withconnection_not_active. - Rotate with overlap, never in place.
POST /applications/{id}/rotate-secretandPOST /tenants/current/rotate-signing-keysboth have a grace window. Use it. See Zero-downtime rotation. - Report the audit trail, not your intentions. After a build, call
ulex_search_audit_logsfiltered on your ownrequest_idand quote it. That is the deliverable.
#Choosing a connection strategy
config.strategy is the discriminator. Eighteen values. You need three of them.
| Strategy | Use it when | External setup | Use mock instead |
|---|---|---|---|
mock_sso | Default for all agent work. Any login test, demo, fixture, or e2e run. | none | — |
oidc | Wiring a real upstream IdP you control and can point at a URL | discovery document | — |
google_oidc | You want Google's exact claim shape and issuer quirks | Google Cloud project | oidc with issuer: https://accounts.google.com |
okta_oidc | Reproducing an Okta tenant's behaviour | Okta tenant | oidc with a fixture discovery doc |
saml | The customer has a SAML IdP and you need SP metadata, ACS, SLO | upstream cert + SSO URL | the built-in fixture IdP via POST /connections/{id}/saml/sso |
scim / directory_sync | Provisioning customers from a directory | SCIM base URL + token | ulex_mock provider |
password | Legacy LDAP/AD bind flows | bind DN | mock_sso |
impersonation_only | Test-only: log in as a user with no credential at all | none | never ship this |
impersonation_only and sso:impersonate exist for tests. Both require the ulex:admin scope. Both write an impersonation.started audit event. Both are rejected on the hosted control plane unless tenant.allow_mocks is true on a non-HIPAA tenant (or when running locally via npx @ulexid/mcp-server).
The rule of thumb: if you cannot describe the upstream IdP's issuer URL, you do not need a real strategy. mock_sso is not a stub — it produces genuine sessions, genuine grants, genuine RS256 JWTs, genuine SCIM provisioning, and genuine audit events.
#Scopes
Request the narrowest set that works. Scopes live on the API key and on the OAuth grant.
| Scope | Grants | Typical agent use |
|---|---|---|
mcp:tools | every read-only MCP tool | almost always include this |
mcp:admin | destructive MCP tools: ulex_reset_tenant, ulex_delete_* | only for teardown scripts |
ulex:admin | everything, including impersonation and key rotation | bootstrap / CI only |
read:organizations write:organizations | organization CRUD + domains + members | multi-tenant work |
read:users write:users | user CRUD + suspend/unsuspend | JIT provisioning |
read:groups write:groups | group CRUD + membership | role mapping |
read:connections write:connections | connection CRUD + activate + verify | SSO wiring |
read:directories write:directories | directory CRUD + sync | SCIM lifecycle |
read:applications write:applications | application CRUD + secret rotation | client setup |
read:webhooks write:webhooks | webhook CRUD + test | event pipelines |
read:audit_logs | GET /audit-events* | self-auditing |
read:deployments write:deployments | deployment lifecycle | delivery receipts |
scim:provision | inbound /scim/v2 writes | directory simulators |
saml:consume | SAML ACS consumption | SP integration tests |
sso:impersonate | impersonation_only connections | error-path tests |
openid profile email offline_access | end-user OIDC claims and refresh | user-facing apps |
ulex:admin, mcp:admin, and sso:impersonate are admin-only. A non-admin key carrying them is rejected at mint time, not at call time.
Recommended bootstrap key scopes: ["mcp:tools", "read:organizations", "write:organizations", "read:users", "write:users", "read:groups", "write:groups", "read:applications", "write:applications", "read:connections", "write:connections", "read:audit_logs"].
#Errors: the one grammar
Every surface — REST, MCP, CLI, webhooks — returns the same object.
{
"error": {
"type": "conflict_error",
"code": "resource_exists",
"message": "A organization with that slug already exists.",
"param": "slug",
"request_id": "req_01M3PSW9R0175NAW62NYR403R8",
"retryable": false,
"docs_url": "https://docs.ulexid.com/api-reference/errors",
"hint": "Reuse the existing organization id, or choose a different slug."
}
}type | Status | Meaning | Retry? |
|---|---|---|---|
invalid_request_error | 400 | The request is malformed. | never |
authentication_error | 401 | Credential missing, wrong, expired, revoked. | never |
permission_error | 403 | Authenticated but not allowed. | never |
not_found_error | 404 | No such resource in this tenant. | never |
conflict_error | 409 | State conflict: exists, immutable, bad transition. | never |
rate_limited | 429 | Per-IP request rate limit. | honor Retry-After |
api_error | 500 | Our fault. | yes |
Status overrides that matter: domain_not_verified → 412, scim_bulk_exceeded → 413, service_unavailable → 503, timeout → 504, saml_clock_skew → 400.
#The backoff algorithm
attempt = 0
loop:
result = call(request)
if result is not an error envelope: return result
if result.error.retryable is false: return result # give up, fix the request
attempt += 1
if attempt > 5: return result # surface it, do not spin
if result.status == 429:
wait = parse_int(response.headers["Retry-After"]) ?? 1
else if attempt == 1 or attempt == 2:
wait = 0.5 * attempt
else:
wait = 2 ** (attempt - 2) # 2s, 4s, 8s, 16s
sleep(wait)Cap total retry time at 30 seconds. If a 5xx persists past 5 attempts, call ulex_get_status, then ulex_explain_error with the code, and report both to the user rather than retrying further.
retryable is a closed set: internal_error, service_unavailable, timeout, webhook_delivery_failed, deployment_failed, scim_bulk_failed. A 429 from the request shield is handled by Retry-After.
#Idempotency
Send Idempotency-Key: <uuid v4> on every POST that creates a resource. ulex stores the key with the response for 24 hours and replays the original response byte-for-byte on a repeat.
| Situation | Without a key | With a key |
|---|---|---|
POST /users returns 500 after writing | duplicate user on retry | original user returned |
POST /organizations run twice | 409 resource_exists | same org returned |
POST /webhooks retried | two endpoints, double events | one endpoint |
POST /deployments retried | two deployments, two app versions | one deployment |
The key is scoped to (tenant_id, method, path, key). The same key on a different path is a different key. Idempotency-Key and X-Ulex-Request-Id are different things: the first deduplicates, the second is a correlation label that appears in the audit log. Use both, different values.
MCP tools that create resources accept an idempotency_key argument with the same semantics. ulex_bootstrap_app is additionally naturally idempotent on (application_name, organization_domain).
#Pagination
Every list endpoint uses opaque cursor pagination. The shape is identical everywhere.
{
"object": "list",
"data": [ /* … */ ],
"first_id": "usr_01M3PSV9GRT8GQGEG686AR1W9S",
"last_id": "usr_01M3PSWBPGS08FWV4NV7P9VNFN",
"has_more": true,
"next_cursor": "usr_01M3PSWBPGS08FWV4NV7P9VNFN"
}page 1: GET /users?limit=100
page 2: GET /users?limit=100&starting_after=usr_01M3PSWBPGS08FWV4NV7P9VNFN
page 3: GET /users?limit=100&starting_after=<next_cursor from page 2>
stop when has_more == falselimitis 1–200, default 20.starting_afteris a resource id.ending_beforepages backwards.orderisascordesc, defaultasc.- Ids are ULIDs, so
ascis creation order anddescis reverse-creation order. Sort by timestamp in your own head, not by the id string. next_cursorisnullexactly whenhas_moreisfalse. Do not compute one; do not decode one.- In MCP, the same parameters exist.
ulex_list_usersreturns{ "data": [...], "has_more": false, "next_cursor": null }with the same field names.
#Rate limits
| Bucket | Limit | Where it shows up |
|---|---|---|
| General routes (including REST, MCP, SCIM, SAML) | 600 sustained/minute, 1,200 burst per source IP and Lambda container | too_many_requests, 429 |
| Authentication/token routes | 60 sustained/minute, 120 burst per source IP and Lambda container | too_many_requests, 429 |
Every shield 429 carries a Retry-After header. Honor it, adding jitter when several clients retry together.
The shield does not emit remaining-budget headers on successful responses. Pricing is usage-based; tenant resource counts are not plan limits.
#Get a token in three calls
The minimum viable path from "I have an API key" to "I have a user access token". No browser, no code_verifier guesswork.
1. ulex_simulate_login { application_id, email }
→ { session_id, grant_id, code, authorization_url, code_expires_at }
2. ulex_exchange_code_for_tokens { application_id, client_secret, code, redirect_uri, code_verifier }
→ { access_token, refresh_token, id_token, expires_in }
3. ulex_introspect_token { token }
→ { active: true, sub, org_id, sid, scope, exp }Call 1 details that matter:
ulex_simulate_logingenerates the PKCEcode_challengeandcode_verifierfor you and returns the plaintextcode_verifierincode_verifier_hintonly when you passreturn_pkce: true. Pass that same value to call 2.- If you pass
return_pkce: false(the default), use the fixed test vector from RFC 7636 Appendix B:code_verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk",code_challenge = "E9MelhoQ2YvW96fl8sW7aTtZbGd0mY6Xl0e8Q1sCk". These are hard-wired formock_ssoconnections so agents never have to implement base64url-SHA256 correctly on the first try. code_expires_atis 60 seconds out. If you sleep, callulex_simulate_loginagain — never reuse a code. A reused code returnsinvalid_grantwithretryable: falsebecause the grant is genuinely consumed; the correct response is a new login, not a retry.
Call 2 details that matter:
redirect_urimust byte-for-byte match one of the application'sredirect_uris. Mismatch returnsinvalid_redirect_uri(400, not retryable).client_secretis required unless the application hastoken_endpoint_auth_method: "none"or you usedprivate_key_jwt.- The response
access_tokenis a real RS256 JWT. Decode the payload forsub,org_id,sid,scope,amr. Do not call/userinfoin a test — you already have the claims.
Call 3 details that matter:
- Introspection tells you whether the token is currently valid, which is different from whether it decodes. Use it to assert revocation in a test.
Token lifetimes in the simulator: access 3600s, refresh 2592000s (30d, rotating, replay kills the family), authorization code 60s, session idle 604800s, session absolute 86400s.
#End-to-end recipe: "build me an app with SSO and report status"
This is the task, verbatim. Here is the minimal correct execution.
{ "name": "ulex_bootstrap_app", "arguments": {
"application_name": "Acme Support",
"organization_name": "Acme Corp",
"organization_domain": "acme.example",
"admin_email": "dana@acme.example",
"connection_strategy": "mock_sso",
"create_scim_directory": true
} }Record: application.id, client_id, client_secret, organization.id, connection.id, user.id, scim_bearer_token.
ulex_simulate_login → ulex_exchange_code_for_tokens → ulex_introspect_token.
Assert: active === true, sub === user.id, org_id === organization.id, scope contains openid.
{ "name": "ulex_simulate_failure", "arguments": {
"application_id": "app_01M3PSV7J8TBSPHG95CYSEX32B",
"email": "dana@acme.example",
"mode": "mfa_required"
} }Then ulex_simulate_mfa with action: "satisfy". Assert the first attempt returns mfa_required (401, retryable: false) and that satisfying it produces a token with amr containing mfa.
curl -sS -X POST "$BASE/scim/v2/Users" \
-H "Authorization: Bearer $SCIM_BEARER_TOKEN" -H "$JSON" \
-d '{"schemas":["urn:ietf:params:scim:schemas:core:2.0:User"],
"userName":"pat@acme.example",
"name":{"givenName":"Pat","familyName":"Iyer"},
"emails":[{"value":"pat@acme.example","primary":true}],
"active":true}'{ "name": "ulex_sync_directory", "arguments": { "directory_id": "dir_01M3PSVBF8038RK2MW2N263Q2B" } }Then ulex_get_sync_status until state is succeeded or partial. Assert usr_... for Pat now exists and is a member of the org.
ulex_deploy with application_id, then poll ulex_get_deployment until state is succeeded or failed. On failed, read error.code and call ulex_explain_error.
{ "name": "ulex_search_audit_logs", "arguments": {
"action_prefix": "authentication.",
"limit": 50,
"order": "desc"
} }Report a table: timestamp, action, outcome, actor_type, target.id, request_id. Quote real ids. If any outcome is denied or failure, say so — a green report that hides a failed assertion is worse than a red one.
Total: 11 tool calls. Report in under 200 words, table-first, no preamble.
#Things that will silently cost you a run
| Mistake | Symptom | Prevention |
|---|---|---|
| Never activating the connection | every login 401s with connection_not_active | check state === "active" before testing |
redirect_uri off by a trailing slash | invalid_redirect_uri | copy the exact string from redirect_uris |
| Exchanging a code twice | invalid_grant, retryable: false | read code_expires_at; re-login instead of retrying |
Passing environment to a tool | unknown_parameter | delete it; it is derived |
Assuming email is unique globally | two orgs, one human — this is correct | users are tenant-global; scope with memberships |
| Paginating to page 1 twice | duplicate processing | starting_after, not offset |
Expecting an sso_only org to allow password sign-in | access_denied, sso_required | sso_only is enforced: users must authenticate via an enterprise connection permitted by the org |
Calling /userinfo with a refresh token | invalid_token | refresh tokens only go to /oauth2/token |
Expecting client_secret twice | null | it is returned once; store it |
| Retrying a 409 | infinite loop | retryable: false means stop |
#Declared fields that are not enforced yet
Some configuration fields are declared in the schemas, settable, and returned on every read, while the server does not consult them yet. Full table, and what each does when it lands: Capability status.
| Field | Set where | Today |
|---|---|---|
application.sign_up_enabled, sign_in_with_email_enabled, organization_usage, grant_access_to_organization, cross_app_sso_redirect_urls, branding, default_locale | ulex_update_application | declared, not enforced yet: no effect |
ulex_get_auth_policy returns not_enforced, naming these, on every call — so you do not have to remember this list.
If your plan depends on one, it depends on a capability that has not been built. The boundaries ulex does enforce are tenant isolation, role checks on the API, and cross_app_sso / blocked_ip_ranges from the authentication policy.
#What ulex is not
Be honest about this in any deliverable:
- It does not authenticate real humans. There is no real identity source behind
mock_sso. - It does not issue certificates, does not run a real CA, and does not sign SAML assertions with a CA-issued key.
- It does not perform real email delivery.
magic_linkandotp_emailstrategies generate codes and return them in the API response instead of sending mail. - It does not run your application's code during
ulex_deploy. It models the lifecycle, produces realistic logs, and hands you credentials. - It is not a production identity provider, and it has not been penetration tested against a live adversary.
Full posture: SOC 2, HIPAA, compliance matrix.
#Next
- MCP tools reference — one row per tool.
- Patterns — eight copy-paste recipes.
- Errors — every code, cause, and fix.