Agents

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

  1. Never pass a secret as a tool argument. API keys come from the ULEX_API_KEY environment 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.
  2. Never pass environment. It is derived from the credential. A tool that takes one is a bug — reject it.
  3. Read retryable, not the HTTP status. retryable: true means back off and retry the identical request. retryable: false means the request is wrong; retrying it will never work. This single field replaces all retry heuristics.
  4. Always send Idempotency-Key on 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.
  5. Prefer ulex_bootstrap_app over assembling primitives. It is idempotent on (application_name, organization_domain) and it is the only path that gets the mock_sso seed users right.
  6. Prefer ulex_simulate_login over driving /oauth2/authorize yourself. It runs the same transaction server-side, produces a real grant, and hands back a real code. There is no browser.
  7. Paginate until has_more is false. Do not guess a count, do not stop at the first page, do not read next_cursor and then re-derive it. It is an opaque resource id; pass it straight back as starting_after.
  8. Create then activate. POST /connections returns state: "draft". Until state === "active", every login on that connection fails with connection_not_active.
  9. Rotate with overlap, never in place. POST /applications/{id}/rotate-secret and POST /tenants/current/rotate-signing-keys both have a grace window. Use it. See Zero-downtime rotation.
  10. Report the audit trail, not your intentions. After a build, call ulex_search_audit_logs filtered on your own request_id and quote it. That is the deliverable.

#Choosing a connection strategy

config.strategy is the discriminator. Eighteen values. You need three of them.

StrategyUse it whenExternal setupUse mock instead
mock_ssoDefault for all agent work. Any login test, demo, fixture, or e2e run.none—
oidcWiring a real upstream IdP you control and can point at a URLdiscovery document—
google_oidcYou want Google's exact claim shape and issuer quirksGoogle Cloud projectoidc with issuer: https://accounts.google.com
okta_oidcReproducing an Okta tenant's behaviourOkta tenantoidc with a fixture discovery doc
samlThe customer has a SAML IdP and you need SP metadata, ACS, SLOupstream cert + SSO URLthe built-in fixture IdP via POST /connections/{id}/saml/sso
scim / directory_syncProvisioning customers from a directorySCIM base URL + tokenulex_mock provider
passwordLegacy LDAP/AD bind flowsbind DNmock_sso
impersonation_onlyTest-only: log in as a user with no credential at allnonenever ship this
Warning

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.

ScopeGrantsTypical agent use
mcp:toolsevery read-only MCP toolalmost always include this
mcp:admindestructive MCP tools: ulex_reset_tenant, ulex_delete_*only for teardown scripts
ulex:admineverything, including impersonation and key rotationbootstrap / CI only
read:organizations write:organizationsorganization CRUD + domains + membersmulti-tenant work
read:users write:usersuser CRUD + suspend/unsuspendJIT provisioning
read:groups write:groupsgroup CRUD + membershiprole mapping
read:connections write:connectionsconnection CRUD + activate + verifySSO wiring
read:directories write:directoriesdirectory CRUD + syncSCIM lifecycle
read:applications write:applicationsapplication CRUD + secret rotationclient setup
read:webhooks write:webhookswebhook CRUD + testevent pipelines
read:audit_logsGET /audit-events*self-auditing
read:deployments write:deploymentsdeployment lifecycledelivery receipts
scim:provisioninbound /scim/v2 writesdirectory simulators
saml:consumeSAML ACS consumptionSP integration tests
sso:impersonateimpersonation_only connectionserror-path tests
openid profile email offline_accessend-user OIDC claims and refreshuser-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.

json
{
  "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."
  }
}
typeStatusMeaningRetry?
invalid_request_error400The request is malformed.never
authentication_error401Credential missing, wrong, expired, revoked.never
permission_error403Authenticated but not allowed.never
not_found_error404No such resource in this tenant.never
conflict_error409State conflict: exists, immutable, bad transition.never
rate_limited429Per-IP request rate limit.honor Retry-After
api_error500Our 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

text
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.

SituationWithout a keyWith a key
POST /users returns 500 after writingduplicate user on retryoriginal user returned
POST /organizations run twice409 resource_existssame org returned
POST /webhooks retriedtwo endpoints, double eventsone endpoint
POST /deployments retriedtwo deployments, two app versionsone 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.

json
{
  "object": "list",
  "data": [ /* … */ ],
  "first_id": "usr_01M3PSV9GRT8GQGEG686AR1W9S",
  "last_id": "usr_01M3PSWBPGS08FWV4NV7P9VNFN",
  "has_more": true,
  "next_cursor": "usr_01M3PSWBPGS08FWV4NV7P9VNFN"
}
text
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 == false
  • limit is 1–200, default 20.
  • starting_after is a resource id. ending_before pages backwards. order is asc or desc, default asc.
  • Ids are ULIDs, so asc is creation order and desc is reverse-creation order. Sort by timestamp in your own head, not by the id string.
  • next_cursor is null exactly when has_more is false. Do not compute one; do not decode one.
  • In MCP, the same parameters exist. ulex_list_users returns { "data": [...], "has_more": false, "next_cursor": null } with the same field names.

#Rate limits

BucketLimitWhere it shows up
General routes (including REST, MCP, SCIM, SAML)600 sustained/minute, 1,200 burst per source IP and Lambda containertoo_many_requests, 429
Authentication/token routes60 sustained/minute, 120 burst per source IP and Lambda containertoo_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.

text
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_login generates the PKCE code_challenge and code_verifier for you and returns the plaintext code_verifier in code_verifier_hint only when you pass return_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 for mock_sso connections so agents never have to implement base64url-SHA256 correctly on the first try.
  • code_expires_at is 60 seconds out. If you sleep, call ulex_simulate_login again — never reuse a code. A reused code returns invalid_grant with retryable: false because the grant is genuinely consumed; the correct response is a new login, not a retry.

Call 2 details that matter:

  • redirect_uri must byte-for-byte match one of the application's redirect_uris. Mismatch returns invalid_redirect_uri (400, not retryable).
  • client_secret is required unless the application has token_endpoint_auth_method: "none" or you used private_key_jwt.
  • The response access_token is a real RS256 JWT. Decode the payload for sub, org_id, sid, scope, amr. Do not call /userinfo in 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.

1
1 — Provision (1 call)
json
{ "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.

2
2 — Prove SSO works end to end (3 calls)

ulex_simulate_login → ulex_exchange_code_for_tokens → ulex_introspect_token.

Assert: active === true, sub === user.id, org_id === organization.id, scope contains openid.

3
3 — Prove the unhappy path (2 calls)
json
{ "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.

4
4 — Prove provisioning (2 calls)
bash
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}'
json
{ "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.

5
5 — Deliver (2 calls)

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.

6
6 — Report (1 call)
json
{ "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

MistakeSymptomPrevention
Never activating the connectionevery login 401s with connection_not_activecheck state === "active" before testing
redirect_uri off by a trailing slashinvalid_redirect_uricopy the exact string from redirect_uris
Exchanging a code twiceinvalid_grant, retryable: falseread code_expires_at; re-login instead of retrying
Passing environment to a toolunknown_parameterdelete it; it is derived
Assuming email is unique globallytwo orgs, one human — this is correctusers are tenant-global; scope with memberships
Paginating to page 1 twiceduplicate processingstarting_after, not offset
Expecting an sso_only org to allow password sign-inaccess_denied, sso_requiredsso_only is enforced: users must authenticate via an enterprise connection permitted by the org
Calling /userinfo with a refresh tokeninvalid_tokenrefresh tokens only go to /oauth2/token
Expecting client_secret twicenullit is returned once; store it
Retrying a 409infinite loopretryable: 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.

FieldSet whereToday
application.sign_up_enabled, sign_in_with_email_enabled, organization_usage, grant_access_to_organization, cross_app_sso_redirect_urls, branding, default_localeulex_update_applicationdeclared, 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_link and otp_email strategies 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