# Get Agent Counts Source: https://docs.barndoor.ai/api-reference/agents/counts/getAgentCounts GET /api/agents/counts Get counts of agents grouped by type (internal vs external). # Delete Agent by Id Source: https://docs.barndoor.ai/api-reference/agents/deleteAgent DELETE /api/agents/{agent_id} Unregister an agent from Barndoor. This removes the agent's registration but does not delete the underlying application directory. The agent can be re-registered using the same application_directory_id. # GET Agent by Id Source: https://docs.barndoor.ai/api-reference/agents/getAgent GET /api/agents/{agent_id} Get details of a specific agent by ID, including its application directory configuration. # List Agents Source: https://docs.barndoor.ai/api-reference/agents/listAgents GET /api/agents List registered agents with pagination. # Register Agent Source: https://docs.barndoor.ai/api-reference/agents/registerAgent POST /api/agents Register a new agent with Barndoor. Agents represent AI applications that can access MCP servers through Barndoor. Each agent must be associated with an application directory (OAuth client configuration). # Delete connection Source: https://docs.barndoor.ai/api-reference/connections/deleteConnection DELETE /api/servers/{server_id}/connection Delete the current user's connection to this server. This will remove the connection record and clean up any stored OAuth credentials. The user will need to reconnect to use this server again. # Get Connection Status Source: https://docs.barndoor.ai/api-reference/connections/getConnectionStatus GET /api/servers/{server_id}/connection Get the user's connection status for a specific server. Used to poll connection status during OAuth flows. # Initiate OAuth connection Source: https://docs.barndoor.ai/api-reference/connections/initiateConnection POST /api/servers/{server_id}/connect Initiate OAuth connection flow for a server. Returns an authorization URL that the user should visit to complete the OAuth flow. The server must have OAuth configuration set up by an admin. # List Server Connections Source: https://docs.barndoor.ai/api-reference/connections/listServerConnections GET /api/registry/v1/servers/{server_id}/connections List who in the organization holds a connection to this MCP server — the inverse of the caller-scoped connection endpoints, which only ever return your own connection. Requires organization **admin**. The response discloses which members use which server, so it is not available to regular members. This reads *current* connection state, so a member who has already migrated and disconnected is simply absent. Use it when retiring or replacing a connector and you need to know who to tell. Audit logs answer a different question — who *used* a connector inside the retention window — so they both miss people who connected but never used it and keep listing people who already moved on. ### Owner classes Every owner class is returned by default: people (`user_id` set), AI agents (`application_id` set), and the tenant service account (neither set). An agent still bound to a server you are retiring blocks the migration just as much as a person does. Narrow with `owner=user` when you specifically want a list of people to notify. ### Resolving `user_id` `user_id` is the external IdP subject. Resolve names and email addresses by joining against the identity users API — but you must **include deactivated members**. Deactivating a member does not remove their connection row, so an active-only user list silently drops people who still hold a connection to the server you are retiring. A `user_id` that resolves nowhere belongs to a member already deleted from identity whose connection row outlived them. Surface those for manual follow-up; do not drop them from the count. ### Interpreting `status` `error` is a positive dead-credential signal for OAuth connectors, which a keepalive sweep refreshes on a few-hour cycle, flipping any credential it cannot refresh to `error`. `connected` is unverified for everything else — non-OAuth connectors (`api_key`, `basic_auth`, `bearer_token`, `plaid`, `generic`), where refresh is lazy and a row can sit in `connected` behind a token that no longer works. `last_accessed_at` tracks *use*, not credential health, and the sweep never writes it. A connection that was never used can still hold a live, actively-refreshed credential with `last_accessed_at` set to `null`. Do not read `null` as "connected once and moved on" — those members still need to be told. ### Migrating between connectors Connecting a replacement server does not remove the old connection; the member has to disconnect it. Pull the roster of both servers and compare: present in both means already migrated and merely untidy, present only in the old one means not yet migrated. # Create a custom detection type Source: https://docs.barndoor.ai/api-reference/dlp/create-a-custom-detection-type /api-reference/openapi.yaml post /api/dlp/admin/v1/custom-detection-types # Create a detection engine Source: https://docs.barndoor.ai/api-reference/dlp/create-a-detection-engine /api-reference/openapi.yaml post /api/dlp/admin/v1/detection-engines # Create an allow-list entry Source: https://docs.barndoor.ai/api-reference/dlp/create-an-allow-list-entry /api-reference/openapi.yaml post /api/dlp/admin/v1/allow-list # Create an enforcement policy Source: https://docs.barndoor.ai/api-reference/dlp/create-an-enforcement-policy /api-reference/openapi.yaml post /api/dlp/admin/v1/enforcement-policies # Create or replace the field-control policy for an MCP server Source: https://docs.barndoor.ai/api-reference/dlp/create-or-replace-the-field-control-policy-for-an-mcp-server /api-reference/openapi.yaml post /api/dlp/admin/v1/field-control-policies # Create or update a provider connection Source: https://docs.barndoor.ai/api-reference/dlp/create-or-update-a-provider-connection /api-reference/openapi.yaml put /api/dlp/admin/v1/provider-connections/{name} # Delete a custom detection type Source: https://docs.barndoor.ai/api-reference/dlp/delete-a-custom-detection-type /api-reference/openapi.yaml delete /api/dlp/admin/v1/custom-detection-types/{id} # Delete a detection engine Source: https://docs.barndoor.ai/api-reference/dlp/delete-a-detection-engine /api-reference/openapi.yaml delete /api/dlp/admin/v1/detection-engines/{id} # Delete a field-control policy Source: https://docs.barndoor.ai/api-reference/dlp/delete-a-field-control-policy /api-reference/openapi.yaml delete /api/dlp/admin/v1/field-control-policies/{id} # Delete a provider connection and its stored secrets Source: https://docs.barndoor.ai/api-reference/dlp/delete-a-provider-connection-and-its-stored-secrets /api-reference/openapi.yaml delete /api/dlp/admin/v1/provider-connections/{name} # Delete an allow-list entry Source: https://docs.barndoor.ai/api-reference/dlp/delete-an-allow-list-entry /api-reference/openapi.yaml delete /api/dlp/admin/v1/allow-list/{id} # Delete an enforcement policy Source: https://docs.barndoor.ai/api-reference/dlp/delete-an-enforcement-policy /api-reference/openapi.yaml delete /api/dlp/admin/v1/enforcement-policies/{id} # Fetch one custom detection type Source: https://docs.barndoor.ai/api-reference/dlp/fetch-one-custom-detection-type /api-reference/openapi.yaml get /api/dlp/admin/v1/custom-detection-types/{id} # Fetch one detection engine Source: https://docs.barndoor.ai/api-reference/dlp/fetch-one-detection-engine /api-reference/openapi.yaml get /api/dlp/admin/v1/detection-engines/{id} # Fetch one enforcement policy Source: https://docs.barndoor.ai/api-reference/dlp/fetch-one-enforcement-policy /api-reference/openapi.yaml get /api/dlp/admin/v1/enforcement-policies/{id} # Fetch one field-control policy Source: https://docs.barndoor.ai/api-reference/dlp/fetch-one-field-control-policy /api-reference/openapi.yaml get /api/dlp/admin/v1/field-control-policies/{id} # Fetch one provider connection Source: https://docs.barndoor.ai/api-reference/dlp/fetch-one-provider-connection /api-reference/openapi.yaml get /api/dlp/admin/v1/provider-connections/{name} # Get Barndoor's AWS principal for role-assumption trust policies Source: https://docs.barndoor.ai/api-reference/dlp/get-barndoors-aws-principal-for-role-assumption-trust-policies /api-reference/openapi.yaml get /api/dlp/admin/v1/provider-connections/aws-role-config # Get the organization's DLP configuration Source: https://docs.barndoor.ai/api-reference/dlp/get-the-organizations-dlp-configuration /api-reference/openapi.yaml get /api/dlp/admin/v1/config # Get the principal and external id for a connection's trust policy Source: https://docs.barndoor.ai/api-reference/dlp/get-the-principal-and-external-id-for-a-connections-trust-policy /api-reference/openapi.yaml get /api/dlp/admin/v1/provider-connections/{name}/aws-trust-info # List every detection type available to the organization Source: https://docs.barndoor.ai/api-reference/dlp/list-every-detection-type-available-to-the-organization /api-reference/openapi.yaml get /api/dlp/admin/v1/detection-types # List the organization's allow-list entries Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-allow-list-entries /api-reference/openapi.yaml get /api/dlp/admin/v1/allow-list # List the organization's custom detection types Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-custom-detection-types /api-reference/openapi.yaml get /api/dlp/admin/v1/custom-detection-types # List the organization's detection engines Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-detection-engines /api-reference/openapi.yaml get /api/dlp/admin/v1/detection-engines # List the organization's enforcement policies Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-enforcement-policies /api-reference/openapi.yaml get /api/dlp/admin/v1/enforcement-policies # List the organization's field-control policies Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-field-control-policies /api-reference/openapi.yaml get /api/dlp/admin/v1/field-control-policies # List the organization's provider connections Source: https://docs.barndoor.ai/api-reference/dlp/list-the-organizations-provider-connections /api-reference/openapi.yaml get /api/dlp/admin/v1/provider-connections # Probe an AWS role Barndoor is meant to assume Source: https://docs.barndoor.ai/api-reference/dlp/probe-an-aws-role-barndoor-is-meant-to-assume /api-reference/openapi.yaml post /api/dlp/admin/v1/provider-connections/aws-role-validate # Resolve the effective protection rules for a scope Source: https://docs.barndoor.ai/api-reference/dlp/resolve-the-effective-protection-rules-for-a-scope /api-reference/openapi.yaml get /api/dlp/admin/v1/policies/resolved # Run a sample through the organization's live DLP pipeline Source: https://docs.barndoor.ai/api-reference/dlp/run-a-sample-through-the-organizations-live-dlp-pipeline /api-reference/openapi.yaml post /api/dlp/admin/v1/test/process-text # Set a field-control policy's unlisted-table override Source: https://docs.barndoor.ai/api-reference/dlp/set-a-field-control-policys-unlisted-table-override /api-reference/openapi.yaml put /api/dlp/admin/v1/field-control-policies/{id}/catalog-unlisted-table-action What catalog-aware SQL controls do for this MCP server with a table no rule covers: `allow`, `block` or `observe`, or `null` to fall back to the organization default (`PUT /config`). Requires catalog SQL controls to be enabled for the organization. # Update a custom detection type Source: https://docs.barndoor.ai/api-reference/dlp/update-a-custom-detection-type /api-reference/openapi.yaml put /api/dlp/admin/v1/custom-detection-types/{id} # Update a detection engine Source: https://docs.barndoor.ai/api-reference/dlp/update-a-detection-engine /api-reference/openapi.yaml put /api/dlp/admin/v1/detection-engines/{id} # Update a field-control policy Source: https://docs.barndoor.ai/api-reference/dlp/update-a-field-control-policy /api-reference/openapi.yaml put /api/dlp/admin/v1/field-control-policies/{id} # Update an enforcement policy Source: https://docs.barndoor.ai/api-reference/dlp/update-an-enforcement-policy /api-reference/openapi.yaml put /api/dlp/admin/v1/enforcement-policies/{id} # Update the organization's DLP configuration Source: https://docs.barndoor.ai/api-reference/dlp/update-the-organizations-dlp-configuration /api-reference/openapi.yaml put /api/dlp/admin/v1/config # Create Idp Connection Source: https://docs.barndoor.ai/api-reference/identity/create-idp-connection /api-reference/openapi.yaml post /api/identity/public/v1/idp/connection Create a new IdP connection for the organization. Creates a new OIDC Identity Provider and links it to the organization. This enables SSO for the organization. Required fields: - display_name: Human-readable name for the IdP - issuer: OIDC issuer URL - client_id: OAuth client ID from your IdP - client_secret: OAuth client secret from your IdP - authorization_url: OIDC authorization endpoint - token_url: OIDC token endpoint - jwks_url: OIDC JWKS endpoint Only admins can create an IdP connection. Returns 409 if an IdP already exists for this organization. # Delete Idp Connection Source: https://docs.barndoor.ai/api-reference/identity/delete-idp-connection /api-reference/openapi.yaml delete /api/identity/public/v1/idp/connection Delete the IdP connection for the organization. This removes the Identity Provider, disabling SSO for the organization. Users will need to use alternative authentication methods. WARNING: This action cannot be undone. Existing user sessions may be affected. Only admins can delete the IdP connection. # Get Idp Config Source: https://docs.barndoor.ai/api-reference/identity/get-idp-config /api-reference/openapi.yaml get /api/identity/public/v1/idp/config Get the current IdP role mapping configuration for the organization. ``admin_group`` is read from the org's ``admin``-role ``group_role_mapping`` row (BCP-3486); ``idp_alias``/``idp_display_name`` still come from Keycloak. Requires admin or superadmin role. # Get Idp Connection Source: https://docs.barndoor.ai/api-reference/identity/get-idp-connection /api-reference/openapi.yaml get /api/identity/public/v1/idp/connection Get the current IdP connection configuration for the organization. Returns the current OIDC configuration including endpoints and whether client credentials are configured (credentials are not exposed). Only admins can view this configuration. # Get Idp Settings Source: https://docs.barndoor.ai/api-reference/identity/get-idp-settings /api-reference/openapi.yaml get /api/identity/public/v1/idp/settings Get IdP-related settings for the organization. Returns settings including: - enforce_sso: Whether SSO is enforced (password login disabled) - break_glass_email: Dedicated emergency admin alias for SSO bypass Requires admin or superadmin role. # Get Organization Roles Groups Source: https://docs.barndoor.ai/api-reference/identity/get-organization-roles-groups /api-reference/openapi.yaml get /api/identity/public/v1/users/roles-groups Get all unique roles and groups across all users in the organization. Returns aggregated lists of all roles and groups that are assigned to any user in the authenticated user's organization. Only users with permission to list users can access this endpoint. # Test Idp Connection Source: https://docs.barndoor.ai/api-reference/identity/test-idp-connection /api-reference/openapi.yaml post /api/identity/public/v1/idp/test Test the IdP connection for the organization. Validates that the current IdP configuration is correct by: 1. Checking required configuration is present 2. Verifying the OIDC discovery endpoint is reachable 3. Validating the JWKS endpoint returns keys This helps diagnose configuration issues before users try to log in. Only admins can run this test. # Update Idp Config Source: https://docs.barndoor.ai/api-reference/identity/update-idp-config /api-reference/openapi.yaml put /api/identity/public/v1/idp/config Update the IdP role mapping configuration for the organization. Requires an IdP to already be configured for the organization — raises 404 otherwise, matching the legacy Keycloak-mapper-backed behavior (strict backward compatibility). Upserts (or, when ``admin_group`` is empty, deletes) the org's ``admin``-role ``group_role_mapping`` row(s) (BCP-3486) and enqueues org-wide re-evaluation. This no longer creates/updates a Keycloak IdP mapper — but does best-effort delete a lingering legacy ``barndoor-role-admin`` mapper if one is still present, so a stale FORCE-sync mapper can't keep granting admin at SSO after this call changes the authoritative DB row (see ``GroupRoleMappingService.update_legacy_idp_config``). Requires admin or superadmin role. # Update Idp Connection Source: https://docs.barndoor.ai/api-reference/identity/update-idp-connection /api-reference/openapi.yaml put /api/identity/public/v1/idp/connection Update the IdP connection configuration for the organization. Updates the OIDC Identity Provider settings including: - Display name - OIDC endpoints (authorization, token, userinfo, JWKS, logout) - Client credentials - Scopes - The OIDC `prompt` sent on the authorization request Only admins can update this configuration. Changes take effect immediately for new login attempts. # Barndoor API Reference Source: https://docs.barndoor.ai/api-reference/introduction ## Welcome Barndoor provides a robust API that allows developers to securely access their dashboard environment’s data and programmatically update settings relevant to their Barndoor organization. ## Authentication All API endpoints are authenticated using a user Bearer token or a Platform API key. * To obtain a platform API key, navigate to: [https://app.barndoor.ai/settings/tokens](https://app.barndoor.ai/settings/tokens) * To obtain a user token, use the Barndoor SDK's loginInteractive() method ```code theme={null} const sdk = await loginInteractive(); ``` See [here](/sdks/introduction) for more info. # Add models to a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/add-models-to-a-route-group /api-reference/openapi.yaml post /api/llm-gateway/admin/model-route-groups/{id}/members # Create an Org API Key Source: https://docs.barndoor.ai/api-reference/llm-gateway/api-keys/createApiKey api-reference/llm-gateway-openapi.yml post /admin/api-keys Creates a `bd-...` gateway API key for LLM traffic. The raw key is returned in this response and never again, so copy it immediately. Assign the key to a person with `user_id`, bind it to an IdP group with `group_name`, or omit both for a service key. `user_id` and `group_name` cannot be combined. Creates an organization-managed `bd-…` API key for the LLM Gateway runtime (`/v1/chat/completions`, `/v1/messages`, `/v1/embeddings`, etc.). > [!WARNING] > > The full key value is returned **only in this response**. Barndoor stores a > one-way hash and cannot reveal the raw key again — copy it immediately, e.g. > into your secrets manager or CI environment. A key is **assigned to a single user** (`user_id`), **bound to an IdP group** (`group_name`), or neither (a service key), but never both. Use the binding to control scope of: * per-user/per-group [budgets](/api-reference/llm-gateway/token-budgets/listBudgets) * per-user/per-group [rate limits](/api-reference/llm-gateway/rate-limits/listRateLimits) * per-user/per-group [model access policies](/api-reference/llm-gateway/model-access/listModelAccess) ## Example: a CI service-account key ```bash theme={null} curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/api-keys \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "GitHub Actions runner", "group_name": "ci", "expires_at": "2026-12-31T23:59:59Z" }' ``` The response includes the raw `key`. From that point on, callers can use it as: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-..." \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.4-mini", "messages": [...] }' ``` To rotate a key, call `POST /admin/api-keys/{id}/rotate`: the key keeps its ID, bindings, and usage history and gets a new secret, and an optional `grace_period_secs` (up to 7 days) keeps the old secret working meanwhile. To extend or shorten a key without a new secret, call `PUT /admin/api-keys/{id}/expiry`. Both are in the full **LLM Gateway** API reference; see [Managing LLM API Keys](/how-tos/manage-llm-api-keys) for the portal workflow. To stop a key for good, [revoke it](/api-reference/llm-gateway/api-keys/revokeApiKey). To stop a key temporarily without reissuing it, [disable it](/api-reference/llm-gateway/api-keys/setApiKeyDisabled) instead. # Get an API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/api-keys/getApiKey api-reference/llm-gateway-openapi.yml get /admin/api-keys/{id} # List API keys Source: https://docs.barndoor.ai/api-reference/llm-gateway/api-keys/listApiKeys api-reference/llm-gateway-openapi.yml get /admin/api-keys Lists the gateway API keys in the organization. The raw key is never returned, only its prefix and metadata. # Revoke an API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/api-keys/revokeApiKey api-reference/llm-gateway-openapi.yml delete /admin/api-keys/{id} Permanently revokes a key. It is rejected on every future request. To stop a key temporarily, disable it instead. # Disable or enable an API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/api-keys/setApiKeyDisabled api-reference/llm-gateway-openapi.yml patch /admin/api-keys/{id} Temporarily disables a key, or re-enables it. A disabled key is rejected on every request, but unlike revocation this is reversible and the key does not need to be reissued. # Change an API key's expiry Source: https://docs.barndoor.ai/api-reference/llm-gateway/change-an-api-keys-expiry /api-reference/openapi.yaml put /api/llm-gateway/admin/api-keys/{id}/expiry Extend, shorten or remove a key's expiry without issuing a new secret, so clients keep working unchanged. Also reactivates an expired key. A shortened expiry takes effect immediately. Admin only, and not limited by the API key lifetime policy. To replace the secret as well, rotate the key instead. # Create a API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-api-key /api-reference/openapi.yaml post /api/llm-gateway/admin/api-keys # Create a group API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-group-api-key-lifetime-override /api-reference/openapi.yaml post /api/llm-gateway/admin/api-key-lifetime-policies/groups Override the default for members of one IdP group. An override replaces the default for its members, so one with neither field set exempts the group. A user in several overridden groups gets the strictest: the shortest maximum, and an expiry required if any requires one. # Create a model-access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-model-access-policy /api-reference/openapi.yaml post /api/llm-gateway/admin/model-access # Create a model mapping Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-model-mapping /api-reference/openapi.yaml post /api/llm-gateway/admin/model-mappings # Create a model pricing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-model-pricing-rule /api-reference/openapi.yaml post /api/llm-gateway/admin/model-pricing # Create a model route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-model-route-group /api-reference/openapi.yaml post /api/llm-gateway/admin/model-route-groups # Create a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-provider /api-reference/openapi.yaml post /api/llm-gateway/admin/providers # Create a provider connection Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-provider-connection /api-reference/openapi.yaml post /api/llm-gateway/admin/connections # Create a rate-limit policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-rate-limit-policy /api-reference/openapi.yaml post /api/llm-gateway/admin/rate-limits # Create a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-routing-policy /api-reference/openapi.yaml post /api/llm-gateway/admin/routing-policies # Create a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-routing-rule /api-reference/openapi.yaml post /api/llm-gateway/admin/routing-rules # Create a token budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-token-budget /api-reference/openapi.yaml post /api/llm-gateway/admin/budgets # Create a user API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-a-user-api-key-lifetime-override /api-reference/openapi.yaml post /api/llm-gateway/admin/api-key-lifetime-policies/users Override the policy for one user. A user override wins outright: it replaces the user's group overrides and the default, so it can be looser or stricter than both. One with neither field set exempts the user. # Create an agent runtime profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-an-agent-runtime-profile /api-reference/openapi.yaml post /api/llm-gateway/admin/agent-runtime-profiles Creates the client's settings at version 1. An organization has one settings object per client, so this is refused with 409 when the client already has one; edit it instead. # Create the safe default Claude launch setup for a login provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/create-the-safe-default-claude-launch-setup-for-a-login-provider /api-reference/openapi.yaml post /api/llm-gateway/admin/agent-runtime-profiles/default-setup Creates a Model Route per current Claude model on the login provider, first enabling the newest catalog Opus, Sonnet, Haiku or Fable model on it when nothing in that family is enabled (`models_enabled` lists them; the organization's pricing requirement applies). Because a login (seat) token works only for Claude Code, each route it creates that has no fallback behind it yet also gets a lower-priority fallback target on the first enabled API-key, Bedrock, Vertex or Foundry provider (by name) that has the same model enabled; `routes[].fallback_provider` names it. A route that already exists with only login-token targets gets the same fallback (never a second one), and `fallback_provider` reports the fallback a route already has. Routes left with only login-token targets are returned in `warnings` (code `seat_only_route`). # Create a Credential Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/createCredential api-reference/llm-gateway-openapi.yml post /admin/connections Stores a new upstream credential. The plaintext `api_key` (or `credentials` object) is written to Barndoor's encrypted secret store and is never returned by any endpoint. Create the credential first, then reference it from a provider with `connection_id`. Providers can no longer store their own key. Create a reusable upstream credential. One credential can back many providers (for example, a single OpenAI key shared across multiple environments or routes). Providers can't store their own key: create the credential first, then reference it from [Create a provider](/api-reference/llm-gateway/providers/createProvider) with `connection_id`. ## Choosing the auth method The `model_provider` and `auth_type` together determine which fields are required: * **API key** (`auth_type` `bearer_api_key`, `x_api_key`, `azure_api_key`, or `bedrock_api_key`) — pass `api_key` with the upstream key. When you omit `auth_type`, it defaults by provider family (for example, `x_api_key` for `anthropic` and `azure_api_key` for `azure_openai`). * **Amazon Bedrock** (`auth_type` `aws_role` or `aws_static_credentials`) — pass the role or access-key details under `credentials`. For a role, name Barndoor's principal from [Get Barndoor's AWS principal](/api-reference/llm-gateway/credentials/getAwsRoleConfig) in the role's trust policy, and read the external ID with [Get AWS trust info](/api-reference/llm-gateway/credentials/getAwsTrustInfo). * **Google Vertex** (`auth_type` `google_adc`, `google_service_account`, or `google_service_account_impersonation`) — pass the service-account details under `credentials`. * **Claude and Codex sign-in passthrough** (`claude_oauth`, `codex_oauth`) — these store no secret, so they're configured on a provider without a credential. The plaintext key (or `credentials` JSON) is written to Barndoor's encrypted secret store and is never returned by any subsequent API call. Update or rotate it later with [`PUT /admin/connections/{id}`](/api-reference/llm-gateway/credentials/updateCredential). ## Example ```bash theme={null} curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/connections \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "OpenAI Production", "model_provider": "openai", "base_url": "https://api.openai.com/v1", "api_key": "sk-..." }' ``` > [!NOTE] > > For a guided walkthrough, see [Configure the Gateway](/how-tos/llm-gateway-quickstart#admin-configure-the-gateway). # Delete a credential Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/deleteCredential api-reference/llm-gateway-openapi.yml delete /admin/connections/{id} Deletes a credential. The request is refused with `409` while any provider still references it; move or delete those providers first. # Get Barndoor's AWS principal Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/getAwsRoleConfig api-reference/llm-gateway-openapi.yml get /admin/connections/aws-role-config Returns the AWS principal ARN to name as the trusted principal in the trust policy of any IAM role you give Barndoor for Amazon Bedrock role-based access. # Get AWS trust info Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/getAwsTrustInfo api-reference/llm-gateway-openapi.yml get /admin/connections/{id}/aws-trust-info Returns the Barndoor principal ARN and the per-credential external ID for an AWS role credential: the two values your role's trust policy needs. # Get a credential Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/getCredential api-reference/llm-gateway-openapi.yml get /admin/connections/{id} # List credentials Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/listCredentials api-reference/llm-gateway-openapi.yml get /admin/connections Returns every credential in your organization. A credential holds an upstream secret (an API key, an AWS role, or Google credentials) that one or more providers reference. The secret itself is never returned; `key_last4` shows the last four characters when the credential stores a key. # Update a credential Source: https://docs.barndoor.ai/api-reference/llm-gateway/credentials/updateCredential api-reference/llm-gateway-openapi.yml put /admin/connections/{id} Updates a credential. Only the fields you send are changed. Sending `api_key` or `credentials` rotates the stored secret for every provider that references this credential. # Delete a API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-api-key /api-reference/openapi.yaml delete /api/llm-gateway/admin/api-keys/{id} # Delete a group API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-group-api-key-lifetime-override /api-reference/openapi.yaml delete /api/llm-gateway/admin/api-key-lifetime-policies/groups/{id} Members of the group fall back to the default (or to their other groups' overrides). # Delete a model-access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-model-access-policy /api-reference/openapi.yaml delete /api/llm-gateway/admin/model-access/{id} # Delete a model mapping Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-model-mapping /api-reference/openapi.yaml delete /api/llm-gateway/admin/model-mappings/{id} # Delete a model pricing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-model-pricing-rule /api-reference/openapi.yaml delete /api/llm-gateway/admin/model-pricing/{id} Dispatches on whether the targeted version is future-dated. A scheduled version is cancelled outright. The current effective version is archived instead: a tombstone version is appended, any pending future versions are cancelled, and the rule leaves the summary list. Archived rules stay readable via `GET /admin/model-pricing/archived` and their full history via `GET /admin/model-pricing/history`. # Delete a model route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-model-route-group /api-reference/openapi.yaml delete /api/llm-gateway/admin/model-route-groups/{id} Policies that targeted the group keep the now-dangling target rather than being rewritten. Rewriting them would silently change what an allowlist permits at a moment nobody was looking at the policy; the dangling target expands to nothing and logs, which is the loud version of the same outcome. # Delete a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-provider /api-reference/openapi.yaml delete /api/llm-gateway/admin/providers/{id} # Delete a provider connection Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-provider-connection /api-reference/openapi.yaml delete /api/llm-gateway/admin/connections/{id} # Delete a rate-limit policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-rate-limit-policy /api-reference/openapi.yaml delete /api/llm-gateway/admin/rate-limits/{id} # Delete a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-routing-policy /api-reference/openapi.yaml delete /api/llm-gateway/admin/routing-policies/{id} # Delete a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-routing-rule /api-reference/openapi.yaml delete /api/llm-gateway/admin/routing-rules/{id} Gates on `update`, not `delete`: rules are versionless config and the admin UI treats add/edit/remove as one editing capability, the same way it does for policy slots. # Delete a token budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-token-budget /api-reference/openapi.yaml delete /api/llm-gateway/admin/budgets/{id} # Delete a user API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-a-user-api-key-lifetime-override /api-reference/openapi.yaml delete /api/llm-gateway/admin/api-key-lifetime-policies/users/{id} The user falls back to their groups' overrides, or to the default. # Delete an agent runtime profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/delete-an-agent-runtime-profile /api-reference/openapi.yaml delete /api/llm-gateway/admin/agent-runtime-profiles/{slug} # Fetch one agent runtime profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-agent-runtime-profile /api-reference/openapi.yaml get /api/llm-gateway/admin/agent-runtime-profiles/{slug} # Fetch one API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-api-key /api-reference/openapi.yaml get /api/llm-gateway/admin/api-keys/{id} # Fetch one client's settings Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-clients-settings /api-reference/openapi.yaml get /api/llm-gateway/admin/client-settings/{client} # Fetch one provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-provider /api-reference/openapi.yaml get /api/llm-gateway/admin/providers/{id} # Fetch one provider connection Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-provider-connection /api-reference/openapi.yaml get /api/llm-gateway/admin/connections/{id} # Fetch one version of a pricing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/fetch-one-version-of-a-pricing-rule /api-reference/openapi.yaml get /api/llm-gateway/admin/model-pricing/version/{id} # Get Barndoor's AWS principal for role-assumption trust policies Source: https://docs.barndoor.ai/api-reference/llm-gateway/get-barndoors-aws-principal-for-role-assumption-trust-policies /api-reference/openapi.yaml get /api/llm-gateway/admin/connections/aws-role-config # Get the API key lifetime policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/get-the-api-key-lifetime-policy /api-reference/openapi.yaml get /api/llm-gateway/admin/api-key-lifetime-policies The org default, per-group overrides and per-user overrides that limit how long self-serve API keys (created by users for themselves) may live. A user's own override wins; otherwise the strictest of their groups' overrides; otherwise the default. Keys created by admins are exempt. Existing keys keep their expiry; the policy is checked when a key is created or rotated. # Get the trust-policy principal and external id for a provider connection Source: https://docs.barndoor.ai/api-reference/llm-gateway/get-the-trust-policy-principal-and-external-id-for-a-provider-connection /api-reference/openapi.yaml get /api/llm-gateway/admin/connections/{id}/aws-trust-info # Get governance configuration Source: https://docs.barndoor.ai/api-reference/llm-gateway/governance/getGovernanceConfig api-reference/llm-gateway-openapi.yml get /admin/governance-config Returns the organization's LLM Gateway governance settings. An organization that has never changed them gets the defaults. # Update governance configuration Source: https://docs.barndoor.ai/api-reference/llm-gateway/governance/updateGovernanceConfig api-reference/llm-gateway-openapi.yml put /admin/governance-config Replaces the organization's governance settings. **This is a full replacement.** Any field you omit is reset to its default, so read the current configuration first and send every field back. In particular, omitting `default_model_access` sets it back to `allow`. Switching `default_model_access` to `deny` is refused with `400` unless at least one enabled allowlist policy exists for LLM traffic, so the change cannot lock out every caller at once. # LLM Gateway API Source: https://docs.barndoor.ai/api-reference/llm-gateway/introduction Programmatically configure the Barndoor LLM Gateway: credentials, providers, model routes, pricing, governance, routing policies, launch profiles, and gateway API keys. The LLM Gateway API is the configuration surface behind the **LLM Management** hub in the Barndoor portal — exposed so platform teams can script provisioning, manage configuration as code, and run automated audits. > [!NOTE] > > This API configures how the gateway routes and governs traffic. It is > **separate** from the runtime endpoints that carry LLM traffic > (`/v1/chat/completions`, `/v1/messages`, `/v1/embeddings`, …), which follow > OpenAI's and Anthropic's own API shapes and are documented in the > [Quickstart Guide](/how-tos/llm-gateway-quickstart#sending-requests). ## Base URL All configuration endpoints sit under `/api/llm-gateway/admin` on your Barndoor portal host: ``` https://app.barndoor.ai/api/llm-gateway/admin ``` On a dedicated or self-hosted deployment, replace `app.barndoor.ai` with your organization's portal hostname. For comparison, the runtime endpoints live under `https://app.barndoor.ai/api/llm-gateway/v1`. ## Authentication Configuration endpoints require a **Barndoor user bearer token (JWT)** — the same identity you use to sign in to the portal. The easiest way to obtain one from a script is the Barndoor SDK: ```ts theme={null} import { loginInteractive } from "@barndoor/sdk"; const sdk = await loginInteractive(); // sdk includes the bearer token; pass it on every API call. ``` Send the token on every request: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/admin/providers \ -H "Authorization: Bearer eyJhbGciOi..." ``` > [!WARNING] > > The `bd-…` gateway API keys you create through this API authenticate > **runtime** traffic only (`/v1/chat/completions`, `/v1/messages`, and so on). > They are **not** accepted on `/admin/...` endpoints. Use a bearer token for > configuration and a `bd-…` key for traffic. ## Permissions Every configuration endpoint requires the **admin** (or **superadmin**) role on the calling user. Users without it receive `403`. Developers manage their own keys and see their available models in the portal, under **Settings → My Models**. ## Conventions * Every resource is scoped to the caller's organization. There is no `org_id` parameter — it's resolved from your token. A resource in another organization behaves as if it doesn't exist (`404`). * Timestamps are RFC 3339 (`2026-06-12T18:30:00Z`). * Most resources are identified by UUID. Launch profiles are identified by their slug, and route group members by route name. * Most update endpoints accept partial bodies — fields you omit are left unchanged. A handful also distinguish **omitted** from **explicit `null`** (which clears the value); the affected fields are documented inline. ## Errors Errors come back with an HTTP status that matches the failure and a JSON body in OpenAI's error shape: ```json theme={null} { "error": { "message": "request_timeout_secs must be between 1 and 3600", "type": "invalid_request_error", "code": null } } ``` | Status | `type` | Meaning | | - | - | - | | `400` | `invalid_request_error` | Validation failure — fix the request body and retry. | | `401` | `authentication_error` | Missing or invalid bearer token. | | `403` | `permission_error` | The caller's role doesn't allow this action. | | `404` | `not_found_error` | The resource doesn't exist, or belongs to another organization. | | `409` | `conflict_error` | Conflicts with existing data — the `message` says what. | | `503` | `service_unavailable_error` | Transient; retry with backoff. | | `500` | `internal_error` | Unexpected server error. | ## API groups The endpoints are grouped by the resource they manage. Each group maps to a section of **LLM Management**. | Group | Paths | Manages | Portal section | | - | - | - | - | | **Credentials** | `/admin/connections` | Reusable upstream credentials — API keys, AWS IAM roles, Google service accounts, Entra ID service principals. Includes the AWS role configuration and per-credential AWS trust info. | Credentials | | **Providers** | `/admin/providers` | Named upstream connections, each using one set of credentials, and the model routes that target a provider. | Providers | | **Model Routes** | `/admin/model-mappings` | Enabled models and client-facing routes with their ordered targets, including reordering targets. | Models, Model Routes | | **Route Groups** | `/admin/model-route-groups` | Named sets of routes that a model access policy can target as a unit, and their members. | Model Routes → Route Groups | | **Model Pricing** | `/admin/model-pricing` | Organization pricing rules, their history and archived versions, and Barndoor's default price catalog. | Model Pricing | | **Budgets** | `/admin/budgets` | Token and spending budgets. | Budgets | | **Rate Limits** | `/admin/rate-limits` | Request and token throughput limits. | Rate Limits | | **Model Access** | `/admin/model-access` | Allow and deny policies for models and routes. | Model Access | | **Routing Policies** | `/admin/routing-policies` | Virtual model names that pick a model per request. | Routing Policies | | **Routing Rules** | `/admin/routing-rules` | Plain-English rules that constrain a routing policy's choice. | Routing Rules | | **Launch Profiles** (deprecated) | `/admin/agent-runtime-profiles` | Replaced by client settings (`/admin/client-settings`), which the admin UI shows as **Client settings**. Still served for at least 90 days; see [Client settings](/how-tos/barndoor-bridge/client-settings#moving-from-launch-profiles). | Client settings | | **API Keys** | `/admin/api-keys` | `bd-…` gateway keys — create, list, disable, and revoke. | API Keys | | **Governance Configuration** | `/admin/governance-config` | Organization-wide settings: whether routes require pricing, the default model access posture, and whether callers must use a routing policy. | Model Pricing, Model Access, Routing Policies | Browse each group's operations in the sidebar. > [!NOTE] > > Routing policies, routing rules, and client settings may not be enabled for > your organization yet — contact Barndoor if you need them. ## Where to next * New to the gateway? Read [Using the LLM Gateway](/how-tos/use-llm-gateway). * Setting it up for the first time? Follow the [Quickstart Guide](/how-tos/llm-gateway-quickstart), which also covers the runtime endpoints (chat completions, messages, embeddings, model listing). * Managing configuration as code? See the [Terraform provider](/terraform/llm-gateway). # Create a launch profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/createLaunchProfile api-reference/llm-gateway-openapi.yml post /admin/agent-runtime-profiles Creates a launch profile for one client. Every value in `config` must be a single model route alias that resolves in your organization. # Delete a launch profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/deleteLaunchProfile api-reference/llm-gateway-openapi.yml delete /admin/agent-runtime-profiles/{slug} Deletes a launch profile. The request fails with `409` if the profile is still referenced. # Get a launch profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/getLaunchProfile api-reference/llm-gateway-openapi.yml get /admin/agent-runtime-profiles/{slug} # List launch profiles Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/listLaunchProfiles api-reference/llm-gateway-openapi.yml get /admin/agent-runtime-profiles Returns the organization's launch profiles. A launch profile sets the models and capabilities that members get when they start Claude Code or Codex through `barndoor run`. # Replace a launch profile's models and capabilities Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/replaceLaunchProfileContract api-reference/llm-gateway-openapi.yml put /admin/agent-runtime-profiles/{slug} Replaces the profile's `config` and, when sent, its `capabilities`, creating a new version of the profile. # Make a launch profile the default Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/setDefaultLaunchProfile api-reference/llm-gateway-openapi.yml post /admin/agent-runtime-profiles/{slug}/default Makes this profile the organization's default for its client, replacing the previous default. Inactive profiles cannot be made the default. # Rename or activate a launch profile Source: https://docs.barndoor.ai/api-reference/llm-gateway/launch-profiles/updateLaunchProfileMetadata api-reference/llm-gateway-openapi.yml patch /admin/agent-runtime-profiles/{slug} Updates the profile's display name or active state without creating a new version. # List the built-in default model pricing Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-built-in-default-model-pricing /api-reference/openapi.yaml get /api/llm-gateway/admin/model-pricing/defaults # List the change history for the organization's pricing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-change-history-for-the-organizations-pricing-rules /api-reference/openapi.yaml get /api/llm-gateway/admin/model-pricing/history # List the model mappings for one provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-model-mappings-for-one-provider /api-reference/openapi.yaml get /api/llm-gateway/admin/providers/{provider_id}/model-mappings # List the organization's agent runtime profiles Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-agent-runtime-profiles /api-reference/openapi.yaml get /api/llm-gateway/admin/agent-runtime-profiles # List the organization's API keys Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-api-keys /api-reference/openapi.yaml get /api/llm-gateway/admin/api-keys # List the organization's archived pricing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-archived-pricing-rules /api-reference/openapi.yaml get /api/llm-gateway/admin/model-pricing/archived # List the organization's client settings Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-client-settings /api-reference/openapi.yaml get /api/llm-gateway/admin/client-settings Returns the settings for both clients, Claude Code first. A client the organization has not configured is returned with `exists: false`, version 0 and the built-in defaults. # List the organization's governance configurations Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-governance-configurations /api-reference/openapi.yaml get /api/llm-gateway/admin/governance-config # List the organization's model-access policys Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-model-access-policys /api-reference/openapi.yaml get /api/llm-gateway/admin/model-access # List the organization's model mappings Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-model-mappings /api-reference/openapi.yaml get /api/llm-gateway/admin/model-mappings # List the organization's model pricing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-model-pricing-rules /api-reference/openapi.yaml get /api/llm-gateway/admin/model-pricing # List the organization's model route groups Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-model-route-groups /api-reference/openapi.yaml get /api/llm-gateway/admin/model-route-groups # List the organization's provider connections Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-provider-connections /api-reference/openapi.yaml get /api/llm-gateway/admin/connections # List the organization's providers Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-providers /api-reference/openapi.yaml get /api/llm-gateway/admin/providers # List the organization's rate-limit policys Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-rate-limit-policys /api-reference/openapi.yaml get /api/llm-gateway/admin/rate-limits # List the organization's routing policys Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-routing-policys /api-reference/openapi.yaml get /api/llm-gateway/admin/routing-policies # List the organization's routing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-routing-rules /api-reference/openapi.yaml get /api/llm-gateway/admin/routing-rules # List the organization's token budgets Source: https://docs.barndoor.ai/api-reference/llm-gateway/list-the-organizations-token-budgets /api-reference/openapi.yaml get /api/llm-gateway/admin/budgets # Make this the organization's settings for its client Source: https://docs.barndoor.ai/api-reference/llm-gateway/make-this-the-organizations-settings-for-its-client /api-reference/openapi.yaml post /api/llm-gateway/admin/agent-runtime-profiles/{slug}/default Promotes an archived profile to the client's settings and archives the current settings, in one transaction. Naming the current settings is a no-op. # Create a model access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-access/createModelAccess api-reference/llm-gateway-openapi.yml post /admin/model-access Creates an allowlist (only the listed targets are permitted) or a denylist (the listed targets are blocked) for a scope. A target can be a model alias, an upstream model, a provider, a provider and alias pair, or a route group. What happens to models no policy mentions is set org-wide by `default_model_access` in the governance configuration. # Delete a model access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-access/deleteModelAccess api-reference/llm-gateway-openapi.yml delete /admin/model-access/{id} # List model access policies Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-access/listModelAccess api-reference/llm-gateway-openapi.yml get /admin/model-access # Update a model access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-access/updateModelAccess api-reference/llm-gateway-openapi.yml put /admin/model-access/{id} Updates a model access policy. Only the fields you send are changed. Send `null` for `scope_id` or `scope_value` to unbind the policy from a single entity. # Archive or cancel a pricing version Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/archivePricing api-reference/llm-gateway-openapi.yml delete /admin/model-pricing/{id} What happens depends on the version you target: - **A scheduled (future-dated) version** is cancelled. - **The current version** archives the whole rule: pending scheduled changes are cancelled and the rule leaves the active list. Archived rules stay available from `GET /admin/model-pricing/archived`, and their full history from `GET /admin/model-pricing/history`. # Create or Schedule Pricing Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/createPricing api-reference/llm-gateway-openapi.yml post /admin/model-pricing Creates a pricing rule, or appends a new version to an existing one. A rule is identified by `model_provider` and `model_pattern`. - Omit `effective_from` (or send `null`) to activate the price now. - Send a future `effective_from` to schedule the change. Past versions are never modified; each price change adds a version to the rule's history. Creates a new pricing version for a model. Pricing drives every cost-aware feature on the platform — usage attribution, spend reporting, and [budgets](/api-reference/llm-gateway/token-budgets/listBudgets) with a `cost_limit`. ## Activate now or schedule for later The `effective_from` field decides whether the change is immediate or scheduled: * **Omit (or `null`)** — the price activates immediately and replaces the current effective price for this rule. * **Future timestamp** — the price activates on that date, recorded as a scheduled change. Visible to admins via the [history](/api-reference/llm-gateway/model-pricing/getPricingHistory) endpoint and the **Scheduled** indicator in the Barndoor app. Past versions are immutable; to correct a mistake, create a new version with an immediate `effective_from`. ## Sync mode `sync_mode` controls whether Barndoor's seeded defaults can move this row later: * `pinned` (default for manually-created rules) — never auto-sync. * `tracking` — show the user a prompt when defaults change. * `auto` — silently follow the default. Useful when you want to outsource pricing maintenance entirely to Barndoor. ## Example ```bash theme={null} curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/model-pricing \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "model_provider": "openai", "model_pattern": "gpt-5.4-mini", "input_cost_per_million_tokens": 0.60, "output_cost_per_million_tokens": 3.60, "sync_mode": "pinned", "change_reason": "Q1 2026 negotiated discount" }' ``` > [!NOTE] > > For wildcards, scheduling, and the four-tier resolution order, see > [Manage Model Pricing](/how-tos/manage-model-pricing). # Get a pricing rule's history Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/getPricingHistory api-reference/llm-gateway-openapi.yml get /admin/model-pricing/history Returns every version of one rule (current, scheduled, archived, and earlier versions). # Get a pricing version Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/getPricingVersion api-reference/llm-gateway-openapi.yml get /admin/model-pricing/version/{id} Returns one version of a pricing rule by ID, including versions that are no longer current. # List archived pricing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/listArchivedPricing api-reference/llm-gateway-openapi.yml get /admin/model-pricing/archived # List pricing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/listPricing api-reference/llm-gateway-openapi.yml get /admin/model-pricing One row per pricing rule, each showing the currently effective version, a `version_count`, and a `scheduled_count` of future-dated changes waiting to activate. Archived rules are not included. # List Barndoor's default pricing Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/listPricingDefaults api-reference/llm-gateway-openapi.yml get /admin/model-pricing/defaults Returns the default pricing catalog Barndoor maintains. Rules with `sync_mode: auto` follow changes to these defaults automatically, `tracking` rules surface them for review, and `pinned` rules ignore them. # Edit a scheduled pricing version Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-pricing/updatePricing api-reference/llm-gateway-openapi.yml put /admin/model-pricing/{id} Updates a future-dated (scheduled) pricing version in place. Past versions are immutable: to change the active price, create a new version with `POST /admin/model-pricing`. # Create a Model Route Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/createRoute api-reference/llm-gateway-openapi.yml post /admin/model-mappings Creates a model route from a caller-facing `model_alias` to an `upstream_model` on a provider. - A **1:1 enablement** (`model_alias` equals `upstream_model`) makes the model servable on the provider. Creating one that already exists updates the existing row instead of failing, so automation can re-issue the call safely. - A **custom alias** (`model_alias` differs from `upstream_model`) requires the 1:1 enablement for the same provider and upstream model to exist first, or the request fails with `400`. When your organization requires pricing for model routes, an enabled route must match a pricing rule. A **Model Route** maps a client-facing alias to a (provider, upstream model) pair. Multiple routes can share the same `model_alias` — the gateway tries them in `priority` order (lowest first) and fails over to the next on upstream errors. ## Two kinds of routes * **1:1 enablement (`model_alias == upstream_model`)** — exposes the upstream model under its own name, addressable as `/`. Defaults to `bare_alias: false`. Re-issuing this call for an existing enablement folds into the existing row, making it idempotent. * **Custom alias (`model_alias != upstream_model`)** — exposes the model under a friendly alias (e.g. `team-coding-model`). Defaults to `bare_alias: true` so callers can use the plain name in `model`. Requires an existing 1:1 enablement on the same `(provider, upstream_model)` pair. Every route also carries its own retry policy (`retry_on_429_*`), timeouts, and passive-health cooldown settings (`cooldown_*`); omitted fields take the platform defaults. Change them later with [Update a model route](/api-reference/llm-gateway/model-routes/updateRoute). ## Example: an alias with failover The simplest production setup is one alias backed by a primary route plus one or more failover routes: Route 1 is a 1:1 enablement opted into bare-name resolution, so callers can send `claude-opus-5-5` without a provider prefix. Route 2 is a custom alias with the same name on Bedrock, so the 1:1 enablement of `anthropic.claude-opus-5-5` on that provider must exist first. ```bash theme={null} # Route 1: primary (priority 0) curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/model-mappings \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "provider_id": "", "model_alias": "claude-opus-5-5", "upstream_model": "claude-opus-5-5", "priority": 0, "bare_alias": true }' # Route 2: failover on Bedrock (priority 1) curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/model-mappings \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "provider_id": "", "model_alias": "claude-opus-5-5", "upstream_model": "anthropic.claude-opus-5-5", "priority": 1, "bare_alias": true }' ``` > [!NOTE] > > For more on failover, retry policies, and bare aliases see [Define Model Routes](/how-tos/llm-gateway-quickstart#step-5-define-model-routes). # Delete a model route Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/deleteRoute api-reference/llm-gateway-openapi.yml delete /admin/model-mappings/{id} # List all model routes Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/listAllRoutes api-reference/llm-gateway-openapi.yml get /admin/model-mappings Returns every model route in the organization with its provider's name. Each row also carries the rate it would be billed at (`effective_pricing`) and, when applicable, whether an exhausted budget, a health cooldown, or a model retired from the provider's catalog is affecting it. # List a provider's model routes Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/listProviderRoutes api-reference/llm-gateway-openapi.yml get /admin/providers/{provider_id}/model-mappings # Reorder model routes Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/reorderRoutes api-reference/llm-gateway-openapi.yml put /admin/model-mappings/reorder Sets the `priority` of several routes in one call. Routes that share an alias fail over in ascending priority order. # Update a model route Source: https://docs.barndoor.ai/api-reference/llm-gateway/model-routes/updateRoute api-reference/llm-gateway-openapi.yml put /admin/model-mappings/{id} Updates a model route. Only the fields you send are changed. When your organization requires pricing for model routes, an enabled route must still match a pricing rule after the update; setting `enabled: false` is always allowed. # Create a Provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/providers/createProvider api-reference/llm-gateway-openapi.yml post /admin/providers Creates a named upstream provider. Providers whose auth type needs a secret must reference an existing credential with `connection_id`; sending `api_key` or `credentials` here is rejected with `400`. Pass `models` to enable a list of upstream model names as 1:1 model routes in the same call. A **Provider** is a named upstream that authenticates with one credential and serves a model family. Pass `connection_id` referencing an existing [Credential](/api-reference/llm-gateway/credentials/createCredential); the provider takes its `auth_type` and settings from it. > [!WARNING] > > Providers can't store their own key. Sending `api_key` or `credentials` here is > rejected with `400`, and so is a provider with no `connection_id` unless its auth > type stores no secret (`claude_oauth` or `codex_oauth`). To rotate a key, update > the credential. ## Auto-enabling models in one call Pass a list of upstream model names in `models` and Barndoor will create a 1:1 [Model Route](/api-reference/llm-gateway/model-routes/listAllRoutes) for each one in the same call. The route's alias matches the upstream model name so callers can address it as `/`. Add bare-name aliases or failover routes afterwards via the Model Routes endpoints. ## Example ```bash theme={null} curl -X POST https://app.barndoor.ai/api/llm-gateway/admin/providers \ -H "Authorization: Bearer $BARNDOOR_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "OpenAI Production (US)", "model_provider": "openai", "base_url": "https://api.openai.com/v1", "connection_id": "4f8b2a3c-12ee-4d92-9c7b-e7d2f8b0a111", "models": ["gpt-5.5", "gpt-5.4-mini", "text-embedding-3-large"] }' ``` > [!NOTE] > > See the [Quickstart Guide](/how-tos/llm-gateway-quickstart#step-2-create-a-provider) for the full walkthrough. # Delete a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/providers/deleteProvider api-reference/llm-gateway-openapi.yml delete /admin/providers/{id} Deletes a provider and every model route that pointed at it. # Get a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/providers/getProvider api-reference/llm-gateway-openapi.yml get /admin/providers/{id} # List providers Source: https://docs.barndoor.ai/api-reference/llm-gateway/providers/listProviders api-reference/llm-gateway-openapi.yml get /admin/providers # Update a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/providers/updateProvider api-reference/llm-gateway-openapi.yml put /admin/providers/{id} Updates a provider. Only the fields you send are changed. To rotate the upstream key, update the credential instead. You can rebind the provider to a different credential with `connection_id`, but a provider whose auth type needs a secret cannot be detached from its credential. # Create a rate limit Source: https://docs.barndoor.ai/api-reference/llm-gateway/rate-limits/createRateLimit api-reference/llm-gateway-openapi.yml post /admin/rate-limits Creates a per-minute request and/or token ceiling for a scope, measured over a rolling 60-second window. At least one of `requests_per_minute` and `tokens_per_minute` is required. Use the `target_*` fields to limit only the traffic that goes to a specific provider, upstream model, model alias, or MCP server. # Delete a rate limit Source: https://docs.barndoor.ai/api-reference/llm-gateway/rate-limits/deleteRateLimit api-reference/llm-gateway-openapi.yml delete /admin/rate-limits/{id} # List rate limits Source: https://docs.barndoor.ai/api-reference/llm-gateway/rate-limits/listRateLimits api-reference/llm-gateway-openapi.yml get /admin/rate-limits # Update a rate limit Source: https://docs.barndoor.ai/api-reference/llm-gateway/rate-limits/updateRateLimit api-reference/llm-gateway-openapi.yml put /admin/rate-limits/{id} Updates a rate limit. Only the fields you send are changed. Send `null` for `scope_id`, `scope_value`, a `target_*` field, or a per-minute metric to clear it; at least one metric must remain set. # Remove a model from a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/remove-a-model-from-a-route-group /api-reference/openapi.yaml delete /api/llm-gateway/admin/model-route-groups/{id}/members/{alias} # Rename a model route Source: https://docs.barndoor.ai/api-reference/llm-gateway/rename-a-model-route /api-reference/openapi.yaml post /api/llm-gateway/admin/model-routes/rename Renames a route in one transaction: every target, and the route's route-group memberships (BCP-4580). Renaming target by target through `PUT /admin/model-mappings/{id}` still works, but leaves the route split across two names until the last PUT lands, and moves the memberships on the first one. # Reorder the organization's model mappings Source: https://docs.barndoor.ai/api-reference/llm-gateway/reorder-the-organizations-model-mappings /api-reference/openapi.yaml put /api/llm-gateway/admin/model-mappings/reorder # Replace a profile's capability contract Source: https://docs.barndoor.ai/api-reference/llm-gateway/replace-a-profiles-capability-contract /api-reference/openapi.yaml put /api/llm-gateway/admin/agent-runtime-profiles/{slug} # Rotate an API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/rotate-an-api-key /api-reference/openapi.yaml post /api/llm-gateway/admin/api-keys/{id}/rotate Replace the key's secret in place. The key id, name, bindings and usage history are kept. With `grace_period_secs` the previous secret keeps working for that long (at most 7 days); otherwise it stops working immediately. The new secret is returned once and never stored. # Add routes to a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/addRouteGroupMembers api-reference/llm-gateway-openapi.yml post /admin/model-route-groups/{id}/members Adds aliases to the group. Aliases that are already members are ignored. # Create a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/createRouteGroup api-reference/llm-gateway-openapi.yml post /admin/model-route-groups Creates a route group, optionally with its initial member aliases. An empty group is valid: you can attach it to a policy and add members later. # Delete a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/deleteRouteGroup api-reference/llm-gateway-openapi.yml delete /admin/model-route-groups/{id} Deletes a route group. Model access policies that targeted the group are not rewritten: the target remains and matches nothing. Review those policies after deleting a group, because an allowlist that relied on it no longer grants those routes. # List route groups Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/listRouteGroups api-reference/llm-gateway-openapi.yml get /admin/model-route-groups Returns every route group in the organization with its member aliases. A route group is a named set of model aliases that a model access policy can target as one unit. # Remove a route from a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/removeRouteGroupMember api-reference/llm-gateway-openapi.yml delete /admin/model-route-groups/{id}/members/{alias} # Update a route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/route-groups/updateRouteGroup api-reference/llm-gateway-openapi.yml put /admin/model-route-groups/{id} Renames a route group or changes its description. When `model_aliases` is present it replaces the whole membership; omit it to leave members unchanged. # Create a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-policies/createRoutingPolicy api-reference/llm-gateway-openapi.yml post /admin/routing-policies Creates a routing policy. Callers use the policy's `model_alias` like any other model name; the gateway sends each request to one of the `slots`. A policy needs at least two slots, a `determiner_model_alias`, and exactly one `context_breakpoints` entry fewer than it has slots. The policy alias cannot be one of its own slots or its determiner. # Delete a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-policies/deleteRoutingPolicy api-reference/llm-gateway-openapi.yml delete /admin/routing-policies/{id} # List routing policies Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-policies/listRoutingPolicies api-reference/llm-gateway-openapi.yml get /admin/routing-policies Returns every routing policy in the organization. A routing policy is a model alias that, when called, picks one of several model slots per request. # Update a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-policies/updateRoutingPolicy api-reference/llm-gateway-openapi.yml put /admin/routing-policies/{id} Updates a routing policy. Only the fields you send are changed; the merged result must still pass the same validation as a new policy. # Create a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-rules/createRoutingRule api-reference/llm-gateway-openapi.yml post /admin/routing-rules Adds a rule to a routing policy. A rule is a plain-English `description` of the requests it applies to, with a minimum slot (`floor_slot`), slots it forbids (`deny_slots`), or both. Slot numbers are 0-based positions in the policy's `slots` list. Conflicts with the policy's other rules are reported in the response but do not block the save. When a floor and a ban cannot both be honored, the ban wins. # Delete a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-rules/deleteRoutingRule api-reference/llm-gateway-openapi.yml delete /admin/routing-rules/{id} # List a policy's routing rules Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-rules/listRoutingRules api-reference/llm-gateway-openapi.yml get /admin/routing-rules Returns the rules attached to one routing policy, plus any conflicts between them. # Replace a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/routing-rules/updateRoutingRule api-reference/llm-gateway-openapi.yml put /admin/routing-rules/{id} Replaces a routing rule with the body you send. Conflicts are reported in the response. # Save one client's settings Source: https://docs.barndoor.ai/api-reference/llm-gateway/save-one-clients-settings /api-reference/openapi.yaml put /api/llm-gateway/admin/client-settings/{client} Replaces the client's capabilities, appending a version; the first save creates the settings. `preferences` are stored but not read by a launch: Model Access decides which models each person can use, and every launch slot is derived from that (the newest allowed route of the slot's family). # Set the default API key lifetime policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/set-the-default-api-key-lifetime-policy /api-reference/openapi.yaml put /api/llm-gateway/admin/api-key-lifetime-policies/default Set the org-wide limit for self-serve API keys. `max_lifetime_days` (1-3650) caps how long a key may live from when it is created or rotated, and also rules out keys that never expire; `require_expiry` requires an expiry without capping it; `fixed_lifetime` gives every key exactly `max_lifetime_days`, so users don't choose one. Sending none removes the default. # Create a budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/token-budgets/createBudget api-reference/llm-gateway-openapi.yml post /admin/budgets Creates a token and/or cost ceiling for a scope over a daily, weekly, or monthly period. Set `token_limit`, `cost_limit`, or both; use `token_limit: 0` with a `cost_limit` for a cost-only budget. Use the `target_*` fields to count only the traffic that goes to a specific provider, upstream model, model alias, or MCP server. # Delete a budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/token-budgets/deleteBudget api-reference/llm-gateway-openapi.yml delete /admin/budgets/{id} # List budgets Source: https://docs.barndoor.ai/api-reference/llm-gateway/token-budgets/listBudgets api-reference/llm-gateway-openapi.yml get /admin/budgets # Update a budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/token-budgets/updateBudget api-reference/llm-gateway-openapi.yml put /admin/budgets/{id} Updates a budget's name, limits, period, alert thresholds, exhaustion action, traffic type, or enabled state. Only the fields you send are changed. A budget's scope and targets cannot be changed; create a new budget instead. # Update a API key Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-api-key /api-reference/openapi.yaml patch /api/llm-gateway/admin/api-keys/{id} # Update a governance configuration Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-governance-configuration /api-reference/openapi.yaml put /api/llm-gateway/admin/governance-config # Update a group API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-group-api-key-lifetime-override /api-reference/openapi.yaml put /api/llm-gateway/admin/api-key-lifetime-policies/groups/{id} # Update a model-access policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-model-access-policy /api-reference/openapi.yaml put /api/llm-gateway/admin/model-access/{id} # Update a model mapping Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-model-mapping /api-reference/openapi.yaml put /api/llm-gateway/admin/model-mappings/{id} When `require_pricing_for_mappings` is on, an enabled post-update row must have pricing configured for its `upstream_model`. Mirrors the create-path guard so disabled rows can't be silently re-enabled (or swapped to an unpriced upstream) without re-validating. `enabled: false` is always allowed. # Update a model pricing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-model-pricing-rule /api-reference/openapi.yaml put /api/llm-gateway/admin/model-pricing/{id} # Update a model route group Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-model-route-group /api-reference/openapi.yaml put /api/llm-gateway/admin/model-route-groups/{id} # Update a profile's display metadata Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-profiles-display-metadata /api-reference/openapi.yaml patch /api/llm-gateway/admin/agent-runtime-profiles/{slug} Changes the display name. `active` is accepted only when it restates the profile's current state: client settings can't be switched off, and an archived profile can't be switched back on (promote it instead). # Update a provider Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-provider /api-reference/openapi.yaml put /api/llm-gateway/admin/providers/{id} # Update a provider connection Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-provider-connection /api-reference/openapi.yaml put /api/llm-gateway/admin/connections/{id} # Update a rate-limit policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-rate-limit-policy /api-reference/openapi.yaml put /api/llm-gateway/admin/rate-limits/{id} # Update a routing policy Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-routing-policy /api-reference/openapi.yaml put /api/llm-gateway/admin/routing-policies/{id} # Update a routing rule Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-routing-rule /api-reference/openapi.yaml put /api/llm-gateway/admin/routing-rules/{id} # Update a token budget Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-token-budget /api-reference/openapi.yaml put /api/llm-gateway/admin/budgets/{id} # Update a user API key lifetime override Source: https://docs.barndoor.ai/api-reference/llm-gateway/update-a-user-api-key-lifetime-override /api-reference/openapi.yaml put /api/llm-gateway/admin/api-key-lifetime-policies/users/{id} # MCP server proxy endpoint Source: https://docs.barndoor.ai/api-reference/mcp/proxyMcpRequest get /mcp/{mcp_server_name} Proxies MCP JSON-RPC requests to third-party servers with automatic authentication. This endpoint supports both regular Streamable HTTP requests and Server-Sent Events (SSE) for real-time MCP protocol communication. ## Usage - **JSON-RPC**: Send MCP protocol requests as JSON - **SSE Streaming**: Use `Accept: text/event-stream` for real-time communication - **Session Management**: Include `x-mcp-session-id` header for session tracking ## Authentication Flow 1. User must first connect to the server via `/api/servers/{server_id}/connect` 2. Complete OAuth flow for the third-party service 3. Use this endpoint to proxy MCP requests with automatic credential injection # Create or update a notification channel Source: https://docs.barndoor.ai/api-reference/notification/create-or-update-a-notification-channel /api-reference/openapi.yaml put /api/notification/public/v1/channels Upserts one channel and **replaces** its subscription set. Without `id`, the channel is keyed on its type's natural identity, so an identical call is idempotent rather than duplicating: `email` by address, `webhook` by URL, `slack` by channel id, personal types by (organization, type, caller). With `id` it is an authoritative edit of that row — the only way to update a `teams` channel, whose natural identity is a secret URL. `subscriptions` is replaced wholesale, not merged: send the complete desired set, and expect an omitted list to unsubscribe the channel from everything. Creating a `webhook` channel reveals its signing secret in `signing_secret` ONCE; it is not readable afterwards. The secret is only generated when the row is new, so a retried create that lands after the first succeeded returns `signing_secret: null`. If you need a secret and got `null`, call `POST /channels/{channel_id}/regenerate-secret`. # Delete a channel Source: https://docs.barndoor.ai/api-reference/notification/delete-a-channel /api-reference/openapi.yaml delete /api/notification/public/v1/channels/{channel_id} Deletes one channel; its subscriptions cascade and any stored secret is removed. Irreversible — to stop delivery reversibly, upsert the channel with `enabled: false` instead. # List the caller's personal channels Source: https://docs.barndoor.ai/api-reference/notification/list-the-callers-personal-channels /api-reference/openapi.yaml get /api/notification/public/v1/channels/user Returns the authenticated caller's own `in_app` and `user_email` channels. Always self-scoped — there is no way to read another user's personal channels, and no user parameter to pass. # List the organization's shared channels Source: https://docs.barndoor.ai/api-reference/notification/list-the-organizations-shared-channels /api-reference/openapi.yaml get /api/notification/public/v1/channels Returns the organization's org-wide channels — `email`, `webhook`, `slack`, `teams` — with their current subscription sets. Personal channels are not included here; read those from `/channels/user`. Unpaginated. Secrets are never returned: a webhook's signing secret and a Teams workflow URL surface only as the `has_signing_secret` / `has_workflow_url` flags. # List the subscribable alert vocabulary Source: https://docs.barndoor.ai/api-reference/notification/list-the-subscribable-alert-vocabulary /api-reference/openapi.yaml get /api/notification/public/v1/channels/options Returns every alert type this organization may subscribe a channel to, plus the category and severity label vocabularies those types reference. Read this before building a subscription set. The alert-type enum grows over time and is gated per organization, so this endpoint — not a hardcoded list — is the authoritative answer to what `subscriptions[].alert_type` accepts. Subscribing to a type absent here is accepted but never delivers. # Rotate a webhook channel's signing secret Source: https://docs.barndoor.ai/api-reference/notification/rotate-a-webhook-channels-signing-secret /api-reference/openapi.yaml post /api/notification/public/v1/channels/{channel_id}/regenerate-secret Generates a new Standard Webhooks signing secret for a `webhook` channel and returns it once, in this response. The previous secret stops verifying immediately, so deploy the new one to your receiver before the next alert fires. Use this if the secret from channel creation was lost or needs rotating; there is no endpoint that reads the current secret. # Send a test message through a channel Source: https://docs.barndoor.ai/api-reference/notification/send-a-test-message-through-a-channel /api-reference/openapi.yaml post /api/notification/public/v1/channels/{channel_id}/test Sends a stock connectivity-test message through the channel's real transport, so you can verify a webhook receiver, email address, Slack channel, or Teams workflow actually works. It is not an alert: nothing is persisted, no other channel is notified, and it does not depend on the channel's subscriptions. A transport failure is reported as `200` with `ok: false` and an `error` string — the request succeeded, the delivery did not. # Clone Policy Source: https://docs.barndoor.ai/api-reference/policies/clonePolicy POST /api/v2/policies/{policy_id}/clone Clone an existing policy, creating a new policy with the same configuration but with a modified name (appending " Copy") and DRAFT status. # Create or Update Policy Source: https://docs.barndoor.ai/api-reference/policies/createPolicy POST /api/policy This endpoint creates a policy in the v2 policy service. ## v2 request shape The v2 API accepts a single policy object. It no longer uses the old `policies[].resourcePolicy` wrapper. Important fields: * `name`: unique policy name within the organization * `mcp_server_id`: target MCP server * `application_ids`: agents/applications this policy applies to * `status`: `DRAFT`, `ACTIVE`, `INACTIVE`, or `ARCHIVED` * `rules`: array of rule objects using `authorized`, `actions`, `roles_groups`, and optional `condition` ### Tool-call actions Each entry in `actions` names one MCP action. For tool calls there are two forms, and the choice between them is the tool's permission state: * `tools/call:` — granted outright; the call runs without confirmation. * `tools/call::approve` — granted subject to approval; the user confirms the specific call before it runs. Use one form per tool per rule, not both. A tool omitted from every applicable rule is not granted. Where more than one rule applies to a principal the most permissive grant wins, so a plain grant elsewhere overrides an `:approve` grant here. The `:approve` suffix is reserved and may appear at most once, at the end of a tool-call action; a doubled suffix is rejected. Example: ```json theme={null} { "name": "Slack outbound policy", "description": "Default outbound Slack controls for the support agent.", "support_contact": "platform@company.com", "tags": ["slack", "support"], "status": "DRAFT", "mcp_server_id": "server_123", "application_ids": ["agent_456"], "rules": [ { "name": "support_reads_and_gated_posts", "authorized": true, "actions": [ "tools/call:conversations_history", "tools/call:chat_postMessage:approve" ], "roles_groups": ["Support"] }, { "name": "block_general_channel", "authorized": false, "actions": ["tools/call:chat_postMessage"], "roles_groups": ["*"], "condition": { "match": { "all": { "of": [ { "expr": "request.resource.attr.channel == \"general\"" } ] } } } } ] } ``` > [!NOTE] > > For a comprehensive guide, see [Manage Access Policies](/how-tos/manage-policies). # Disable Policy Source: https://docs.barndoor.ai/api-reference/policies/disablePolicy PUT /api/policy/disable # Disable Restriction Source: https://docs.barndoor.ai/api-reference/policies/disableRestriction PUT /api/policies/restrictions/disable/{restriction_name} # Enable Policy Source: https://docs.barndoor.ai/api-reference/policies/enablePolicy PUT /api/policy/enable # Enable Restriction Source: https://docs.barndoor.ai/api-reference/policies/enableRestriction PUT /api/policies/restrictions/enable/{restriction_name} # Get Filter Definitions Source: https://docs.barndoor.ai/api-reference/policies/getFilterDefinitions GET /api/v2/policies/filter-definitions Return filter categories for the policies list UI. Static filter options for status, plus dynamic filters for MCP servers and agents based on the organization's registry. # Get Policies Summary Source: https://docs.barndoor.ai/api-reference/policies/getPoliciesSummary GET /api/v2/policies/summary Return summary counts of policies by status. # Get Policy Source: https://docs.barndoor.ai/api-reference/policies/getPolicy GET /api/v2/policies/{policy_id} # List Policies Source: https://docs.barndoor.ai/api-reference/policies/listPolicies GET /api/v2/policies # List Policy Revisions Source: https://docs.barndoor.ai/api-reference/policies/listPolicyRevisions GET /api/v2/policies/{policy_id}/revisions List all revisions for a given policy with pagination. Uses the same authorization as get_policy - if a user can read a policy, they can view its revision history. Args: changes_summary: Include human-readable change descriptions in response # Reload Policy Cache Source: https://docs.barndoor.ai/api-reference/policies/reloadCache POST /api/reload-cache # Update Policy Source: https://docs.barndoor.ai/api-reference/policies/updatePolicy PATCH /api/v2/policies/{policy_id} Accepts a partial policy object. Send only the fields you are changing; `rules` is replaced wholesale when present, so include the complete rule set rather than a delta. Tool-call actions inside `rules[].actions` use the same two forms as on create — `tools/call:` for an outright grant and `tools/call::approve` to require user approval. See [Create Policy → Tool-call actions](/api-reference/policies/createPolicy#tool-call-actions). > [!NOTE] > > For a comprehensive guide, see [Managing Policies](/how-tos/manage-policies). # Validate Policy Source: https://docs.barndoor.ai/api-reference/policies/validatePolicy POST /api/v2/policies/validate Validate a policy before creation or update. Checks for duplicate names and overlapping MCP server/agent combinations. When exclude_policy_id is provided (edit mode), that policy is excluded from validation. # Acknowledge Policy Impact Source: https://docs.barndoor.ai/api-reference/policy/acknowledge-policy-impact /api-reference/openapi.yaml post /api/policy/v2/policies/{policy_id}/impacts/{impact_id}/acknowledge ``open`` -> ``acknowledged``. 404 if the impact doesn't exist (or belongs to another org/policy); 409 if it isn't ``open``. **Both** ``policy_id`` and ``impact_id`` are typed as UUIDs, so a malformed id in the URL 422s here rather than reaching the query and raising an unhandled ``asyncpg.DataError`` (=> 500) against a UUID column. This is deliberately stricter than ``admin_v2``'s plain-``str`` path-param convention. # Clone Policy Source: https://docs.barndoor.ai/api-reference/policy/clone-policy /api-reference/openapi.yaml post /api/policy/v2/policies/{policy_id}/clone Clone an existing policy, creating a new policy with the same configuration but with a modified name (appending " Copy") and DRAFT status. # Compare Policy Revisions Source: https://docs.barndoor.ai/api-reference/policy/compare-policy-revisions /api-reference/openapi.yaml get /api/policy/v2/policies/{policy_id}/revisions/compare Compare two revisions of a policy. Returns the before/after state, a diff of changes, change categories, and the union of resolved_refs from both endpoint revisions. The before/after are always normalized so before is the older revision. # Create Policy Source: https://docs.barndoor.ai/api-reference/policy/create-policy /api-reference/openapi.yaml post /api/policy/v2/policies Create a policy governing exactly one MCP server. A rule grants its `actions` to its `roles_groups`. Access is denied by default, so a tool no rule grants is already blocked — `authorized: false` is only for carving an exception out of a broader allow. Write ONE rule per `roles_groups` set — all of a principal's actions on one rule, with `:approve` carrying allow-vs-confirm. Example, reads free and writes confirmed: {"name": "Support tooling", "mcp_server_id": "3f7c…", "rules": [ {"name": "Support issue access", "authorized": true, "active": true, "actions": ["tools/call:list_issues", "tools/call:create_issue:approve"], "roles_groups": ["group:Support"]}]} One policy per (server, agent scope): a second ACTIVE policy over the same `mcp_server_id` and `application_ids` is refused with 409 naming the holder. Add rules to the existing policy instead, or scope the new one to specific `application_ids`. `validate_policy` reports this before you write. # Get Affected Policies Source: https://docs.barndoor.ai/api-reference/policy/get-affected-policies /api-reference/openapi.yaml get /api/policy/v2/policies/affected-by Preview policies that would be archived or revised by a cascade. Backs the AI agent / MCP server delete-confirmation modal so the user sees what's about to change before they confirm (BCP-1686 spec § "Policy-service endpoint"). Exactly one of ``agent_id`` / ``mcp_server_id`` must be supplied. # Get Filter Definitions Source: https://docs.barndoor.ai/api-reference/policy/get-filter-definitions /api-reference/openapi.yaml get /api/policy/v2/policies/filter-definitions Return filter categories for the policies list UI. Static filter options for status, plus dynamic filters for MCP servers and agents based on the organization's registry. # Get Policies Summary Source: https://docs.barndoor.ai/api-reference/policy/get-policies-summary /api-reference/openapi.yaml get /api/policy/v2/policies/summary Return summary counts of policies by status. # Get Policy Source: https://docs.barndoor.ai/api-reference/policy/get-policy /api-reference/openapi.yaml get /api/policy/v2/policies/{policy_id} # Get Policy Counts By Agent Source: https://docs.barndoor.ai/api-reference/policy/get-policy-counts-by-agent /api-reference/openapi.yaml get /api/policy/v2/policies/counts-by-agent Return the number of policies associated with each agent. Unscoped policies (applying to all agents) are counted separately. # Get Policy Impacts Summary Source: https://docs.barndoor.ai/api-reference/policy/get-policy-impacts-summary /api-reference/openapi.yaml get /api/policy/v2/policy-impacts/summary Badge counts: ``{policy_id: {breaking, review, info}}``, archived excluded. # Get Policy Impacts Summary By Kind Source: https://docs.barndoor.ai/api-reference/policy/get-policy-impacts-summary-by-kind /api-reference/openapi.yaml get /api/policy/v2/policy-impacts/summary/by-kind Rollup line counts: ``{policy_id: {change_kind: live_count}}``, archived excluded. Sibling of ``/policy-impacts/summary`` grouped by ``change_kind`` instead of severity — kept as a separate route rather than a widened ``/summary`` response because ``PolicyImpactSeverityCounts`` uses ``extra="allow"`` to surface unrecognised severities, and a structural ``kinds`` key there would be indistinguishable from one. ``change_kind`` is tool-router's open vocabulary, so kinds are not zero-filled: only kinds with live rows appear. # Get Policy Revision Source: https://docs.barndoor.ai/api-reference/policy/get-policy-revision /api-reference/openapi.yaml get /api/policy/v2/policies/{policy_id}/revisions/{revision_id} Return a single policy revision by ID, scoped to the given policy. # List Impacts For Policy Source: https://docs.barndoor.ai/api-reference/policy/list-impacts-for-policy /api-reference/openapi.yaml get /api/policy/v2/policies/{policy_id}/impacts Every impact on one policy, newest first — the policy detail view's list. Unlike the org-wide list, resolved rows are NOT excluded by default: this is the history view, with resolved rows collapsed client-side. Archived policies are still excluded (:class:`PolicyImpactService`'s ``_base_query`` backs both this and the org-wide list identically) — an archived policy's detail page must not surface flags the org view is hiding. **Capped, and the cap is not an error.** At most :data:`~policy_service.services.policy_impact.PER_POLICY_LIST_CAP` rows are returned, newest first. Resolved impacts are kept indefinitely as an audit trail and each carries a non-trivial ``detail`` blob, so an uncapped response would grow without limit. Truncation is therefore possible and is NOT signalled — this is a detail view where the newest rows are what matter. For full history, page the org-wide ``GET /policy-impacts?policy_id=`` instead. # List Policies Source: https://docs.barndoor.ai/api-reference/policy/list-policies /api-reference/openapi.yaml get /api/policy/v2/policies # List Policy Impacts Source: https://docs.barndoor.ai/api-reference/policy/list-policy-impacts /api-reference/openapi.yaml get /api/policy/v2/policy-impacts Org-wide impact list. Serves the ACC org view and the server/snapshot revisions page (hence the ``mcp_server_id`` / ``snapshot_id`` filters on what is otherwise an org-wide list). Archived policies are excluded by :class:`PolicyImpactService`'s join on ``policy.status``. # List Policy Revisions Source: https://docs.barndoor.ai/api-reference/policy/list-policy-revisions /api-reference/openapi.yaml get /api/policy/v2/policies/{policy_id}/revisions List all revisions for a given policy with pagination. # List Server Policy Revisions Source: https://docs.barndoor.ai/api-reference/policy/list-server-policy-revisions /api-reference/openapi.yaml get /api/policy/v2/policy-revisions List policy revisions across every policy scoped to `mcp_server_id` in the caller's organization, newest first, cursor-paginated (BCP-4458). Replaces the client's old per-policy revisions fan-out (one call per policy, capped at 20 policies): this is one server-scoped call whose `version_number` values are computed over each policy's whole revision history before `since`/`cursor` filtering, so they stay stable across pages. # Update Policy Source: https://docs.barndoor.ai/api-reference/policy/update-policy /api-reference/openapi.yaml patch /api/policy/v2/policies/{policy_id} Update a policy. Sending `rules` REPLACES the entire rule list. There is no "add a rule" operation. To add one, read the policy first and send every existing rule back alongside the new one — sending only the new rule deletes the others, and the call still returns 200 with a policy that looks perfectly healthy. Omit `rules` entirely to change only metadata. Verify afterwards rather than assuming: `GET /v2/policies/{policy_id}/revisions` lists what each change actually did, and `compare_policy_revisions` diffs two of them. A revision summarising removals you did not intend is how you catch a partial send — and it is also how you recover, since the diff records what was taken out. Other fields are a partial update: omitted ones are left alone. `mcp_server_id` is immutable — rules reference server-specific tool actions, so retargeting is a new policy, not an edit. # Validate Policy Source: https://docs.barndoor.ai/api-reference/policy/validate-policy /api-reference/openapi.yaml post /api/policy/v2/policies/validate Validate a policy before creation or update. Checks for duplicate names and overlapping MCP server/agent combinations. When exclude_policy_id is provided (edit mode), that policy is excluded from validation. # Validate Rule Source: https://docs.barndoor.ai/api-reference/policy/validate-rule /api-reference/openapi.yaml post /api/policy/v2/policies/rule/validate Validate a single policy rule for correctness. Validates CEL expression syntax, undefined variables, action format, and role/group format. Returns 204 No Content if valid, or 422 with Pydantic validation errors if invalid. # Authenticate an already-registered server Source: https://docs.barndoor.ai/api-reference/registry/authenticate-an-already-registered-server /api-reference/openapi.yaml post /api/registry/v1/servers/{server_id}/connect Authenticates the caller against an MCP server that is ALREADY registered in this organization. It does not add a server: a `server_id` that is not yet registered returns 404, and a catalog (directory) id is never valid here — that ordering is the usual reason this endpoint 404s. Registering a server is not available as a tool; an operator adds it in the console first. For OAuth providers it returns an authorization URL for the user to visit. For non-OAuth providers (api_key, bearer_token, basic_auth, generic) credentials go in the request body — prefer a server registered with managed credentials so no secret passes through the caller at all, and never solicit one in a chat transcript. `as_service: true` connects the tenant's shared service account rather than the calling user, which is what a server needs before it can be published, and requires an organization admin. # Delete Connection Source: https://docs.barndoor.ai/api-reference/registry/delete-connection /api-reference/openapi.yaml delete /api/registry/v1/servers/{server_id}/connection Delete the current user's (or service-account) connection to this server. # Get Active Application Ids Source: https://docs.barndoor.ai/api-reference/registry/get-active-application-ids /api-reference/openapi.yaml get /api/registry/v1/applications/active-ids Return org-scoped, non-soft-deleted application IDs (uncapped, BCP-2766). # Get Active Server Directory Ids Source: https://docs.barndoor.ai/api-reference/registry/get-active-server-directory-ids /api-reference/openapi.yaml get /api/registry/v1/server-directory/active-ids Return alive (non-soft-deleted) directory IDs visible to the org (BCP-3308). Mirrors ``GET /servers/active-ids`` (BCP-2766): backs the audit-history "Deleted" badge. Directory audit events store the directory id in the ``mcp_server_id`` field, so the frontend unions these ids with the server active set when tagging audit dimensions. # Get Active Server Ids Source: https://docs.barndoor.ai/api-reference/registry/get-active-server-ids /api-reference/openapi.yaml get /api/registry/v1/servers/active-ids Return org-scoped server IDs in a single uncapped response (BCP-2766). Backs active-set lookups (audit-history deleted tagging, dashboard denominator) that previously paginated/capped GET /servers at 100 items per page. # Get Application Source: https://docs.barndoor.ai/api-reference/registry/get-application /api-reference/openapi.yaml get /api/registry/v1/agents/{application_id} # Get Application Counts Source: https://docs.barndoor.ai/api-reference/registry/get-application-counts /api-reference/openapi.yaml get /api/registry/v1/agents/counts Get counts of applications by agent type. # Get Application Directory Source: https://docs.barndoor.ai/api-reference/registry/get-application-directory /api-reference/openapi.yaml get /api/registry/v1/agent-directory/{application_directory_id} # Get Connection Source: https://docs.barndoor.ai/api-reference/registry/get-connection /api-reference/openapi.yaml get /api/registry/v1/servers/{server_id}/connection Get the current user's (or service-account) connection status for this server. # Get Mcp Server Source: https://docs.barndoor.ai/api-reference/registry/get-mcp-server /api-reference/openapi.yaml get /api/registry/v1/servers/{server_id} Return details for an individual MCP server including connection status and base URL. ``server_id`` is the UUID from ``GET /v1/servers`` list rows. The response includes derived fields computed per request — ``connection_status``, ``url``, and the ``attention_tier`` / ``publish_blockers`` publish-state pair — alongside the stored record. # Get Mcp Server By Slug Source: https://docs.barndoor.ai/api-reference/registry/get-mcp-server-by-slug /api-reference/openapi.yaml get /api/registry/v1/servers/by-slug/{slug} Return details for an individual MCP server by slug. Uses the slug and organization ID from auth context to fetch the server. This is useful for fetching server details when you only have the service name/slug. # Get Mcp Servers Source: https://docs.barndoor.ai/api-reference/registry/get-mcp-servers /api-reference/openapi.yaml get /api/registry/v1/servers # Get Server Directory Source: https://docs.barndoor.ai/api-reference/registry/get-server-directory /api-reference/openapi.yaml get /api/registry/v1/server-directory/{server_directory_id} # List Applications Source: https://docs.barndoor.ai/api-reference/registry/list-applications /api-reference/openapi.yaml get /api/registry/v1/agents List applications with pagination. # List Applications Directory Source: https://docs.barndoor.ai/api-reference/registry/list-applications-directory /api-reference/openapi.yaml get /api/registry/v1/agent-directory List application directories with pagination. # List Server Directory Source: https://docs.barndoor.ai/api-reference/registry/list-server-directory /api-reference/openapi.yaml get /api/registry/v1/server-directory List server directories with pagination. # Publish Mcp Server Source: https://docs.barndoor.ai/api-reference/registry/publish-mcp-server /api-reference/openapi.yaml post /api/registry/v1/servers/{server_id}/publish BCP-3039 — one-way publish gate. Publishing makes a server discoverable in end-user listings (``published_at IS NOT NULL``). It is deliberately one-way: there is no unpublish, and later operational-state changes never hide a published server — taking a server out of service means deactivating its policies. Preconditions (422 when unmet): - the server is operationally available (``server_available_expr``: status=active AND requires_auth=false / embedded-local source / a "connected" tenant service-account connection), and - it has at least one ACTIVE policy (verified against policy-service with the caller's own token; 403 when policy-service refuses the caller, 503 when it can't answer). Re-publishing an already-published server is an idempotent no-op success. Audit: every rejected publish of an existing server (403/422/503) and every state-changing success emit an event; the idempotent no-op does not, so the audit trail means "a publish happened". # Register Application Source: https://docs.barndoor.ai/api-reference/registry/register-application /api-reference/openapi.yaml post /api/registry/v1/agents # Report Connection Auth Error Source: https://docs.barndoor.ai/api-reference/registry/report-connection-auth-error /api-reference/openapi.yaml post /api/registry/v1/servers/{server_id}/connection/auth-error Report that the provider rejected the stored credential for the calling user's connection. Called by tool-router when an upstream provider rejects a served OAuth token mid-use. The service first forces one refresh; if it succeeds the connection stays connected. The caller's connection flips to a reconnect prompt only when the provider refuses that refresh (the authorization is then dead for every connection using it), or when no refresh token exists and the token is older than the service's cooldown, which changes only the caller's own connection. A caller-supplied ``rejected_fingerprint`` matching the stored token on a credential with no refresh token skips the cooldown and retires the shared authorization, which also affects service-account connections that borrow it. A report that cannot be acted on (a just-issued token, a lost refresh race, a transient failure) changes nothing. The response is always 204 once the connection is found and never says which outcome occurred. # Unregister Application Source: https://docs.barndoor.ai/api-reference/registry/unregister-application /api-reference/openapi.yaml delete /api/registry/v1/agents/{application_id} # Update Application Llm Gateway Source: https://docs.barndoor.ai/api-reference/registry/update-application-llm-gateway /api-reference/openapi.yaml patch /api/registry/v1/agents/{application_id}/llm-gateway # Update Application Write Confirmations Source: https://docs.barndoor.ai/api-reference/registry/update-application-write-confirmations /api-reference/openapi.yaml patch /api/registry/v1/agents/{application_id}/write-confirmations # Create MCP Server Source: https://docs.barndoor.ai/api-reference/servers/createServer POST /api/servers Create a new MCP server instance from a server directory template. The server will be created in `pending` status until OAuth credentials are configured. If `client_id` and `client_secret` are provided, the server will be set to `active` status. # Delete Server by Id Source: https://docs.barndoor.ai/api-reference/servers/deleteServer DELETE /api/servers/{server_id} Delete an MCP server and all associated connections. This will: - Remove all user connections to this server - Clean up stored OAuth credentials - Delete the server configuration For custom server types, this will also delete the associated server directory. # Get Server by Id Source: https://docs.barndoor.ai/api-reference/servers/getServer GET /api/servers/{server_id} Get detailed information about a specific MCP server. Returns extended information including MCP URL if available. # List MCP servers Source: https://docs.barndoor.ai/api-reference/servers/listServers get /api/servers List all MCP servers available to the caller's organization. Returns paginated results with server details including connection status. # Update MCP Server Source: https://docs.barndoor.ai/api-reference/servers/updateServer PUT /api/servers/{server_id} Update an existing MCP server's configuration. You can update the name, slug, OAuth credentials, and metadata. If updating OAuth credentials, provide the actual values (not obfuscated). # SSE server proxy endpoint Source: https://docs.barndoor.ai/api-reference/sse/proxySSERequest get /sse/{mcp_server_name} Server-Sent Events proxy endpoint for real-time streaming communication with third-party servers. This endpoint provides dedicated SSE streaming capabilities separate from the MCP protocol, allowing for custom event streaming and real-time data flows. ## Usage - **SSE Streaming**: Optimized for `text/event-stream` communication - **Real-time Events**: Custom event types and data streaming - **Session Management**: Include `x-mcp-session-id` header for session tracking ## Authentication Flow 1. User must first connect to the server via `/api/servers/{server_id}/connect` 2. Complete OAuth flow for the third-party service 3. Use this endpoint for real-time event streaming with automatic credential injection # Clear an export's delivery destination and its stored credentials Source: https://docs.barndoor.ai/api-reference/system-management/clear-an-exports-delivery-destination-and-its-stored-credentials /api-reference/openapi.yaml delete /api/system-management/public/v1/exports/{orgId}/{exportType}/destination # Configure an export's delivery destination Source: https://docs.barndoor.ai/api-reference/system-management/configure-an-exports-delivery-destination /api-reference/openapi.yaml put /api/system-management/public/v1/exports/{orgId}/{exportType}/destination # Disable an export and stop delivery Source: https://docs.barndoor.ai/api-reference/system-management/disable-an-export-and-stop-delivery /api-reference/openapi.yaml post /api/system-management/public/v1/exports/{orgId}/{exportType}/pause # Enable an export and resume delivery Source: https://docs.barndoor.ai/api-reference/system-management/enable-an-export-and-resume-delivery /api-reference/openapi.yaml post /api/system-management/public/v1/exports/{orgId}/{exportType}/start # Get an export's delivery destination Source: https://docs.barndoor.ai/api-reference/system-management/get-an-exports-delivery-destination /api-reference/openapi.yaml get /api/system-management/public/v1/exports/{orgId}/{exportType}/destination # Get one audit log export Source: https://docs.barndoor.ai/api-reference/system-management/get-one-audit-log-export /api-reference/openapi.yaml get /api/system-management/public/v1/exports/{orgId}/{exportType} # Get the AWS principal and external ID to trust for iam_role auth Source: https://docs.barndoor.ai/api-reference/system-management/get-the-aws-principal-and-external-id-to-trust-for-iam_role-auth /api-reference/openapi.yaml get /api/system-management/public/v1/exports/{orgId}/{exportType}/destination/aws-trust-info # List an organization's audit log exports Source: https://docs.barndoor.ai/api-reference/system-management/list-an-organizations-audit-log-exports /api-reference/openapi.yaml get /api/system-management/public/v1/exports/{orgId} # Probe an export's destination and persist the result Source: https://docs.barndoor.ai/api-reference/system-management/probe-an-exports-destination-and-persist-the-result /api-reference/openapi.yaml post /api/system-management/public/v1/exports/{orgId}/{exportType}/destination/health-check # Update an export's delivery settings Source: https://docs.barndoor.ai/api-reference/system-management/update-an-exports-delivery-settings /api-reference/openapi.yaml patch /api/system-management/public/v1/exports/{orgId}/{exportType}/settings Partial update: omitted fields keep their current value. # Adding MCP Servers Source: https://docs.barndoor.ai/how-tos/add-an-mcp-server Step-by-step guide to adding a new MCP server in Barndoor. One of the first steps to getting started with Barndoor is to **register your MCP servers** so so its **tools can be discovered** and fine-grained access control **policies can be applied** to them. You can add servers that are built and hosted by Barndoor, curated by Barndoor but hosted by third parties, or hosted internally on your own infrastructure. ![MCP Server Activation](https://mintcdn.com/barndoor/S5FnpNSAJTsuXc13/images/mcp-server-activation-flow.png?fit=max\&auto=format\&n=S5FnpNSAJTsuXc13\&q=85\&s=8275966108cfd8d1f4029078334f1379) ## Before You Begin Before getting started with adding an MCP server in Barndoor, you’ll need: * A Barndoor account with **admin privileges** * Authentication credentials from your MCP provider (an OAuth Client ID/Secret, an API key, or another credential type, depending on the server) > [!TIP] > > To learn how to authenticate Barndoor to a specific MCP provider, visit the [MCP Servers Catalog](/mcp-servers/servers), select an MCP server, and follow the **Setup Instructions**. **For example:** [here](/mcp-servers/atlassian#setup-instructions) is how to connect Atlassian's Rovo MCP server. ## Understanding MCP Server Types Barndoor's MCP server catalog (**Admin > MCP Servers > Add MCP Server**) organizes servers into three categories, filterable via the **Custom / Barndoor / Official** chips at the top of the catalog: | Server Type | Description | | :- | :- | | **Barndoor Managed** | Secure, turnkey MCP servers built, managed, and hosted by Barndoor. | | **Official (Remote)** | Remotely hosted third-party MCP servers offered by the SaaS/platform provider. | | **Custom Servers** | Any remotely hosted MCP servers created/registered by your organization. | Use the search box to find a specific service by name, or the **Categories** filter to browse by use case. > [!NOTE] > > You are allowed to create multiple instances of MCP servers within Barndoor. ## Adding a Barndoor or Official server 1. Navigate to **Admin > MCP Servers** and click **Add MCP Server**. 2. Find your target service in the catalog and click its **Add MCP Server** button. 3. In the **Configure MCP Server Instance** dialog: * Confirm or edit the **MCP Server Name** (prefilled with the connector's name). * Optionally set a **Slug** — a URL-friendly identifier. If left blank, it's auto-generated from the name. * Provide **connection credentials** (OAuth, API Key, etc. - the type of credential differs by server). * If the provider supports OAuth Dynamic Client Registration, you can click **Register Client** to automatically register and fill in a Client ID and Secret. 4. Click **Configure MCP Server**. ## Adding a custom server > [!WARNING] > > Review any custom MCP server carefully with your security team before registering it. Barndoor applies your access-control policies to it but doesn't vet third-party code on your behalf. Custom servers go through a short configuration wizard. 1. Navigate to **Admin > MCP Servers > Add MCP Server** and click the **Add New** tile ("Create or connect a new custom MCP server"). 2. **Add Custom MCP Server** — choose the **MCP Server Source**: * **Internal** — hosted and managed within your own infrastructure * **3rd Party** — hosted externally by an outside provider * Enter the **MCP Server URL**, then click **Add MCP Server**. 3. **Add Custom MCP Server Details** — fill in: * **Name** (prefilled from the URL) and an optional **Description** * An optional **Icon** (JPG, PNG, GIF, or WebP, up to 10MB) * **MCP Server URL** (carried over from step 2; Barndoor attempts to auto-discover OAuth metadata from it) * **Protocol** — Choose `MCP` (Streamable HTTP) or `SSE` (Server-Sent Events). (While SSE is supported, please note that it has been deprecated.) * **Authentication Type** — the type you choose determines which credential fields appear: * **OAuth** * **Issuer:** The unique URL of the authorization server for this MCP server. * **Authorization Endpoint:** The authorization server's endpoint URL where a user will be redirected to log in and grant consent. This can either be a relative path to the Issuer URL above, or an absolute (full) endpoint URL. * **Token Endpoint:** The authorization server's endpoint URL that Barndoor will use to exchange an authorization code for an access token. This can either be a relative path to the Issuer URL above, or an absolute (full) endpoint URL. * **Allow OAuth Override:** Allows the issuer (base URL) to be overridden per instance of this MCP server. * **Scopes:** A list of OAuth scopes (permissions) that Barndoor will request during the authentication flow (e.g., "read:profile read:issues write:comments") * **Categories:** Select one or more categories for this MCP server which is used to improve server discovery. * **Additional Metadata (JSON):** Optional field of additional metadata to be passed between MCP clients and servers. * **API Key** — the key itself is supplied when configuring the instance. * **Bearer Token** — the token itself is supplied when configuring the instance. * **Basic Auth** — username and password credentials are supplied when configuring the instance. * **Generic** — define custom **Credential Fields** that users will need to provide when connecting. Each field is sent as an HTTP header. Fields can be edited in Form View or as raw JSON. * Optional **Categories**, which are used to improve server discovery. * Click **Update MCP Server** to continue. 4. **Configure MCP Server Instance** — name the instance, optionally set a slug, and, depending on the authentication type chosen in step 3, supply the appropriate credential values. Click **Configure MCP Server**. 5. **Connect a Service Account** — click **Connect MCP Server** to authorize the connection and let Barndoor discover the server's tools. > [!TIP] > > If a server uses OAuth, confirm its OAuth client allowlists your Barndoor hostname as a valid redirect URI, or the connection step may fail with a redirect URI error. ## Publishing an MCP server Successfully connecting a server doesn't make it usable right away. A newly connected server sits in a **Pending Publish** state: it's visible to admins, but end users can't see it or connect to it yet. > [!NOTE] > > Publishing requires at least one policy to be configured first - there's no way to publish an unpoliced server. To make a server available to end users: 1. Configure at least one **access control policy** for the server in the **Access Control Center**, defining which AI agents and/or users are allowed to use it. 2. Once a policy is in place, open the server (from the `⋮` menu on the MCP Servers list or its detail page) and choose **Publish**. 3. Publishing the server makes it visible to end users, who can then connect to it themselves. ## Managing an existing MCP server From the MCP Servers list, each row has a `⋮` menu with: * **View Details** — opens the server's detail page (actions taken, AI agent usage, tool calls, and an activity log) * **Manage Access** — configure which AI agents and users can use the server * **Publish** — makes the server visible and connectable to end users * **Edit** — update the server's configuration * **Delete** — permanently remove the server (this cannot be undone; Barndoor will warn you if any access policies still reference it) A server's status badge reflects where it is in this lifecycle: * **Pending Publish** (connected, but not yet visible to end users) * **Pending Connection** or **Pending Credentials** (setup not finished) * **Connection Error** (setup failed or credentials need attention) * **Available** (connected, policied, and published) > [!TIP] > > A Pending Connection or Error status usually means the connection setup needs to be resumed or its credentials re-entered — use **Resume Setup** from the list, or **Edit** from the MCP Server detail page. # Adding Your Agents Source: https://docs.barndoor.ai/how-tos/agent-profile/add-an-agent Step-by-step guide for adding an agent in Barndoor. Adding your agents to Barndoor **Prerequisites** * Admin privileges in your Barndoor organization. * Application details for your agent, including application type (guidance below) and OAuth callback URL(s) ## Step-by-step guide 1. Go to **AI Agents**: [https://app.barndoor.ai/agents](https://app.barndoor.ai/agents). 2. Click **Add Agent** button (top-right).\ This opens the **Add AI agent** registration form. ![Add AI agent modal with fields for name, description, application type, and allowed logout URLs](https://mintcdn.com/barndoor/go_AIQEYFLJQKYJM/images/add-agent-modal2.png?fit=max\&auto=format\&n=go_AIQEYFLJQKYJM\&q=85\&s=7408f961bf7b1d5dc1eba6178b9d08a9) > Tip: If you don't see the button, ensure your user has admin access. ## Fill out the registration form 1. **Name**\ Clear, human-readable name (e.g., `Snowflake Assistant`, `Sales Ops Agent`). 2. **Description**\ Short sentence on what the agent does and which services it connects to. 3. **Agent Owner**\ Name of person or team that is responsible for the agent (optional) 4. **Owner Contact Information**\ Email address, slack channel, or other contact information for the Agent Owner (optional) 5. **Callback URLs**\* Enter one or more URLs where Barndoor should send callbacks after users sign in through your Identity Provider or authorize Barndoor to access an MCP server. 6. **Allowed Logout URLs**\ One or more URLs where users can be safely redirected after logging out (press **Enter** after each URL). When you're done, click **Register agent**. Upon successful agent creation, you'll be presented your agents credentials. These credentials are required for authenticating your application to make authorized requests to Barndoor operations. ## Your Agent Credentials ![Agent Credentials print out](https://mintcdn.com/barndoor/XeNGvf7i3-lwyztZ/images/agent-credentials.png?fit=max\&auto=format\&n=XeNGvf7i3-lwyztZ\&q=85\&s=5870c465469b11cf08d603c166038488) ## What happens next? * Your new agent appears in the **All Agents** list. * From there you can: * Configure **access policies** for the agent by adding the agent to the scope of MCP servers such as Snowflake, Salesforce, and Notion in Access Control Center. * For Machine to Machine or Autonomous Agents, you can directly connect them to MCPs with service account credentials or LLM models with their virtual keys. See [AgentProfiles](https://docs.barndoor.ai/how-tos/agent-profile/overview) * Manage **auth settings** and rotate credentials if your application type requires it. * Monitor **Active users** and **Monitored actions** over time. **Next step:** Create an [access control policy](https://docs.barndoor.ai/how-tos/manage-policies) for the agent to fine-tune which tools it can use and define any exception conditions that should limit its behavior. # Agent Profiles Source: https://docs.barndoor.ai/how-tos/agent-profile/overview Configuring agents that operate with their own access credentials to MCPs and LLMs and provides visibility to what your agents are doing and what their models costs are. ## Overview ![AgentProfile: one record covering data access policies, per-agent spend, LLM access, budget guardrails, MCP access, and human manager](https://mintcdn.com/barndoor/GZbbBabC4MisXQDA/images/agent-profile/agent_profile_overview.png?fit=max\&auto=format\&n=GZbbBabC4MisXQDA\&q=85\&s=e9bb3aa3be0b586ece9396c1318dec5d) Every agent in Barndoor has an **AgentProfile,** a single record where your agents may be registered and used for enabling access controls. It may be a commercial agents such as Anthropic Claude, OpenAI ChatGPT, Codex, Gemini, Cursor and so on. Or it may be custom developed agents. For your custom agents, **AgentProfile** may be further used for configuration and ongoing management, especially in cases where the agent is autonomous and you utilize both Barndoor's LLM gateway and MCP gateway. You may configure the **AgentProfile** with the virtual keys it needs to make model API calls as well as grant it specific credentials, such as services account credentials, for the MCP's of systems it requires access to. By doing so, your **AgentProfile** ties together its access controls and credentials in one place, and provides visibility into it's ongoing AI token model costs, policy enforcement logs, error rates, and so on. > [!NOTE] > > This binds together the LLM Gateway and MCP Gateway product modules. AgentProfile is the central object for both governed tool traffic and LLM usage especially useful for custom agents. ## Configuring an Autonomous Agent with AgentProfile **To configure your autonomous agent:** 1. Select and open the agent from the **AI Agents** list. [https://app.barndoor.ai/agents](https://app.barndoor.ai/agents) 2. Select the Edit action to open the agent configuration modal 3. If the agent is to contain its own credentials to your MCP servers, enable the MCP Connections feature 4. If the agent is to contain its own LLM keys, enable the LLM Gateway Enabled feature From this point, configure access to tools the agent should have to in the [Access Control Center](https://app.barndoor.ai/policies). ### Deciding which tool calls need a human Whether an agent's write actions pause for approval is set per tool and per group in the policy that governs the agent, not on the agent itself. For an unattended agent that must run without a human in the loop, set its tools to **Always Allow**; where you want a person to confirm, use **Needs Approval**. Test thoroughly before letting an agent make system updates unattended. See [Granular Tool Use Confirmations](/how-tos/tool-confirmations) for how to set the three states, and how overlapping group grants resolve. ## Enabling MCP Server Connections on an agent Agents may be given its own service account credentials to the MCP Servers it needs access to. This is most valuable when creating custom agents that do not work explicitly on behalf of a user's own login credentials. On the Edit AI Agent modal, the **MCP Connections Enabled** toggle controls whether this feature is enabled for the agent. * **Default:** off for new agents. * **When enabled:** the agent can be given access credentials for each MCP server available in Barndoor. * **When disabled:** the agent must utilize MCP user login credentials found otherwise in your agent application or through the user connection flows in Barndoor My Apps. Once the feature is enabled, select the **Manage Connections** action from the agent details page. You are then able to add the MCP server connections that the agent is to have access to. ## Enabling LLM Gateway on an agent Most agents will interact with an AI model via the LLM gateway. If you are managing agentic access to models with Barndoor's LLM gateway, this process will bind a virtual key to the agent so you can manage what models it may access and track its token spend. On the Edit AI Agent modal, the **LLM Gateway Enabled** toggle controls whether this feature is enabled for the agent. * **Default:** off for new agents. * **When enabled:** the agent can be bound to LLM Gateway keys, and Barndoor starts routing and tracking its model calls. * **When disabled after keys are bound:** a confirmation dialog warns you that bindings will be preserved but disabled. Turning the toggle back on automatically reactivates them. ### Managing key bindings Once LLM Gateway is enabled, a **Manage keys** action appears on the agent detail page kebab menu (`⋮`). It opens a dedicated screen listing keys you're authorized to bind or you may provision a new key. An agent may have more than one model key, but each key may only be bound to a single agent. #### Bind a key Keys that have been created already may be bound to the agent if they have not been used with other agents. #### Creating a key from this screen **Create new key** opens a key-creation form. The resulting key is automatically bound to the current agent as part of the same action. #### Managing an existing key binding Keys may be unbound from an agent through the **Unbind** button. All event history is preserved against the agent, but new activity using the key will not be associated to the agent. Keys may be subsequently bound to a new or existing agent. # Lock Down Claude Enterprise to One Barndoor URL Source: https://docs.barndoor.ai/how-tos/claude-enterprise-barndoor-universal-url How to configure Claude with Barndoor to manage the MCP access of your organization's users. If you are a Claude Team or Enterprise admin, the Barndoor ToolIQ MCP simplifies your users' experience accessing your organization's business systems while giving IT the access-control and governance tooling to ensure AI is adopted safely. Instead of configuring, exposing, and managing a separate connector MCP for every system your organization uses — and training users on when to enable or disable each one — you configure a single Barndoor ToolIQ URL and let the Barndoor platform handle all the downstream access control and interactions. Your users then connect through that single entry point, while Barndoor decides which MCP servers, tools, and policies apply to them at runtime. > [!NOTE] > > **Best For**: Enterprise teams that want one controlled Claude connector, centralized policy enforcement, and a simpler rollout and experience for users. ## What This Achieves With this setup: * Claude Enterprise admins add one Barndoor connector to the Claude organization * Claude users connect to the single connector instead of needing to select individual app connectors per prompt, command, or skill * Barndoor controls which MCP servers and tool calls are available by user, group or role * Fine-grained access policies are enforced in Barndoor * New MCP servers and policy changes can be rolled out via Barndoor without requiring any change in Claude ## Before You Begin Before setting this up, make sure you have: * Claude Enterprise owner or admin access with permission to manage organization connectors * Your Barndoor ToolIQ MCP URL from the [Barndoor AI Client Setup](https://app.barndoor.ai/settings/ai-client-setup) page * At least one registered Barndoor agent * At least one connected MCP server in Barndoor * Production policies prepared or in draft for the users and agents you plan to roll out > [!NOTE] > > This guide assumes you want Claude users to enter through one Barndoor-controlled MCP endpoint. The governance model lives in Barndoor, so Claude stays simple while Barndoor handles server access, policy enforcement, and auditability. ## Step 1: Prepare Barndoor First Before touching Claude, confirm the Barndoor side is ready. **Barndoor readiness checklist** * Your production MCP servers are registered and connected * The Barndoor ToolIQ URL is available in your setup page * The correct Barndoor agent is registered * Policies are created in `DRAFT` or `ACTIVE` as appropriate * Tool access has been reviewed for the MCP servers included in launch * Test users or pilot users are identified If these pieces are not in place first, Claude users may connect successfully but see the wrong tools or fail policy checks later. References: * [Registering MCP Servers](/how-tos/add-an-mcp-server) * [Adding Your Agents](/how-tos/agent-profile/add-an-agent) * [Managing Policies](/how-tos/manage-policies) ## Step 2: Copy the Barndoor ToolIQ URL Go to your Barndoor AI Client Setup page and copy the ToolIQ MCP endpoint for your organization. This will be the single connector URL you want Claude Enterprise to expose to users. > [!TIP] > > Do not create one Claude connector per downstream system unless you have a special exception. The point of this pattern is to centralize Claude access behind one Barndoor-controlled MCP. ## Step 3: Add the Connector in Claude Enterprise In Claude Enterprise, the organization owner adds the connector once for the whole organization. **1. Open Claude Organization Settings** In Claude, go to **Organization Settings > Connectors**. **2. Add Custom Connector** Click **Add custom connector**. **3. Name the Connector** Give it a recognizable name, such as **Barndoor**. **4. Enter the Barndoor ToolIQ URL** Paste your Barndoor MCP URL, for example: ```text theme={null} https://your-org.platform.barndoor.ai/mcp ``` You won't need to configure any Claude-side OAuth credentials — only the Barndoor URL is required. **5. Save the Connector** Save the connector so it becomes available to your Claude organization. At this point, Claude has one approved enterprise connector, and that connector points to Barndoor rather than directly to a single downstream MCP server. ## Step 4: Expose the Connector to Claude Org Users After the owner adds the connector, Claude users can connect to it individually. **1. Have Users Open Claude Settings** Users go to **Settings > Connectors** in Claude. **2. Locate the Organization Connector** Users find the Barndoor connector that was added by the Claude Enterprise admin. It will appear under the organization connectors section, distinct from any personal or directory connectors. **3. Connect and Authenticate** Users click **Connect** and complete the authentication flow to Barndoor. **4. Begin Using Claude with Barndoor** Users start a new Claude conversation with the approved Barndoor connector enabled. > [!NOTE] > > Users are connecting to one Claude-approved Barndoor entry point. They are not managing separate Salesforce, Slack, Notion, Snowflake, etc. connectors inside Claude. ## Step 5: Validate the Runtime Experience Before broad rollout, test the connector with pilot users. The pilot users should have the "User" role in Claude. **Claude Enterprise validation checklist** * Confirm the Claude org sees only the approved Barndoor connector * Confirm users cannot add custom connectors in their customization settings * Confirm users can connect successfully * Confirm the expected Barndoor-managed tools are exposed in Claude * Confirm that for a system with both a Barndoor route and a native connector, Claude chooses the Barndoor route * Confirm tools not allowed by policy do not appear or are denied correctly * Confirm at least one allowed workflow succeeds end to end * Confirm at least one denied workflow is blocked correctly * Confirm the enforcement result is visible in Barndoor logs References: * [Go-Live Checklist](/how-tos/go-live-checklist) * [Managing Policies](/how-tos/manage-policies) Once pilot validation is complete: * Roll the connector out to the rest of the Claude organization * Keep the connector URL stable * Add or remove MCP server access in Barndoor as needed * Update policies in Barndoor without retraining users on connector setup * Use Barndoor logs and policy summary views to monitor adoption and enforcement This gives you a clean enterprise model: one Claude connector, one Barndoor ToolIQ URL, many governed downstream systems. ## Advanced Bypass Prevention settings ### Network-Level Enforcement The most reliable way to ensure all MCP traffic routes through Barndoor is to enforce it at the network layer. * Allowlist only your Barndoor production URL at the corporate firewall or proxy * Block outbound connections to known MCP endpoints for systems like Salesforce, Slack, Snowflake, and others that are governed by Barndoor * This ensures that even if a user adds a direct connector in Claude, the connection will fail at the network boundary This approach does not require changes inside Claude and applies uniformly across Claude.ai, Claude Desktop, and Claude Code. ### Managed MCP Configuration (Claude Desktop & Claude Code) ***Enterprise accounts only*** ![2026 06 11 12 26 24](https://mintcdn.com/barndoor/nmcgg5jX1RbUDOvB/images/2026-06-11_12-26-24.png?fit=max\&auto=format\&n=nmcgg5jX1RbUDOvB\&q=85\&s=acd562831d2286dbd8aff10dbc3dcc8a) ![2026 06 11 12 26 24](https://mintcdn.com/barndoor/nmcgg5jX1RbUDOvB/images/2026-06-11_12-26-24.png?fit=max\&auto=format\&n=nmcgg5jX1RbUDOvB\&q=85\&s=acd562831d2286dbd8aff10dbc3dcc8a) For organizations using **Claude Desktop** or **Claude Code**, a managed `managed-mcp.json` file takes *exclusive* control of MCP connections on the machine. This is the strongest client-side lockdown: it removes the user's ability to define their own MCP servers, parameters, paths, or environment variables entirely — not just filter them. #### Claude Desktop Create and deploy a `managed-mcp.json` file that defines only the Barndoor URL: ```json theme={null} { "mcpServers": { "barndoor": { "type": "http", "url": "https://your-org.platform.barndoor.ai/mcp", "description": "All MCP access through Barndoor" } } } ``` When this file is deployed, users cannot add, modify, or remove MCP servers through Claude Desktop. Only the servers defined in the managed config are available. #### Claude Code (absolute lockdown) A soft control — an allowlist or an organization instruction — can still be worked around. A determined user might point Claude at an unauthorized MCP server that happens to match a generic naming convention or allowlist string. To remove that possibility entirely on Claude Code, deploy a system-level `managed-mcp.json`. Drop a standalone `managed-mcp.json` file into the system config directory for the platform: | OS | Path | | - | - | | macOS | `/Library/Application Support/ClaudeCode/` | | Linux / WSL | `/etc/claude-code/` | | Windows | `C:\Program Files\ClaudeCode\` | Define the exact Barndoor endpoint, and only that: ```json theme={null} { "mcpServers": { "barndoor": { "type": "http", "url": "https://your-org.platform.barndoor.ai/mcp" } } } ``` Once this file is present, Claude Code switches to a strict "only load what is explicitly defined here" state: * Users cannot add, modify, or use any other MCP server — including plugin-provided servers. * Any user-defined local parameters, paths, or environment variables for those connections are discarded. * Native claude.ai connectors are **suppressed by default** (unless an admin explicitly sets `"allowAllClaudeAiMcps": true`), which directly closes the "Claude reaches for a native connector on its own" gap. Verify the deployment on a managed machine: ```bash theme={null} # Should list only the Barndoor server claude mcp list # Should fail with an enterprise-config error claude mcp add --transport http test https://example.com/mcp ``` > [!TIP] > > Roll `managed-mcp.json` out at fleet scale with your device management tooling — Jamf or a configuration profile on macOS, Group Policy or Intune on Windows. Anthropic publishes starter MDM templates at [github.com/anthropics/claude-code/tree/main/examples/mdm](https://github.com/anthropics/claude-code/tree/main/examples/mdm). Pair the rollout with spend-limit controls to cap API token consumption. > [!NOTE] > > Managed MCP configuration applies to the Claude Desktop and Claude Code clients on managed machines. It does not control connectors added through the Claude.ai web interface or mobile apps. Pair this with network controls (Option 1) for full coverage. ### Steer Claude with Organization Instructions This control targets the second bypass vector — Claude defaulting to a native connector even when Barndoor is enabled. Claude Team and Enterprise admins can set organization-wide custom instructions under **Organization Settings > Organization and Access**. Well-crafted instructions push Claude to route through Barndoor first and treat native connectors only as a fallback. > [!NOTE] > > **This is a behavioral steer, not a hard control.** Claude generally follows clear instructions, but model adherence is not guaranteed. Layer it on top of network or desktop enforcement (Options 1 and 2) rather than relying on it alone. In the Organization Instructions box, add language such as the below: ```text theme={null} When accessing any external service (Jira, Confluence, Slack, Salesforce, Google, etc.), always route calls through the connector using its execute_tool tool. Never call stock/native Claude connectors (e.g., Atlassian Rovo, Gmail, etc.) directly. Only fall back to a stock connector if is explicitly unavailable or returns a connection error. ``` Replace `` with the exact name of your Barndoor connector as it appears in Claude (for example, `Barndoor`). **Why this phrasing works:** * **Say "always," not "prefer."** Soft verbs like "prefer," "optimize by using Barndoor," or "use Barndoor when available" produce inconsistent results — sometimes Claude routes through Barndoor, sometimes it overrules and uses the native connector. Absolute "always" / "never" framing is far more reliable. * **Name the `execute_tool` tool explicitly.** Pointing Claude at the specific tool it should call removes ambiguity about *how* to route through Barndoor. * **Broaden the scope beyond one system.** Listing several services (Jira, Confluence, Slack, Salesforce, Google) rather than naming just one signals that the rule applies to all external access, not a single integration. * **Include explicit fallback language.** Telling Claude to fall back to a stock connector only when Barndoor is unavailable keeps it functional for systems Barndoor doesn't yet govern, instead of failing when a service isn't behind Barndoor. > [!TIP] > > Validate this in your environment as many organizations have additional text for Organization Instructions. Run a few prompts that target systems with both a Barndoor route and a native connector, and confirm Claude chooses Barndoor. Re-test after any major Claude model update, since steering behavior can shift between versions. ### Acceptable Use Policy For organizations that cannot enforce controls at the network or desktop level, pair your rollout with a clear acceptable use policy that: * Requires all Claude MCP connections to route through the approved Barndoor URL * Prohibits adding custom MCP connectors that connect directly to governed systems * Uses Barndoor enforcement logs to detect unexpected tool usage patterns ### Summary: Layered Defense For a complete lockdown, combine these approaches: | Layer | Control | Coverage | Strength | | - | - | - | - | | Network | Firewall allowlist for Barndoor URL only | Claude.ai, Desktop, Code, Mobile | Hard | | Client config | `managed-mcp.json` deployment | Claude Desktop & Claude Code | Hard | | Instructions | Org-wide custom instructions steering to Barndoor | Claude.ai, Code, workspace | Soft (best-effort) | | Policy | Acceptable use policy + Barndoor audit logs | All surfaces | Soft | ## Operational Best Practices * Use one Claude Enterprise connector per Barndoor environment, not per downstream app * Keep production users on the production Barndoor URL only * Test policy changes in `DRAFT` before activating them * Use Barndoor policies to control access instead of relying on user behavior inside Claude * Keep the Claude connector rollout narrow at first, then expand by user group or team * Use Barndoor enforcement logs to investigate denied or unexpected actions * Set organization instructions (**Settings > General**) to steer Claude toward the Barndoor connector, and re-validate the wording after major Claude model updates ## Troubleshooting > [accordion] Users can see the connector but not the expected tools > > Check Barndoor first. The most common causes are: > > * the wrong MCP servers are connected > * policies are still in `DRAFT` > * the user or agent is out of scope for the active policy > * the allowed tools were not enabled in the policy model > [accordion] Users can connect but actions are denied > > Review the active Barndoor policies and enforcement logs. Confirm whether the denial is expected and which policy caused it. > [accordion] Different teams want different systems through the same Claude connector > > Keep the single connector model and separate access in Barndoor through server selection, user identity, group mapping, and policies. Do not solve this by creating many duplicate Claude connectors unless you have a strict org-level reason. > [accordion] We want to add more MCP servers later > > You can keep the same Claude connector and expand the governed systems behind it in Barndoor, as long as you update server connectivity and policies before rollout. ## Next Steps * Review the [Go-Live Checklist](/how-tos/go-live-checklist) before organization-wide release * Finalize your v2 policies in [Managing Policies](/how-tos/manage-policies) * Use [Connect AI clients to Barndoor](/how-tos/connecting-barndoor-to-agents) for the broader multi-client connection guide # Connecting a Self-Hosted Model Source: https://docs.barndoor.ai/how-tos/connect-self-hosted-model Route traffic from your own model server — vLLM, Ollama, SGLang, or anything with an OpenAI-compatible API — through the Barndoor LLM Gateway, so in-house models get the same budgets, audit trail, and usage reporting as your hosted providers. If your model server speaks an OpenAI-compatible API, the Barndoor LLM Gateway can route to it. That covers [vLLM](https://docs.vllm.ai), [Ollama](https://ollama.com), [SGLang](https://docs.sglang.ai), [LM Studio](https://lmstudio.ai), llama.cpp's `llama-server`, and in-house wrappers alike. Connecting one is configuration on both sides — no adapter, no SDK, no code. What you get for doing it: every request to your own GPUs carries the same user identity, budget enforcement, rate limits, and audit record as a request to OpenAI or Anthropic. Your developers point at one endpoint and stop caring which side of the line a model lives on. And if your self-hosted capacity runs out, a model route can fall back to a hosted provider automatically — see [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns). > [!NOTE] > > This guide assumes you already have an admin account and know your way around **LLM Management**. If not, read [Using the LLM Gateway](/how-tos/use-llm-gateway) first. Only [Step 1](#step-1-start-your-server-so-barndoor-can-reach-it) differs between servers — everything after it is identical, because Barndoor sees the same OpenAI-compatible endpoint either way. ## Before you start You'll need three things: * A running model server, reachable over the network from Barndoor (see [Making the server reachable](#making-the-server-reachable) — this is the step that trips people up). * The API key you started that server with. * Admin access to **LLM Management** in the Barndoor portal. *** ## Step 1: Start your server so Barndoor can reach it Two defaults bite on nearly every model server, and both must change before Barndoor can use it: 1. **It listens on loopback only**, so nothing off that machine can connect. 2. **It requires no credential**, so anything that *can* connect may use your GPUs freely. > [tab] vLLM > > ```bash theme={null} > vllm serve Qwen/Qwen3-8B --host 0.0.0.0 --port 8000 --api-key > ``` > > > [!WARNING] > > > > **`--host` defaults to `127.0.0.1`.** Without `--host 0.0.0.0`, vLLM binds to loopback only and every connection from outside that machine — including Barndoor's — is refused. This is the single most common cause of a provider that saves as **Enabled · not serving**. > > `--api-key` turns on bearer-token authentication for the `/v1` paths. Treat the value as a secret: it is the only thing standing between your GPUs and anyone who can reach the port. Barndoor stores it encrypted and never exposes it to end users. > > **Flags worth knowing about:** > > > [accordion] --served-model-name — control the name clients use > > > > By default vLLM advertises the model under its Hugging Face repo id, so `vllm serve Qwen/Qwen3-8B` reports `Qwen/Qwen3-8B` in `/v1/models` and expects that exact string in the `model` field of a request. > > > > `--served-model-name qwen3-8b` overrides that with something friendlier. Whatever you choose, it must match what you enable in Barndoor in [Step 3](#step-3-enable-the-models). The gateway passes the name through untouched. > > > > A name without a `/` is also easier to call directly. The gateway reads everything before the first `/` in a request's `model` field as a provider name, so a model named `Qwen/Qwen3-8B` can only be called through a Model Route ([Step 4](#step-4-create-a-model-route)) or as `/Qwen/Qwen3-8B`. > > > [accordion] --enable-auto-tool-choice / --tool-call-parser — tool calling > > > > vLLM only emits OpenAI-style `tool_calls` when the server was started for it, and the correct parser depends on the model family: > > > > ```bash theme={null} > > vllm serve Qwen/Qwen3-8B --host 0.0.0.0 --api-key \ > > --enable-auto-tool-choice --tool-call-parser hermes > > ``` > > > > Without these flags the model will describe a tool call in prose instead of returning a structured one, and clients that expect tool use will appear to hang or loop. Barndoor passes `tools` through unchanged either way — it can't compensate for a server that wasn't started for tool calling. > > > [accordion] --reasoning-parser — separate reasoning from the answer > > > > For reasoning models, `--reasoning-parser qwen3` (or `deepseek_r1`, depending on the family) splits thinking tokens into their own field rather than leaving them inline in `content`. Recommended if your clients render responses directly to users. > > > [accordion] --max-model-len — cap context length > > > > Sets the maximum combined prompt and output length. If unspecified, vLLM derives it from the model config, which can be more than your GPUs can actually hold. Setting it explicitly turns an out-of-memory crash into a clean HTTP error that Barndoor reports and can fail over from. > [tab] Ollama > > Ollama binds `127.0.0.1:11434` by default. Override it with an environment variable rather than a flag: > > ```bash theme={null} > OLLAMA_HOST=0.0.0.0:11434 ollama serve > ``` > > Then pull whatever you intend to serve — `ollama pull llama3.2:1b`. The name in `/v1/models` is the Ollama tag (`llama3.2:1b`), not a Hugging Face repo id. > > > [!WARNING] > > > > **Ollama has no authentication and ignores the `Authorization` header entirely.** Any key is accepted, so anything that can reach the port can use your hardware. Barndoor still requires an API key on the provider, but Ollama will not check it. > > > > Do not expose Ollama beyond a trusted network on its own. Put a reverse proxy in front that enforces a bearer token on `/v1` and forwards to Ollama, and point Barndoor at the proxy. `brew services start ollama` is also not a substitute for the command above — the service definition doesn't set `OLLAMA_HOST`, so it binds loopback. > > Ollama is a strong fit for a shared on-prem box or an edge deployment. For multi-GPU production serving, vLLM or SGLang are the better targets. > [tab] Anything else > > The gateway needs three things from your server, whatever it is: > > * It **listens on an address Barndoor can reach** — usually meaning bind `0.0.0.0` rather than loopback. > * It **serves `/v1/models` and `/v1/chat/completions`** off a host root, in OpenAI format. > * It **accepts a bearer token** on those paths. If it can't, put a reverse proxy in front that does and point Barndoor at the proxy. > > SGLang, LM Studio, llama.cpp's `llama-server`, TGI and in-house FastAPI wrappers all satisfy the first two out of the box; check your server's own documentation for the bind address and auth flags, since those are the two that differ. Everything from [Step 2](#step-2-add-the-provider) onward is identical regardless. Confirm the server answers before you go anywhere near the portal: ```bash theme={null} curl -s http://:8000/v1/models -H "Authorization: Bearer " ``` You should get a JSON list containing the model id you intend to use. Run this from a *different* machine than the one hosting the server — running it locally passes even when the loopback-binding problem above is present, which is exactly how that problem stays hidden. *** ## Making the server reachable Barndoor connects to your server over the network like any other client, which means the gateway has to be able to route to it. This is independent of which server you run. > [tab] Barndoor SaaS > > A server on a private subnet is not reachable from `app.barndoor.ai`. You need to give it a routable address: > > * Put it behind your own load balancer or ingress with a public DNS name and TLS. > > * Restrict who can reach that address — an IP allowlist for Barndoor's egress addresses, or mutual TLS at your edge. `--api-key` is authentication, not network isolation. > > > [!WARNING] > > > > The certificate must be issued by a publicly trusted CA. The gateway validates TLS and will reject a self-signed or private-CA certificate — it surfaces as `could not reach upstream provider`, which reads like a connectivity problem rather than a certificate one. > [tab] Self-hosted Barndoor > > When Barndoor runs inside your own infrastructure, no public exposure is needed. Use whatever address the gateway can resolve — a Kubernetes service DNS name such as `http://vllm.ml.svc.cluster.local:8000`, or a private VPC address. > > Plain `http://` is accepted, so an internal deployment doesn't need certificates. *** ## Step 2: Add the provider In the Barndoor portal, go to **LLM Management → Providers**, click **Add Provider**, and on the **Custom Provider** card click **Add Custom**. Don't pick one of the named vendor cards. That's the right choice rather than a compromise. The named cards carry facts about a vendor's hosted endpoint: its URL, the models it serves, its per-token prices. None of those are knowable for a server you run yourself. The **Add Custom Provider** form asks for the things that actually vary and assumes nothing else, which is why it works the same for every server in [Step 1](#step-1-start-your-server-so-barndoor-can-reach-it). | Field | Value | | - | - | | **Name** | Anything recognizable, such as `vllm-prod` or `qwen-cluster`. It appears in usage reports, and it's the prefix callers use to address this provider's models directly (`vllm-prod/qwen3-8b`), so a short name without spaces is easiest. It must be unique in your organization. | | **Model Provider** | Fixed at **Custom (OpenAI-compatible)**. Not editable, and correct for any OpenAI-compatible server. | | **Block traffic on failed health check** | On by default, and recommended. See [health below](#how-barndoor-checks-the-connection). | | **Calculate token cost** | Turn off if you don't want to put a per-token price on self-hosted traffic, then set **Billing arrangement** to **Self-hosted**. See [Cost reporting](#cost-reporting-for-self-hosted-models). | | **Credentials** | Choose **+ Create new credentials** the first time. Later custom providers can reuse the same saved credentials. | | **Credential name** | A name for the saved credentials, such as `vLLM prod token`. They appear on the **Credentials** tab. | | **Base URL** | Your server's **host root**, for example `https://llm.internal.example.com` or `http://10.0.4.12:8000`. | | **API Key** | The value you passed to `--api-key`. | The base URL and key belong to the credentials, not the provider. To rotate the key or change the address later, edit the credentials on the **Credentials** tab. Every provider using them picks up the change, and a changed address triggers a fresh health check. > [!WARNING] > > **The base URL must not end in `/v1`.** > > vLLM's own documentation shows `http://localhost:8000/v1` because that's what OpenAI SDK clients expect. Barndoor is not an SDK client. It appends the version segment itself, requesting `{base_url}/v1/models` and `{base_url}/v1/chat/completions`, so a `/v1` on the end would produce `/v1/v1/…` on every request. Barndoor refuses to save it: the form shows `base_url must not end in '/v1'` along with the corrected URL to use instead. ### How Barndoor checks the connection On save, Barndoor runs a connectivity check: a `GET {base_url}/v1/models` with your key, which times out after 10 seconds. The result decides the status shown under the provider's name in the Providers list: | Check result | Status shown | Serves traffic? | | - | - | - | | The server answered with a model list and accepted the key | **Enabled** | Yes | | The server has no model list at that path (HTTP 404 or 405) | **Enabled** | Yes. Barndoor treats a missing model list as inconclusive, not as a failure | | Barndoor couldn't reach the server, the key was rejected, or the server returned another error | **Enabled · not serving** | No. Hover the status to see the reason | | Same failure, with **Block traffic on failed health check** turned off | **Enabled · health failing (override)** | Yes | A provider that is **not serving** stays suspended from routing until a later check passes. Checks run when you save the provider and when you choose **Re-check health** from the provider's row menu (⋮). Turn **Block traffic on failed health check** off only if your server sits behind something that blocks the model-list endpoint but serves completions fine. *** ## Step 3: Enable the models Right after you save the provider, the **Enable Models** dialog opens. A custom provider has no catalog to pick from, which is the honest state of affairs: only your server knows what it loaded. Type your model name into **Custom Models (optional)**. You can enter several names, separated by commas or new lines. If you skip this step, open the provider later and click **Add Models**. **The name must match what `/v1/models` reports, exactly.** Take it from the server rather than from memory: ```bash theme={null} curl -s https://llm.internal.example.com/v1/models \ -H "Authorization: Bearer " ``` That's the Hugging Face repo id (`Qwen/Qwen3-8B`) unless you set `--served-model-name`, in which case it's whatever you chose. Copy it character for character — `Qwen/Qwen3-8B` and `qwen3-8b` are different models as far as the gateway is concerned, and a mismatch surfaces only when the first request 404s. Models added this way carry a **Custom** badge. That's provenance, not a warning: you typed the name rather than picking it from the Barndoor catalog. It's also the first place to look when requests to a model fail, since a typo looks exactly like a real model until the first request. > [!NOTE] > > If your organization requires pricing before a model can be enabled, saving a self-hosted model fails with `Model '…' has no pricing`. Either add a rate under **Model Pricing** first, or turn off **Calculate token cost** on the provider. See [Cost reporting](#cost-reporting-for-self-hosted-models). *** ## Step 4: Create a model route A model you just enabled is callable only in `/` form, which ties clients to this one provider. Under **LLM Management → Model Routes**, click **Create Route**, enter the **Route Name** your developers will actually use (say `qwen3`), and point it at the model you just enabled. Developers then call it as `qwen3`. This indirection is what lets you move traffic later without touching a single client: repoint the route at a bigger GPU node, or add a hosted provider as a second target so requests spill over when your own capacity is saturated. *** ## Step 5: Verify the connection Test in layers. Each one isolates a different failure, and a green result at one layer tells you nothing about the next — so resist skipping ahead when something breaks. Almost every failed setup is diagnosed by finding the lowest layer that fails. **1. Your server is serving — on the server host** ```bash theme={null} curl -s http://localhost:8000/v1/models -H "Authorization: Bearer " ``` Proves the process is up and the weights finished loading. A large model can take minutes; until it's ready this returns nothing useful no matter how correct your configuration is. **2. It's reachable from somewhere else** Run the *same* curl from a different machine — your laptop, a bastion, anything that isn't the server host — against the exact address you plan to give Barndoor: ```bash theme={null} curl -s https://llm.internal.example.com/v1/models -H "Authorization: Bearer " ``` > [!WARNING] > > Do not skip this by testing on the server host. Loopback succeeds even when the server is bound to `127.0.0.1` and unreachable by everything else, which is the most common reason a provider saves as **Enabled · not serving**. This layer is the only one that catches it, along with firewall and security-group problems. **3. Barndoor can reach it** Saving the provider runs the connectivity check (see [How Barndoor checks the connection](#how-barndoor-checks-the-connection)). To re-test after changing something on your side, open the provider's row menu (⋮) in **LLM Management → Providers** and choose **Re-check health**. The result appears as a notification, for example **Health check passed** or **Health check failed: …**. Health is only re-evaluated on save and on **Re-check health**, so a server you just fixed keeps its old status until you do one of them. | Result | Reading | | - | - | | **Health check passed** | Reachable, and the key was accepted. Move on. | | `could not reach upstream provider` | Network, host binding, or a certificate Barndoor doesn't trust. | | `connection to upstream timed out after 10s` | Something accepted the connection but didn't answer. Often a model still loading: the check waits 10 seconds and no longer. | | `upstream rejected the credentials (HTTP 401)` | The key here doesn't match the server's `--api-key`. | | `upstream returned HTTP 404 … base_url ends in '/v1'` | A base URL saved before Barndoor started rejecting `/v1`. Edit the credentials and remove the `/v1`. | **4. The model is exposed to a caller** Create a key under **Settings → My Models → API Keys**, then ask the gateway what that key can actually use: ```bash theme={null} curl -s https://app.barndoor.ai/api/llm-gateway/v1/models \ -H "Authorization: Bearer bd-…" ``` Your route name should be listed, with your provider's name in its `barndoor.provider` field. This is a different question from the previous layer: it proves the route resolves *and* that model access policy lets this caller use it. If the provider is healthy but the model isn't listed here, the problem is the route or the access policy, not your server. Go back to [Step 4](#step-4-create-a-model-route), and check **LLM Management → Model Access**. **5. A request completes — both ways** ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen3", "messages": [{"role": "user", "content": "Say hello"}] }' ``` Then run it again with `"stream": true` added. Streaming goes through a different path, an SSE relay with its own idle timeout, and it's what coding assistants and chat UIs actually use. A passing non-streaming request is not evidence that streaming works. ```bash theme={null} curl -N https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "qwen3", "messages": [{"role": "user", "content": "Count to five"}], "stream": true, "stream_options": {"include_usage": true} }' ``` Expect incremental `data:` chunks, a final chunk carrying `usage`, then `data: [DONE]`. The usage chunk is what makes a streamed request countable. The gateway asks for it on every streamed request even when the client doesn't, so your server must accept `stream_options`. If the usage chunk is missing, tokens won't reach your reports. **6. Governance actually applied** This is the layer that justifies the gateway existing, and the one most people forget to check. Open the **LLM Usage Dashboard** and confirm your requests appear, attributed to the user whose key sent them, with a token count. Cost will read **zero**, which is expected for self-hosted until you set rates (see below). See [Reading the LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard). For real assurance that controls apply to self-hosted traffic the same as hosted, set a deliberately tiny token budget scoped to your test key under **LLM Management → Budgets**, with action **Block**, and confirm the next request is refused. Budget definitions are cached for up to five minutes, so allow for that before concluding it doesn't work. See [LLM Controls](/how-tos/use-llm-controls). *** ## Cost reporting for self-hosted models Self-hosted inference has no market rate (the cost is your own GPU time), so Barndoor ships no default pricing for self-hosted models. Until you decide, usage reporting counts tokens accurately, reports the cost as **zero**, and shows the model as **Unpriced**. You have two ways to make that a decision rather than a gap: * **Record self-hosted traffic as not metered.** Edit the provider, turn off **Calculate token cost**, and set **Billing arrangement** to **Self-hosted**. Tokens are still counted, cost is recorded as \$0 on purpose, and the model shows **Not metered** instead of **Unpriced**. The **Billing arrangement** is required when cost calculation is off. * **Give it a rate.** Leave **Calculate token cost** on and set your own rates under **LLM Management → Model Pricing**. A reasonable approach is to divide the fully loaded hourly cost of the instance by the tokens it produces in that hour, and enter the result as an input and output rate. It doesn't need to be exact to be useful: even a rough number makes "what did this team actually consume" answerable, and lets a cost budget act as a real ceiling. See [Managing Model Pricing](/how-tos/manage-model-pricing). Token budgets and rate limits apply either way. *** ## Troubleshooting > [accordion] could not reach upstream provider > > Barndoor couldn't open a connection. In rough order of likelihood: > > * vLLM is bound to loopback — restart it with `--host 0.0.0.0`. > * A firewall or security group blocks the port from Barndoor's side. > * You're on Barndoor SaaS and the address is private. See [Making the server reachable](#making-the-server-reachable). > * You're using `https://` with a self-signed or private-CA certificate. > > Test from a third machine, not the server host — that's what distinguishes "not listening publicly" from "not running". > [accordion] connection to upstream timed out after 10s > > Something is accepting the connection but not answering in time. Usually a load balancer or proxy in front of your server that's routing to a dead backend, or a server still loading model weights. A large model can take minutes to become ready. Wait for the server's own logs to report it's serving, then choose **Re-check health** on the provider. > [accordion] upstream rejected the credentials (HTTP 401) > > The key in Barndoor doesn't match the token your server was started with. Check for a trailing newline or a shell-quoting artifact: these are usually copy-paste damage rather than the wrong secret. To replace the key, edit the credentials on the **Credentials** tab. Barndoor also raises a critical admin alert when a health check finds a provider's credential rejected. > [accordion] base\_url must not end in '/v1' > > The save was refused because the base URL ends in `/v1`. Use the corrected URL the message suggests, which is the same address without the trailing `/v1`. The gateway adds `/v1` itself. > [accordion] Provider shows Enabled, but requests fail with 404 > > The health check treats a missing model list (HTTP 404 or 405) as inconclusive, so the provider still shows **Enabled**. If requests then 404 too, check whether a reverse proxy in front of your server is rewriting or blocking `/v1` paths, and whether the base URL points at the host root rather than a sub-path. > [accordion] Requests fail with an unknown-model error > > The name enabled in Barndoor doesn't match what the server serves. Compare against `curl http://:8000/v1/models`: the id there is the name to enable, letter for letter. If you added `--served-model-name` after configuring Barndoor, the enabled name is now stale. > > If the gateway itself answers `404 model '…' not found`, the problem is the name the client sent, not the server. A model ID containing `/` (such as `Qwen/Qwen3-8B`) can't be called by its bare name. Call it through a Model Route, or as `/Qwen/Qwen3-8B`. > [accordion] Tool calls come back as prose > > The server wasn't started with `--enable-auto-tool-choice` and a `--tool-call-parser` matching the model family. Barndoor forwards the `tools` array unchanged; it cannot synthesize structured tool calls from a server that isn't producing them. *** ## Current limits * **Chat completions and streaming** are the supported surface. Claude Code and other Anthropic-format clients can use a self-hosted model too, because the gateway translates Messages requests into chat completions. The gateway also forwards embeddings, legacy completions, and Responses API requests to your server unchanged, but those aren't verified on this path and work only if your server implements them. * **Tool calling and reasoning output** depend entirely on how you started the server, so Barndoor makes no promise about them on your behalf. They pass through when your server produces them. * **Barndoor SaaS cannot reach a server on a private network.** There is no tunnel or agent for this today; the server needs a routable address, or Barndoor needs to run inside your infrastructure. # Connecting Your Tools to the LLM Gateway Source: https://docs.barndoor.ai/how-tos/connect-tools-to-llm-gateway Grab your API key, model name, and gateway endpoint from the Barndoor portal, then point Cursor, Claude Code, Codex, or the OpenAI / Anthropic SDKs at the gateway. > [!NOTE] > > This page is for developers. It assumes an admin has already configured a provider and at least one model. If **Available Models** is empty for you, ask your admin to work through the [Quickstart Guide](/how-tos/llm-gateway-quickstart) first. ## What You Need Every tool below needs the same three values. All of them are on the **My Models** page in the Barndoor portal (**Settings → My Models**): | Value | Looks like | Where to get it | | - | - | - | | **API key** | `bd-…` | [**API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) → **Create Key** | | **Model name** | `gpt-5.4-mini`, `claude-sonnet-5`, `OpenAI/gpt-5.4-mini` | [**Available Models**](https://app.barndoor.ai/settings/models?section=models) | | **Gateway endpoint** | `https://app.barndoor.ai/api/llm-gateway/v1` | [**Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) | ![Settings → My Models page showing Available Models, with Model Routes & Routing Policies above Standalone Models](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/08-my-models-page.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=efa5405fcb95ec4dac19b0af91340f6d) **1. Create an API key** Open [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) and click **Create Key**. Enter a **Key Name** that says where the key will live (for example `Cursor on laptop`), choose an **Expiration** (or **No expiry**, if your organization allows it), and click **Create**. The **API Key Created** dialog shows a `bd-…` key. **Copy it now.** Barndoor stores only a one-way hash of the key, so the raw value cannot be shown again. Keys created here are linked to your account, so usage is attributed to you and your model access policies apply. From the same table you can **rotate** a key (new secret, same key — use this to renew it before it expires), **disable** it (reversible, blocks requests until you re-enable it), or **revoke** it (permanent). See [Managing LLM API Keys](/how-tos/manage-llm-api-keys). ![Create API Key dialog in the Barndoor portal, with a key name and an expiration](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/01-create-api-key.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=e889e4d13747dee4289695935064340e) **2. Copy a model name** [**Available Models**](https://app.barndoor.ai/settings/models?section=models) lists every model your admin has enabled and your access policies allow. Each row has a copy button. Use the name exactly as shown: * **Model Routes**: a plain name such as `gpt-5.4-mini`, `claude-sonnet-5`, or `coding`. The gateway tries the route's targets in order and fails over between them. Route names are chosen by your admin and don't have to look like model IDs. * **Standalone Models**: a `provider/model` name such as `OpenAI/gpt-5.4-mini`. The part before the `/` is the name your admin gave the provider, not the vendor. A standalone model is served by that one provider only, with no failover to another. * **Routing Policies**, if your organization uses them, also appear in this list and are called by name. See [Routing Policies](/how-tos/llm-routing-policies). See [How model names resolve](#how-model-names-resolve) for the full rules. **3. Copy your gateway endpoint** The [**LLM Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) card shows two base URLs. Copy the one that matches your client: | Card label | URL | Use for | | - | - | - | | **OpenAI SDKs & compatible clients** | `https://app.barndoor.ai/api/llm-gateway/v1` | OpenAI SDKs, Cursor, Codex, LangChain, cURL | | **Claude Code & Anthropic SDKs** | `https://app.barndoor.ai/api/llm-gateway` | Claude Code, the Anthropic SDKs | ![LLM Gateway Endpoint card on the Settings → My Models page](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/02-endpoint-card.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=d82ffb537b648b6644aeaf19cff3e70a) > [!NOTE] > > The two URLs differ only by the trailing `/v1`. Anthropic clients append `/v1/messages` themselves, so giving them the `/v1` form produces `/v1/v1/messages`. **4. Confirm all three work** Before configuring a tool, try all three from a shell. This separates auth problems from model-name problems, which look alike once an editor is in the middle: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.4-mini", "messages": [{"role": "user", "content": "Say hello"}] }' ``` | Status | Meaning | | - | - | | `401` | The key is wrong, revoked, or disabled, or the URL is wrong. | | `404` | The model name doesn't match anything enabled for your organization. | | `403` | The model exists, but a model access policy doesn't allow you to use it. | > [!WARNING] > > Treat `bd-…` keys like passwords. Keep them in environment variables or a secret store, not in source control. > [!NOTE] > > **Self-hosted and private-cloud deployments:** if Barndoor runs on your own infrastructure, swap `app.barndoor.ai` for your organization's portal hostname everywhere on this page. The path (`/api/llm-gateway/v1`) is the same, and the **Gateway Endpoint** card always shows the right URL for your deployment. *** ## What the Gateway Accepts The gateway speaks both the OpenAI and the Anthropic wire formats. On Chat Completions and Messages, it translates between formats when the client's format and the provider's differ, so an OpenAI-style client can call a Claude model and Claude Code can call a GPT model. | Endpoint | Format and notes | | - | - | | `POST /v1/chat/completions` | **OpenAI Chat Completions.** Streaming, tools, and images. Works with every chat provider except OpenAI Codex OAuth, which serves Responses only. | | `POST /v1/responses` | **OpenAI Responses.** Used by Codex. Not translated: the model must be served by a provider that speaks the Responses API itself, such as OpenAI, Azure OpenAI (with **Azure API Mode** set to **OpenAI v1 paths**, the default), xAI, OpenAI Codex OAuth, or a custom OpenAI-compatible server that implements it. Anthropic, Bedrock, Vertex, and Google AI models can't be called here. | | `POST /v1/messages` | **Anthropic Messages.** Used by Claude Code and the Anthropic SDKs. Works with the same providers as Chat Completions. For Anthropic, and for Claude on Bedrock or Vertex, your request body is forwarded as-is, so `thinking`, `metadata`, and `cache_control` keep working. | | `POST /v1/messages/count_tokens` | **Anthropic token counting.** Returns a local estimate. Nothing is sent to a provider, and it doesn't count against budgets or rate limits. | | `POST /v1/completions` | **OpenAI legacy completions.** For providers that still serve it. | | `POST /v1/embeddings` | **OpenAI Embeddings.** For providers that serve embeddings. | | `GET /v1/models` | **OpenAI or Anthropic model list.** Lists only the models you are allowed to call. | All paths above are relative to `https://app.barndoor.ai/api/llm-gateway`. If you call an endpoint the model's provider can't serve, the request fails with `provider '…' does not support endpoint …`. Pick a model served by a different provider, or ask your admin to add a route target that supports it. ### Authentication and headers | Header | What the gateway does with it | | - | - | | `Authorization: Bearer bd-…` | Authenticates the request. This is what OpenAI-style clients send. | | `x-api-key: bd-…` | Also authenticates the request. If both headers are present, `x-api-key` wins, which leaves `Authorization` free to carry a Claude or ChatGPT OAuth token for [OAuth passthrough](#claude-code). | | `anthropic-version`, `anthropic-beta` | Forwarded to Anthropic-family providers. On `GET /v1/models`, an `anthropic-version` header makes the gateway return Anthropic's list format instead of OpenAI's. | By default, a request body can be up to 32 MiB, which covers a full-context Claude Code conversation. Successful responses carry `x-bd-request-id` and routing headers that tell you which provider served the request and whether failover happened. The [Quickstart Guide](/how-tos/llm-gateway-quickstart) describes them. ### How model names resolve The `model` field decides which provider serves your request: | You send | The gateway | Failover | | - | - | - | | A Model Route name (`claude-sonnet-5`, `coding`) | Tries the route's targets in the order your admin set | Yes, across every target in the route | | A Routing Policy name | Picks a model per request from the policy's options, then routes to it | Yes, within the chosen target | | `/` (`OpenAI/gpt-5.4-mini`) | Sends the request to that one provider's model | No | Some details that commonly trip people up: * **The provider prefix is the provider's name in Barndoor**, matched without regard to case. It isn't the vendor. If your admin named a provider `OpenAI-Prod`, the name is `OpenAI-Prod/gpt-5.4-mini`. * **`/` is not accepted.** A route is called by its own name. Something like `OpenAI-Prod/coding` returns `404`, and the error message suggests the route name. * **Everything before the first `/` is read as a provider name.** A model whose ID contains a slash, such as `Qwen/Qwen3-8B`, has to be called through a Model Route or as `/Qwen/Qwen3-8B`. * **Your organization may require Routing Policies.** When that setting is on, only routing-policy names are accepted, and `GET /v1/models` lists only those. `GET /v1/models` returns exactly the names you can call. Each entry also carries a `barndoor` object with the serving `provider`, the `upstream_model`, and whether the name is a multi-target `fallback_group`. When a name fans out across several providers, `provider` and `upstream_model` are left out. *** ## Connect Your Tools > [accordion] OpenAI Python SDK > > ```python theme={null} > from openai import OpenAI > > client = OpenAI( > base_url="https://app.barndoor.ai/api/llm-gateway/v1", > api_key="bd-…", > ) > > response = client.chat.completions.create( > model="gpt-5.4-mini", > messages=[{"role": "user", "content": "Hello, gateway!"}], > ) > print(response.choices[0].message.content) > ``` > > Streaming, function calling, and embeddings work the same way as they do against OpenAI directly. `client.responses.create(...)` works too, as long as the model is served by a provider that supports the Responses API (see [What the Gateway Accepts](#what-the-gateway-accepts)). > [accordion] OpenAI Node SDK > > ```ts theme={null} > import OpenAI from "openai"; > > const client = new OpenAI({ > baseURL: "https://app.barndoor.ai/api/llm-gateway/v1", > apiKey: process.env.BARNDOOR_API_KEY, > }); > > const response = await client.chat.completions.create({ > model: "gpt-5.4-mini", > messages: [{ role: "user", content: "Hello, gateway!" }], > }); > console.log(response.choices[0]?.message?.content); > ``` > [accordion] Anthropic SDK > > ```python theme={null} > import anthropic > > client = anthropic.Anthropic( > base_url="https://app.barndoor.ai/api/llm-gateway", > api_key="bd-…", > ) > > message = client.messages.create( > model="claude-sonnet-5", > max_tokens=256, > messages=[{"role": "user", "content": "Hello"}], > ) > print(message.content[0].text) > ``` > > > [!NOTE] > > > > Use the **Claude Code & Anthropic SDKs** URL from the endpoint card, the one without `/v1`. The SDK appends `/v1/messages` itself. The SDK sends your key as `x-api-key`, which the gateway accepts. > > `model` can be any name from **Available Models**, not only Claude models. The gateway translates Messages requests for non-Anthropic providers. > [accordion] Claude Code > > Claude Code talks to the gateway through `ANTHROPIC_BASE_URL`. Which other variables you set depends on how your admin configured the Anthropic provider behind your models. In **LLM Management → Providers**, an Anthropic provider's **Authentication** is one of: > > * **API key**: everyone's traffic bills against one Anthropic API key that Barndoor stores. Bedrock, Vertex, and Foundry providers work the same way from Claude Code's side. > * **Claude OAuth passthrough**: each request bills against the developer's own Claude subscription. Barndoor stores no Anthropic credential, and the gateway forwards each developer's Claude sign-in to Anthropic. > > Ask your admin which one applies if you're not sure. > > > [!NOTE] > > > > Set `ANTHROPIC_BASE_URL` to the **Claude Code & Anthropic SDKs** URL on the endpoint card, the one **without** `/v1`. Claude Code appends `/v1/messages` itself. > > > [tab] API-key provider > > > > Use this when the provider behind your model has a stored credential (an Anthropic API key, Bedrock, Vertex, Foundry, or a non-Anthropic provider). > > > > ```bash theme={null} > > export ANTHROPIC_BASE_URL="https://app.barndoor.ai/api/llm-gateway" > > export ANTHROPIC_AUTH_TOKEN="bd-…" # your LLM Gateway key from Settings → My Models > > export ANTHROPIC_MODEL="claude-sonnet-5" # a name from Available Models > > export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1 > > claude > > ``` > > > > Claude Code sends `bd-…` as `Authorization: Bearer`. The gateway authenticates you with that key, then calls the provider with the credential your admin stored. > > > > > [!NOTE] > > > > > > **Admins can issue keys for other people** under **LLM Management → API Keys** → **Create API Key**, using **Assign to User**, **Assign to Group**, or neither. A key with no assignee works for anyone in the organization who holds it. > > > > > > Prefer a per-user or per-group key. An unassigned key carries no user identity, so per-user spend has nothing to attribute traffic to, and user-scoped model access policies can never match it. A group-assigned key keeps group-scoped policies working while still being one key for many people. > > > > > [!WARNING] > > > > > > `ANTHROPIC_AUTH_TOKEN` takes the **bare key**: `bd-…`, not `x-api-key: bd-…`. The `x-api-key:` prefix belongs only in `ANTHROPIC_CUSTOM_HEADERS`, and only in the OAuth passthrough setup. Mixing the two produces a `401`, because the gateway treats the whole string as the key. > > > > Without `ANTHROPIC_MODEL`, Claude Code requests its own default Anthropic model IDs, which then must appear in **Available Models** under those exact names. Setting `ANTHROPIC_MODEL` to one of your Model Route names avoids that dependency. `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` fills the `/model` picker from the gateway's `GET /v1/models`, which the gateway returns in Anthropic's format for Claude Code. That applies to **this** setup only. With OAuth passthrough, Claude Code doesn't look models up, so the picker keeps its built-in names whatever the flag says. > > > > > [!NOTE] > > > > > > This setup needs every model you request to resolve to a provider with a **stored credential**. If a request lands on a **Claude OAuth passthrough** provider, the gateway rejects it with `401 Anthropic provider requires an incoming Claude OAuth bearer token`. Switch to the OAuth passthrough setup for those models. > > > [tab] Claude OAuth passthrough provider > > > > Use this when the provider behind your model uses **Claude OAuth passthrough**. Claude Code already sends your Claude sign-in in the `Authorization` header, so your Barndoor key goes in a separate `x-api-key` header and the two don't collide: > > > > ```bash theme={null} > > export ANTHROPIC_BASE_URL="https://app.barndoor.ai/api/llm-gateway" > > unset ANTHROPIC_API_KEY > > unset ANTHROPIC_AUTH_TOKEN > > export ANTHROPIC_CUSTOM_HEADERS="x-api-key: bd-…" # your LLM Gateway key from Settings → My Models > > export ANTHROPIC_MODEL="claude-opus-5-5" # a name from Available Models > > claude > > ``` > > > > Make sure you're signed in to Claude (run `claude /login` if not). Claude Code refreshes its OAuth token for you, and the gateway forwards it to Anthropic unchanged. The gateway reads your Barndoor key from `x-api-key` and never treats the Claude token as a Barndoor key. > > > > Set `ANTHROPIC_MODEL` to the name you want from **Available Models**. `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` has no effect in this setup, because Claude Code makes no startup `/v1/models` call when it signs in with OAuth. `ANTHROPIC_MODEL` is what decides the route. > > #### Claude Code in VS Code > > The `export` lines above apply only to the terminal you ran them in. The VS Code extension starts its own process, so put the same variables in an `env` block at the root of **`.claude/settings.local.json`** in your project. Claude Code reads it at the start of every session. > > For a **Claude OAuth passthrough** provider: > > ```json .claude/settings.local.json theme={null} > { > "env": { > "ANTHROPIC_BASE_URL": "https://app.barndoor.ai/api/llm-gateway", > "ANTHROPIC_CUSTOM_HEADERS": "x-api-key: bd-…", > "ANTHROPIC_MODEL": "{{a name from Available Models}}" > } > } > ``` > > For an **API-key** provider: > > ```json .claude/settings.local.json theme={null} > { > "env": { > "ANTHROPIC_BASE_URL": "https://app.barndoor.ai/api/llm-gateway", > "ANTHROPIC_AUTH_TOKEN": "bd-…", > "ANTHROPIC_MODEL": "{{a name from Available Models}}", > "CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY": "1" > } > } > ``` > > `ANTHROPIC_MODEL` takes the name exactly as it appears under [**Available Models**](https://app.barndoor.ai/settings/models?section=models). Route names are free-form, so a name like `Developer` is valid. > > > [!WARNING] > > > > This file stores your `bd-…` key in plaintext. Confirm `.claude/settings.local.json` is listed in your `.gitignore` (Claude Code adds it when it creates the file). Anything you want checked in belongs in `.claude/settings.json` instead, and only if it's safe to share. `ANTHROPIC_BASE_URL` is safe to share. Your key is not. > > > [!NOTE] > > > > Reload the window (**Cmd/Ctrl+Shift+P → Developer: Reload Window**) after editing the file. The extension reads `env` when a session starts, not while one is running. To use the same gateway settings in every project, put the same block in `~/.claude/settings.json`. > > > [!TIP] > > > > **Check your environment before launching `claude`.** A wrong combination of variables is the most common setup problem, and it often shows up as a silent retry rather than a useful error. > > > > ```bash theme={null} > > env | grep -E '^ANTHROPIC_|^CLAUDE_CODE_' > > ``` > > > > | Setup | Expect to see | Expect to be absent | > > | - | - | - | > > | API-key provider | `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` (bare `bd-…` key) | `ANTHROPIC_CUSTOM_HEADERS`, `ANTHROPIC_API_KEY` | > > | Claude OAuth passthrough | `ANTHROPIC_BASE_URL`, `ANTHROPIC_CUSTOM_HEADERS` | `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_API_KEY`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | > > > > Then confirm the key and base URL work before launching `claude`. This isolates auth problems from model-name problems: > > > > ```bash theme={null} > > curl "$ANTHROPIC_BASE_URL/v1/models" -H "x-api-key: bd-…" -H "anthropic-version: 2023-06-01" > > ``` > > > > A model list means auth is good, so any remaining failure is model naming. A `401` means the key or URL is wrong. > > > [!TIP] > > > > **Check which provider served a request.** The `model` field in an Anthropic response names the model that actually answered. If a route such as `claude-opus-5-5` has an Anthropic primary and a Bedrock fallback, an Anthropic-style ID means the primary served it, and a Bedrock-style ID (for example `anthropic.claude-opus-5-5`) means failover engaged. This works on every response. Successful responses also carry routing headers with the same information. > > > [accordion] `jq: Could not open file ~/.claude/.credentials.json` > > > > Recent Claude Code versions don't expose a plaintext credentials file. If you have a shell snippet that runs `jq` over that path to extract an OAuth token, remove it. Claude Code handles the OAuth token itself. Your only job is to set the variables in the tabs above. > [accordion] Cursor IDE > > Cursor lets you add custom OpenAI-compatible providers under **Settings → Models → OpenAI API Key → Override OpenAI Base URL**: > > 1. Toggle **Custom OpenAI API Key**. > 2. Set the base URL to the **OpenAI SDKs & compatible clients** URL, `https://app.barndoor.ai/api/llm-gateway/v1`. > 3. Paste your `bd-…` key as the API key. > 4. Add the model names from **Available Models** (for example `gpt-5.4-mini`, `claude-sonnet-5`) that you want Cursor to be able to select. > > ![Cursor Settings → Models with the Barndoor LLM Gateway configured as a custom OpenAI base URL](https://mintcdn.com/barndoor/R2cAUz0zJ6SKh319/images/llm-gateway/09-cursor-custom-openai.png?fit=max\&auto=format\&n=R2cAUz0zJ6SKh319\&q=85\&s=71834110e909a55f5d23fbfac1f4a0b8) > [accordion] Codex CLI / Desktop > > Codex uses the OpenAI **Responses** API (`wire_api = "responses"`), not Chat Completions. Point a custom provider at the gateway and keep `/v1` on the base URL. Codex appends `/responses` itself. > > ```toml theme={null} > model_provider = "barndoor" > model = "gpt-5.4-mini" > > [model_providers.barndoor] > name = "Barndoor" > base_url = "https://app.barndoor.ai/api/llm-gateway/v1" > wire_api = "responses" > env_key = "BARNDOOR_API_KEY" > ``` > > ```bash theme={null} > export BARNDOOR_API_KEY="bd-…" > codex > ``` > > `env_key` is the environment variable's *name*. The `export` supplies the secret. The model must be served by a provider that supports the Responses API. A Claude route, for example, won't work from Codex. > > Full steps for CLI and Desktop, plus troubleshooting: **[Use Codex with the LLM Gateway](/how-tos/use-codex-with-llm-gateway)**. > [accordion] LangChain > > ```python theme={null} > from langchain_openai import ChatOpenAI > > llm = ChatOpenAI( > model="gpt-5.4-mini", > base_url="https://app.barndoor.ai/api/llm-gateway/v1", > api_key="bd-…", > ) > print(llm.invoke("Hello, gateway!").content) > ``` > > `OpenAIEmbeddings` and the other OpenAI-style integrations work the same way: set `base_url` and `api_key`. For `ChatAnthropic`, set `anthropic_api_url` to the URL without `/v1`. > [accordion] cURL / scripts > > For CI and shell scripts, export the URL and key once: > > ```bash theme={null} > export BARNDOOR_BASE_URL="https://app.barndoor.ai/api/llm-gateway/v1" > export BARNDOOR_API_KEY="bd-…" > > curl "$BARNDOOR_BASE_URL/models" -H "Authorization: Bearer $BARNDOOR_API_KEY" > ``` > > More request shapes (streaming, embeddings, Anthropic Messages) are in the [Quickstart Guide](/how-tos/llm-gateway-quickstart). *** ## Launching Claude Code or Codex with Barndoor Bridge Everything above is do-it-yourself configuration: you set the variables, and you can change them. If your organization uses [Barndoor Bridge](/how-tos/barndoor-bridge/overview), developers don't configure the gateway at all. `barndoor run claude` (or the Bridge app's launch button) starts the client already pointed at the gateway, on a short-lived session credential that Bridge renews and revokes for you. Two admin settings shape that launch: * **Models** come from [Model Access](/how-tos/use-llm-controls#model-access). At launch, the gateway fills the client's default and per-family models with the newest Model Route the developer is allowed to use, and the session can call any allowed route and nothing else. * **What the client can do** is set under **LLM Management → Client settings**, one set for Claude Code and one for Codex: optional governance of native file, shell, network, browser, secrets, skills, and subagent access. See [Client settings](/how-tos/barndoor-bridge/client-settings) for how models are chosen and what each setting does. > [!NOTE] > > Barndoor Bridge is in early access, and **Client settings** may not be enabled for your organization yet. Contact Barndoor to turn them on. *** ## Related * [Using the LLM Gateway](/how-tos/use-llm-gateway): overview, architecture, and prerequisites * [Quickstart Guide](/how-tos/llm-gateway-quickstart): admin setup, request reference, and troubleshooting * [Use Codex with the LLM Gateway](/how-tos/use-codex-with-llm-gateway): the full Codex CLI and Desktop walkthrough * [Connecting a Self-Hosted Model](/how-tos/connect-self-hosted-model): route to vLLM, Ollama, and other OpenAI-compatible servers * [Get the most out of your Claude subscription](/how-tos/llm-gateway-failover): run Claude Code on your own Claude seat and fail over when you hit the cap # Connecting Accounts to Barndoor Source: https://docs.barndoor.ai/how-tos/connected-accounts Step-by-step guide for connecting external accounts (like Salesforce) in Barndoor. Barndoor lets you connect MCP servers to your user workspace. Once connected, Barndoor can securely use your authorized credentials when executing **MCP server tool calls** on your behalf. ## How It Works Behind the Scenes When you connect an account, Barndoor uses OAuth 2.0 to perform a secure handshake with the provider. * After you log in, the provider (e.g., Salesforce) sends Barndoor an **access token**. * Barndoor securely stores this JWT token and uses it whenever an **MCP server tool call** needs to act on your behalf — for example, retrieving Salesforce data or updating records. The JWT token will live for 60 minutes and can always be refreshed. * Tokens can be revoked at any time through your provider’s account settings or through our API/SDK. *** ## Step 1: Go to Your Connected Accounts 1. Log in to your [Barndoor Dashboard](https://app.barndoor.ai/). 2. Underneath 'MY BARNDOOR', navigate to **Connected Accounts** or go directly to [**app.barndoor.ai/settings/accounts**](https://app.barndoor.ai/settings/apps). 3. You’ll see three tabs: * **Available** – services you can connect. * **All** – the complete list of supported integrations. * **Connected** – services already linked to your account. > [!NOTE] > > This is entire web flow is also achievable via our Barndoor SDK and API's. *** ## 🔗 Step 2: Choose a Service to Connect 1. Under the **Available** tab, find the service you want to connect — for example, **Salesforce**. 2. Click **Connect**. 3. Barndoor will redirect you to the service’s authentication page (in this case, Salesforce). *** ## Step 3: Authorize Access 1. Sign in with your account credentials on the provider’s login page. 2. Approve Barndoor’s request for access. * This allows Barndoor to securely obtain an **access token** that it will store on your behalf. * Barndoor never sees or stores your password — only the OAuth token returned from the provider. *** ## Step 4: Verify the Connection Once the authentication is complete: * You’ll be redirected back to Barndoor. * The connected service (e.g., **Salesforce**) will now appear in your **Connected Accounts** tab. * You can disconnect at any time from the same page. *** ## That’s It! You’ve now connected your first external service to Barndoor. # Connect AI clients to Barndoor Source: https://docs.barndoor.ai/how-tos/connecting-barndoor-to-agents Step-by-Step: Connect your ToolIQ universal endpoint to your MCP Servers for Claude, ChatGPT, and other AI clients ## Overview Add your Barndoor ToolIQ endpoint [found here](https://app.barndoor.ai/settings/ai-client-setup) to your favorite chat client. If you're not already logged in, you'll be redirected to Barndoor to authenticate and authorize the MCP servers you want to access. > [!NOTE] > > If you ever want to see what servers you're connected to, [click here](https://app.barndoor.ai/settings/apps). ## Connect Your Chat Client Select your preferred AI chat client below to see detailed connection instructions: > [accordion] Claude > > ![Claude AI](https://logos.barndoor.ai/logos/logo-claude-1.png) > > #### Prerequisites: > >
    >
  • Active Claude account (Pro, Max, Team, or Enterprise plan)
  • >
  • Universal Barndoor URL
  • >
> > ### Connection Steps > > Follow the [official guide for connecting to remote MCP servers](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp) for step-by-step instructions. > > > [tab] Pro / Max > > > > **1. Open Settings** > > > > Navigate to **Settings > Connectors**. > > > > **2. Add Custom Connector** > > > > Click **"Add custom connector"** at the bottom of the Connectors section. > > > > **3. Configure Connection** > > > > Enter your MCP server URL (e.g., `https://{{your-org}}.platform.barndoor.ai/mcp/mcp`). > > > > Optionally, click **"Advanced settings"** to provide an OAuth Client ID and OAuth Client Secret for your server. > > > > **4. Finish** > > > > Click **"Add"** to save your connector. > > > > **5. Use in Conversations** > > > > Start a new conversation — Claude will have access to your connector's tools and data. > > > [tab] Team / Enterprise (Owner) > > > > > [!NOTE] > > > > > > Only **Owners** can add custom connectors to a Team or Enterprise organization. Members connect individually after an Owner has added the connector. > > > > **1. Open Organization Settings** > > > > Navigate to **Organization Settings > Connectors**. > > > > **2. Add Custom Connector** > > > > Click **"Add custom connector"** at the bottom of the Connectors section. > > > > **3. Configure Connection** > > > > Enter your MCP server URL (e.g., `https://{{your-org}}.platform.barndoor.ai/mcp`). > > > > Optionally, click **"Advanced settings"** to provide an OAuth Client ID and OAuth Client Secret for your server. > > > > **4. Finish** > > > > Click **"Add"** to make the connector available to your organization's members. > > > [tab] Team / Enterprise (Member) > > > > > [!NOTE] > > > > > > Your Owner must add the custom connector to your organization before you can connect to it. > > > > **1. Open Settings** > > > > Navigate to **Settings > Connectors**. > > > > **2. Find the Connector** > > > > Locate the custom connector your Owner added — it will have a **"Custom"** label. > > > > **3. Connect** > > > > Click **"Connect"** to authenticate and start using the connector with Claude. > > > > **4. Use in Conversations** > > > > Start a new conversation — Claude will have access to your connector's tools and data. > > > [!TIP] > > > > You can enable or disable specific connectors for individual conversations using the tools menu in the chat interface. > [accordion] ChatGPT > > ![ChatGPT](https://logos.barndoor.ai/logos/logo-chatgpt-1.png) > > #### Prerequisites: > >
    >
  • ChatGPT Plus or Enterprise account
  • >
  • MCP server OpenAPI schema
  • >
> > ### Custom GPT with Actions > > Follow the [official guide for connecting to remote MCP servers](https://developers.openai.com/apps-sdk/deploy/connect-chatgpt/). > > **1. Create Custom GPT** > > Go to [ChatGPT](https://chat.openai.com) and navigate to Settings → Apps → ***Create App***. > > **2. Provide the metadata for your App** > > * Name – a user-facing title such as Kanban board. > * Description – explain what the connector does and when to use it. The model uses this text during discovery. > * MCP server URL – the public /mcp endpoint of your server (for example [https://abc123.ngrok.app/mcp](https://abc123.ngrok.app/mcp)). > > **3. Test & Publish** > > Click Create. If the connection succeeds you will see a list of the tools your server advertises. If it fails, refer to the [Testing](https://developers.openai.com/apps-sdk/deploy/testing) guide to debug your app with MCP Inspector or the API Playground. > [accordion] Cursor IDE > > ![Cursor IDE](https://logos.barndoor.ai/logos/symbol-logo-cursor.png) > > #### Prerequisites: > >
    >
  • Cursor IDE installed
  • >
  • MCP server URL and API key
  • >
> > **1. Open Settings** > > Go to **Cursor** → **Settings** (or `Cmd/Ctrl + ,`) > > **2. Find MCP Configuration** > > Navigate to **Extensions** → **MCP** or search for "MCP" in settings > > **3. Add Server** > > Click **Add MCP Server** and configure: > > ```json theme={null} > { > "mcpServers": { > "{{your-org}}.platform.barndoor.ai": { > "url": "https://{{your-org}}.platform.barndoor.ai/mcp" > } > } > } > ``` > > **4. Restart Cursor** > > Restart Cursor to apply changes > [accordion] VS Code > > ![VS Code](https://code.visualstudio.com/assets/updates/1_35/logo-stable.png) > > #### Prerequisites: > >
    >
  • Visual Studio Code installed
  • >
  • VS Code version with MCP support enabled
  • >
> > ### Connection Steps > > **1. Open VS Code Settings** > > Open the Command Palette (`Cmd/Ctrl + Shift + P` > > ) and select **Preferences: Open Settings (JSON)**. > > **2. Configure MCP Server** > > Add your MCP server configuration to `settings.json` > > : > > ```json theme={null} > { > "mcp.servers": [ > { > "name": "Your Server", > "url": "https://{{your-org}}.platform.barndoor.ai/mcp" > } > ] > } > ``` > > **3. Authenticate** > > Authorize Barndoor and Sign in when prompted. > > **4. Reload Window** > > Reload VS Code to activate the MCP connection. ## Troubleshooting > [accordion] Connection Failed > > * Verify your server URL is correct and accessible > * Check that authentication credentials are valid > * Ensure your MCP server is running and responding to requests > * Check firewall settings if using a self-hosted server > [accordion] Tools Not Appearing > > * Confirm the MCP server is properly registered > * Verify the server's tools are correctly defined in its schema > * Try disconnecting and reconnecting the server > * Clear cache and restart the client application > [accordion] Authentication Errors > > * Double-check API keys or tokens > * Verify authentication method matches your server's requirements > * Check if tokens have expired and need renewal > * Ensure proper scopes/permissions are granted ## Security Best Practices > [!WARNING] > > Never share your MCP server credentials publicly or commit them to version control. * Use environment variables for sensitive credentials * Implement proper authentication and authorization * Use HTTPS for all MCP server connections * Regularly rotate API keys and tokens * Monitor Barndoor server logs # Field Controls Source: https://docs.barndoor.ai/how-tos/data-control-center/field-controls Deterministic, field-level redaction for specific MCP tools — independent of text-based detection. **Field Controls** give you deterministic, field-level governance over structured JSON tool output — independent of text-based detection. Instead of scanning payloads for patterns, you name exact field paths to either remove or keep from a specific tool's response. Use field controls when: * You know the exact JSON field paths that contain sensitive data * You want to guarantee a field is always removed regardless of its content * You need an allow-only posture — strip every field except the ones explicitly approved for a given audience * The tool returns structured data (Salesforce records, database rows, API responses) where field names are stable Field controls complement [MCP Policies](/how-tos/data-control-center/mcp-policies): use MCP policies for text-pattern detection across many tools, and field controls for precise, schema-aware redaction on specific tools. To filter or block activity by a value in the data — such as a Google Drive label or a Slack channel — across every tool on a server, use a [conditional rule](/how-tos/data-control-center/field-controls/conditional-rules). ## View your field control rules Navigate to **Data Control Center → Field Controls**. The rules table lists every active rule with: * **Rule name** * **MCP Server** and **Tool** — the specific tool the rule targets * **Direction** — Input (what the agent sends) or Output (what the tool returns) * **Mode** — Redact listed fields, or Allow only listed fields * **Audience** — groups or roles scoped (blank = everyone) * **Status** — enabled or disabled ## Create a rule Before creating a rule, use the **Sample a call** panel to see the real response shape from the tool. This tells you the exact field paths to configure. ### Step 1 — Sample the tool (recommended) 1. In the Field Controls tab, click **New rule** to open the rule dialog. 2. Select the MCP Server and tool you want to control. 3. In the **Sample a call** section, click the expander. This runs a live call through the proxy admin endpoint and returns the structured response. ![Sample a call panel](https://mintcdn.com/barndoor/ycLd3Cg8QdOmsIcT/images/data-control-center/data-protection-field-controls-sample-a-call-panel--structured-salesforce-response.png?fit=max\&auto=format\&n=ycLd3Cg8QdOmsIcT\&q=85\&s=93b2d717f3c2998e694f71b5665ad203) 4. The response fields appear in the field picker. Select the paths you want to redact or allow. ### Step 2 — Configure the rule Complete the remaining fields: 1. **Rule name** — a descriptive name (e.g., "Strip revenue fields from Salesforce Account for support group"). 2. **Direction**: * **Output** — controls what the tool returns to the agent (most common) * **Input** — controls what the agent sends to the tool 3. **Mode**: | Mode | Behaviour | | - | - | | **Redact listed** | The fields you name are removed; everything else passes through, including new fields the tool adds later | | **Allow only listed** | Only the fields you name pass through; everything else is removed, including new fields the tool adds later | Choose **Redact listed** when you have a small number of known sensitive fields and want everything else to flow. Choose **Allow only listed** when you need strict control and only a defined subset of fields should ever reach the agent. 4. **Fields** — select paths from the field picker (populated by the sample call), or type dotted paths directly (e.g., `records[*].AnnualRevenue`, `records[*].BillingAddress`). 5. **Principals (optional)** — add groups or roles to scope the rule. Without principals, the rule applies to everyone. 6. **Enabled** — leave toggled on to activate immediately, or toggle off to save the rule in a disabled state. 7. Click **Save rule**. ## Edit a rule 1. Find the rule in the Field Controls table. 2. Click **⋮ → Edit**. 3. Update the name, mode, field list, or principals. 4. Save. The rule takes effect immediately on the next matching tool call. ## Delete a rule 1. Click **⋮ → Delete** on the rule row. 2. Confirm. The rule stops applying immediately. ## Enable and disable rules Toggle a rule on or off without deleting it. Use this to temporarily suspend a rule during debugging or a maintenance window while preserving its configuration. ## Test a field control rule ### Using the Sample a call panel The sample panel within the rule editor is the primary testing tool. Before saving a rule, run a sample call and verify: 1. The fields you expect to be present are in the response 2. Your selected field paths match the actual paths in the response (nested paths use dot notation: `records[0].Name`) ### Using the Policy Test Workbench 1. Navigate to **Data Control Center → Test**. 2. Select the MCP server and tool. 3. Paste a representative tool response payload. 4. Review the processed output to confirm the fields are redacted or allowed as expected. ### Verifying in the Audit Center Field control events appear in the Audit Center alongside detection policy events. Filter by **Event type → Data Protection** and look for `field_control` action type rows. Each row shows: * The tool and MCP server * The direction (Input / Output) * The fields that were redacted * The rule and principal context that matched ## Common patterns **Always strip revenue data from Salesforce Account records for the support team:** * Server: Revenue ops Salesforce * Tool: `queryAccount` * Direction: Output * Mode: Redact listed * Fields: `records[*].AnnualRevenue`, `records[*].BillingAddress`, `records[*].Contract__c` * Principals: Group `customer-support` **Allow only approved fields from a finance tool for all users:** * Server: Finance reconciliation * Tool: `getVendorPayment` * Direction: Output * Mode: Allow only listed * Fields: `vendor_name`, `payment_date`, `invoice_id`, `status` * Principals: (none — applies to everyone) **Strip all internal metadata from outgoing tool inputs:** * Server: Internal API * Tool: `createTicket` * Direction: Input * Mode: Redact listed * Fields: `_internal_user_id`, `_session_token`, `_trace_id` * Principals: (none) ## Conditional rules **Add Conditional Rule** creates a rule that matches on a value in the data instead of a field path, for every tool on a Barndoor-hosted Slack (User) or Google Drive server. See [Conditional Rules](/how-tos/data-control-center/field-controls/conditional-rules), and the setup guides for [Google Drive](/how-tos/data-control-center/field-controls/conditional-rules/google-drive) and [Slack](/how-tos/data-control-center/field-controls/conditional-rules/slack). # Conditional Rules Source: https://docs.barndoor.ai/how-tos/data-control-center/field-controls/conditional-rules Filter or block MCP tool activity based on values in the data, such as a Google Drive label or a Slack channel. A **conditional rule** is a field control that matches on a value in the data rather than on a field path. For example, it can remove Google Drive files labeled **Confidential** from search results, or block agents from posting to an externally shared Slack channel. Unlike a field-path rule, a conditional rule applies to every tool on the server you select — there is no per-tool scoping. ## Supported servers Conditional rules are available for these Barndoor-hosted MCP servers from the MCP server directory: > [card] [Google Drive](/how-tos/data-control-center/field-controls/conditional-rules/google-drive) > > Match files by their Google Drive labels and label options. > [card] [Slack](/how-tos/data-control-center/field-controls/conditional-rules/slack) > > Match messages and posts by channel or channel type. **Add Conditional Rule** is unavailable until your organization has a **Slack (User)** or **Google Drive** server. ## Before you start Connect the server's **service account** — the organization-level OAuth connection on the server detail page. Barndoor uses it to list live values, such as your Drive labels or Slack channels, while you build a rule. If it isn't connected, the rule dialog prompts you to connect it. ## Rule settings | Setting | What it does | | - | - | | **Name** | A descriptive name for the rule | | **Server** | The Slack (User) or Google Drive server the rule applies to | | **Target Group / Role** | Groups or roles the rule applies to. Leave empty to apply to all users | | **When** | The condition and values to match, such as **Labels** or **Channel** | | **Applies to** | **All tools** (reads and writes), **Read** (tool results), or **Write** (create, update, and delete calls) | | **Then** | **Filter** removes matching items from results. **Block** denies matching calls or results | ## How Applies to and Then combine ![Applies to options All tools, Read, and Write, and Then options Filter and Block, with Read and Filter selected](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-drive--applies-to-then.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=604268805db1542785ccaf885550744f) | Applies to | Filter | Block | | - | - | - | | **Read** | Returns the result with matching items removed | Denies the tool result if any item matches | | **Write** | Not available — writes are always blocked outright | Denies the tool call if any item matches | | **All tools** | Returns results with matching items removed, and denies matching tool calls | Denies matching tool calls and tool results | ## Create a conditional rule 1. Navigate to **Data Control Center → Field Controls**. 2. Click **Add Conditional Rule**. 3. Fill in the [rule settings](#rule-settings), then click **Add Rule**. For the conditions and values each server supports, see [Google Drive](/how-tos/data-control-center/field-controls/conditional-rules/google-drive) and [Slack](/how-tos/data-control-center/field-controls/conditional-rules/slack). # Google Drive conditional rules Source: https://docs.barndoor.ai/how-tos/data-control-center/field-controls/conditional-rules/google-drive Filter or block files by their Drive labels on the Barndoor-hosted Google Drive MCP server. A Google Drive [conditional rule](/how-tos/data-control-center/field-controls/conditional-rules) matches files by their Google Drive labels. For example, you can remove files labeled **Confidential** from search results for the Finance group, or block agents from changing them. Setup has three steps: 1. [Prepare your Google Drive labels](#1-prepare-your-google-drive-labels) in the Google Admin console. 2. [Connect the Google Drive MCP server](#2-connect-the-google-drive-mcp-server) in Barndoor so it can read those labels. 3. [Create the conditional rule](#3-create-the-conditional-rule) in Field Controls. This guide applies to the Barndoor-hosted [Google Drive MCP server](/mcp-servers/google_drive) available in the MCP server directory. It does not apply to Google's official remote Drive MCP server. ## Prerequisites You need: * Admin access to your Barndoor organization * A Google Workspace edition that supports [Drive labels](https://developers.google.com/workspace/drive/labels/guides/create-label) * At least one published, Drive-enabled label in your Google Workspace * A Google Workspace user who can view the labels you want Barndoor to discover ## 1. Prepare your Google Drive labels Barndoor discovers existing labels; it does not create or publish the label taxonomy. Set up the labels in Google first. 1. Open [Label manager](https://admin.google.com/ac/dc/labels) in the Google Admin console, or navigate to **Security → Access and data control → Label manager**. You need the **Manage Classification Labels** privilege. 2. On **Classification labels**, create the labels your organization needs. 3. Enable the labels for Drive and publish them. Published Drive-enabled labels show **Drive** under **Applications** and **Published** under **Status**. Only published, Drive-enabled labels visible to the connected identity appear in Barndoor. > [!NOTE] > > If you lack that privilege, Google may send you to `/permissiondenied` or a > redirect-loop error. That is an authorization failure, not a broken link. > [!TIP] > > Before continuing, confirm that at least one label is published and enabled for > Drive in Label manager. ## 2. Connect the Google Drive MCP server > [!NOTE] > > In this guide, **service account** means the organization-level OAuth connection > on the Barndoor server detail page. It does not mean a Google Cloud IAM service > account. Connect a Google Workspace user that can view the labels you need. Barndoor's stored public OAuth credentials for Google Drive include the restricted `drive.labels.readonly` scope, so most organizations can use them as-is for label discovery. 1. Navigate to **Admin → MCP Servers**. 2. Add **Google Drive** from the Barndoor-hosted MCP server directory, or open an existing Google Drive server. 3. Leave **Use stored public OAuth credentials** enabled unless you already use a private client. 4. Confirm **Scopes** includes: ```text theme={null} https://www.googleapis.com/auth/drive.labels.readonly ``` New servers inherit this from the catalog. An existing server may still have an older snapshotted list. If Labels is missing, add it or click **Reset to default scopes**. 5. Save the server configuration. 6. On the server detail page, connect the service account that conditional rules will use for live label discovery. If the server was already connected, reconnect it after changing scopes. Existing OAuth grants do not automatically receive newly added scopes. On the Google consent screen, confirm that access to Drive labels is included. `drive.labels.readonly` is the least-privilege scope for label discovery (`list_labels` / `list_file_labels`). It does not let Barndoor apply labels or edit files. For that, see [Enable write tools on existing files](#enable-write-tools-on-existing-files). > [!TIP] > > The service account connection should show as connected, and the completed > Google consent flow should include access to Drive labels. ### Use a private OAuth client A private client is optional for label discovery. Keep it if you already configured one. You need one to [enable write tools on existing files](#enable-write-tools-on-existing-files), and you may also want one if you need scopes beyond the catalog defaults or want label traffic to run through your own Google Cloud project. 1. In a Google Cloud project, enable the [Drive Labels API](https://console.cloud.google.com/apis/library/drivelabels.googleapis.com) and the [Google Drive API](https://console.cloud.google.com/apis/library/drive.googleapis.com). 2. Create a **Web application** OAuth client and add the production redirect URI from [Redirect URI Allowlisting](/how-tos/redirect-uri-allowlisting): ```text theme={null} https://app.barndoor.ai/callback ``` If you are connecting from a Barndoor trial hostname, allowlist that hostname's `/callback` URI as well. 3. On **Google Auth Platform → Data Access**, add every scope Barndoor will request, including the default Google Drive scopes, `drive.labels.readonly`, and `drive` if you need write tools on existing files. Adding a scope on Data Access only makes it **available** to request. Barndoor must also list it on the server instance, then the user must reconnect. `drive` is a restricted scope. If your OAuth app's **Audience** is **Internal**, users in your Workspace can grant it without Google verification. An **External** app needs Google's restricted-scope verification first. 4. On the Google Drive server in Barndoor, turn off **Use stored public OAuth credentials**, paste the Client ID and Client Secret, confirm **Scopes** includes `drive.labels.readonly` (and `drive` for write tools on existing files), and save. 5. Connect or reconnect the service account. > [!NOTE] > > The **Drive Labels API** provides the label taxonomy. The **Google Drive API** > provides file search and file-label access. Enabling the separate **Drive MCP > API** does not enable these tools. Tenants already on private OAuth can keep it. Switching back to stored public credentials is optional and is not required for label discovery. ### Enable write tools on existing files The catalog's default write scope is `drive.file`, which only covers files the Barndoor OAuth app created or that the user opened with it. Write tools called on any other file, which includes most of your existing Docs, Sheets, and folders, fail with `appNotAuthorizedToFile`. This applies to `update_file_labels` as well as `update_file`, `rename_file`, `move_file`, and `create_permissions`. To let these tools act on existing files, an admin must: 1. Add the full Drive scope to the Google Drive server's **Scopes**: ```text theme={null} https://www.googleapis.com/auth/drive ``` 2. Switch the server to your own OAuth client. Barndoor's stored public OAuth credentials do not include the `drive` scope, so turn off **Use stored public OAuth credentials** and follow [Use a private OAuth client](#use-a-private-oauth-client). 3. Reconnect the service account and any users who already connected, and approve the new Drive access on the Google consent screen. > [!WARNING] > > `drive` grants read and write access to every file the connected user can > access. Use [Field Controls](/how-tos/data-control-center/field-controls) and > [MCP Policies](/how-tos/data-control-center/mcp-policies) to limit which > tools agents can call and what they can see. `update_file_labels` also needs the connected user to have permission to apply that label, as configured in Label manager. Without the `drive` scope, an agent can still work on a copy: `copy_file` creates a file the connector owns, and write tools can change that copy. People working on the original file won't see those changes. ## 3. Create the conditional rule With labels published and the service account connected, you can build the rule. 1. Navigate to **Data Control Center → Field Controls**. 2. Click **Add Conditional Rule**. 3. Enter a **Name** and select your Google Drive server under **Server**. 4. Optionally, add groups or roles under **Target Group / Role**. Leave it empty to apply the rule to all users. 5. Under **When**, select **Labels**, then choose one or more labels or label options. See [Choose labels and label options](#choose-labels-and-label-options). 6. Under **Applies to**, choose **All tools**, **Read** (tool results), or **Write** (create, update, and delete calls). 7. Under **Then**, choose **Filter** to remove matching files from results, or **Block** to deny matching calls or results. **Filter** isn't available for **Write**: writes are always blocked outright. 8. Click **Add Rule**. ![Add Conditional Rule dialog for Google Drive with the Confidential and RESTRICTED labels selected, applying to Read with the Filter action](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-drive--live-labels.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=53a5c679c2b8dff85a7fef8c15a60531) The live list is loaded with the service account connection on the selected Google Drive server. If the service account isn't connected, the **When** section prompts you to connect it. Click **Connect service account**, complete the OAuth flow, and retry the search. ![When section prompting you to connect the service account to load Drive labels](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-drive-labels--managed-connect--when.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=6f2edc8a8547dc6b98d6f8cde4a352de) > [!TIP] > > Your organization's published labels should appear in the live results when > you search under **Labels**. ### Choose labels and label options The **Labels** list includes every published label the service account can see, plus each option of a label's selection fields, listed by its display name. For example, a **Sensitivity** label with **Confidential** and **Internal** options appears as three entries. | You select | The rule matches | | - | - | | A label | Any file that has the label applied, whatever its field values | | A label option | Files where that option is selected on the label | | A typed title | Labels or options whose title matches, ignoring case | | A pattern with `*` (for example `CONFIDENTIAL-*`) | Every label or option whose title matches the pattern | Pick from the list where you can. Listed labels and options are matched by ID, so the rule keeps working if someone renames the label. Typed titles and patterns are matched by title, so renaming a label can break them. Use them for labels the service account can't see. If you type the title of a label that is listed, Barndoor uses the listed label instead. Typed titles follow these rules: * Case is ignored, but spaces, `-`, and `_` must match exactly: `Confidential-*` does not match **Confidential Internal**. * Titles can use letters, numbers, spaces, `-`, and `_`, with `*` as a wildcard. For a title with other characters, pick the label from the list. * `*` on its own isn't allowed, because it would match every labeled file. Pick the labels to cover, or add text around the `*`. ![When section with the listed label Confidential and the typed title Confidential-\* selected](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-value-picker--drive-live-labels.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=d48c85173e97d1e3408315e2bf514cfa) ### What a rule matches * **Read** checks the files that Google Drive tools return, such as search, list, get, and export results. **Filter** removes matching files and returns the rest. **Block** denies the whole result if any file matches. Files without a matching label pass through. * **Write** checks the file a write tool acts on, for example `update_file`, `rename_file`, `move_file`, `trash_file`, `create_permissions`, or `update_file_labels`. Barndoor looks up the target file's labels before the call runs and blocks the call if they match. * **All tools** applies both checks. ## Verify the setup You can verify label discovery in either place: * In **Field Controls**, the **Labels** condition of a conditional rule shows your published label titles in the live results. * Through the Google Drive MCP server, the `list_labels` tool returns the published label taxonomy. To verify a label on a specific file, apply the label in Google Drive and call `list_file_labels` with that file's ID. ## Troubleshooting > [accordion] list\_labels returns a 403 for drivelabels.googleapis.com > > On stored public OAuth, the Drive Labels API must be enabled on Barndoor's > managed Google Cloud project. Contact Support if the error persists after > you reconnect. > > On a private OAuth client, enable the **Drive Labels API** on the Google > Cloud project that owns that client. Wait a few minutes, then retry. > [accordion] File search returns a 403 saying the Drive API is disabled > > On stored public OAuth, contact Support. On a private client, enable the > **Google Drive API** on the same project, wait a few minutes, and retry. > [accordion] The Google consent screen omits Labels or Drive file scopes > > In Field Controls, the **When** section reports that the connected Google > identity did not grant access to read Drive labels. > > ![When section reporting that the connected Google identity did not grant access to read Drive labels, with a Reconnect service account button](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-drive-labels--scope-required-managed--when.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=f6a36d52241e13412f50ca732cf46bb4) > > Confirm that **Scopes** on the Google Drive server includes > `drive.labels.readonly`. If the instance still has an older snapshotted > list, add the scope or click **Reset to default scopes**, then reconnect > the service account. Existing grants do not receive new scopes > automatically. > > If you use a private OAuth client, also confirm that **Data Access** on > that client lists every scope Barndoor will request, including the default > Drive scopes and `drive.labels.readonly`. > [accordion] Label manager shows permission denied or a redirect loop > > You are not authorized for [Label > manager](https://admin.google.com/ac/dc/labels). Ask a Google Workspace > super admin to grant **Manage Classification Labels**, then retry. The > URL is correct even when Google redirects to `/permissiondenied`. > [accordion] No published Drive labels are visible > > ![When section reporting that no published Drive labels are visible to the connected Google identity, with a Retry button](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-drive-labels--no-visible-labels--when.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=4d47162bf68e7c121e25226f5b3c9a43) > > Confirm that the labels are published, enabled for Drive, and visible to the > Google Workspace user connected through Barndoor's organization-level > service account connection. An empty list usually means the API and OAuth > grant are working but that user cannot see any eligible labels. You can > still type a label title or a pattern for a label that isn't listed. > [accordion] A write tool returns appNotAuthorizedToFile > > The default `drive.file` scope can write only files this OAuth app created > or that the user opened with it. Adding `drive.labels` does not change > that. Add the `drive` scope on a private OAuth client and reconnect. See > [Enable write tools on existing > files](#enable-write-tools-on-existing-files). Otherwise, apply the label > in the Drive UI, or have the agent edit a copy made with `copy_file`. ## Limitations * Barndoor discovers existing labels but does not create or publish the label taxonomy. There is no `create_label` tool on the Google Drive connector. * Reading labels on an existing file works with the default scopes. Applying labels or running other write tools on files Barndoor did not create needs the `drive` scope on your own OAuth client. * Stored public OAuth is enough for label discovery. A private client is optional unless you need write tools on existing files. # Slack conditional rules Source: https://docs.barndoor.ai/how-tos/data-control-center/field-controls/conditional-rules/slack Filter or block Slack messages by channel or channel type on the Barndoor-hosted Slack (User) MCP server. A Slack [conditional rule](/how-tos/data-control-center/field-controls/conditional-rules) matches Slack activity by the channel it happens in. For example, you can remove messages from `#finance` when the Support group reads Slack, or stop agents from posting to externally shared channels. Setup has two steps: 1. [Connect the Slack (User) MCP server](#1-connect-the-slack-user-mcp-server) in Barndoor so it can list your workspace's channels. 2. [Create the conditional rule](#2-create-the-conditional-rule) in Field Controls. This guide applies to the Barndoor-hosted **Slack (User)** [MCP server](/mcp-servers/slack) from the MCP server directory. Conditional rules are not available for Slack Bot or other Slack servers. ## Prerequisites You need: * Admin access to your Barndoor organization * A Slack user who can see the channels you want to govern ## 1. Connect the Slack (User) MCP server > [!NOTE] > > In this guide, **service account** means the organization-level OAuth > connection on the Barndoor server detail page. Barndoor uses it to list your > workspace's channels when you build a rule. 1. Navigate to **Admin → MCP Servers**. 2. Add **Slack (User)** from the Barndoor-hosted MCP server directory, or open an existing **Slack (User)** server. 3. On the server detail page, connect the service account with a Slack user who can see the channels you want to govern. The channel list includes the public and private channels that user can see, including archived channels. If the service account isn't connected when you create a rule, the **When** section prompts you to connect it. Click **Connect service account**, complete the Slack OAuth flow, and continue. ## 2. Create the conditional rule With the service account connected, you can build the rule. 1. Navigate to **Data Control Center → Field Controls**. 2. Click **Add Conditional Rule**. 3. Enter a **Name** and select your **Slack (User)** server under **Server**. The rule applies to every tool on the server. 4. Optionally, add groups or roles under **Target Group / Role**. Leave it empty to apply the rule to all users. 5. Under **When**, choose a condition: * **Channel**: specific channels. See [Choose channels](#choose-channels). * **Channel type**: every channel of a kind. See [Choose channel types](#choose-channel-types). 6. Under **Applies to**, choose **All tools**, **Read** (tool results), or **Write** (create, update, and delete calls). 7. Under **Then**, choose **Filter** to remove matching items from results, or **Block** to deny matching calls or results. **Filter** isn't available for **Write**: writes are always blocked outright. 8. Click **Add Rule**. ![Add Conditional Rule dialog for Slack (User) with the #finance channel selected, applying to Read with the Filter action](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-dialog-slack--live-channels.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=7c167140a04ba2e63b60f7e6f122f07b) ### Choose channels Search the list of channels from your workspace and select one or more. You can also type a channel name, or a wildcard pattern such as `proj-*` or `*-prod`, for channels that aren't listed. ![When section with the listed channels #general and a saved channel, plus the typed name proj-\*](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-value-picker--slack-live-channels.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=2a5f4a5d10fbf0036eec8a6786320647) | You add | Stored as | After a channel is renamed | | - | - | - | | A channel from the list | The channel's ID | The rule still matches | | A typed name or wildcard | The text you typed | The rule may stop matching | Pick from the list where you can. If you type the name of a channel that is listed, Barndoor uses the listed channel's ID instead. Typed names are for channels the service account can't see. Hover the info icon next to the condition description for a reminder: ![Choosing Slack channels hint explaining that listed channels are stored by ID and typed names or wildcards are stored as text](https://mintcdn.com/barndoor/jYjKzlrvisdEId-v/images/data-control-center/platform-data-protection-conditional-rules-value-picker--slack-channels-hint.png?fit=max\&auto=format\&n=jYjKzlrvisdEId-v\&q=85\&s=3854bfa1ea230cbb6827f7719a0f396c) A few entries aren't accepted: * **Pasted Slack IDs or channel links.** Pick the channel from the list, or type its name. * **A wildcard on its own**, such as `*`. To cover every channel of a kind, use a **Channel type** rule instead. > [!NOTE] > > Large workspaces can take a moment to load. Barndoor loads up to 2,000 > channels. If the list isn't complete, the **When** section says so. Search > it, or type the name of a channel that isn't shown. ### Choose channel types **Channel type** matches every conversation of the kinds you select: | Option | Matches | | - | - | | **Public channel** | Public channels | | **Private channel** | Private channels | | **Direct message** | One-to-one direct messages | | **Group DM** | Group direct messages | | **Externally shared** | Channels shared with another organization through Slack Connect, including pending shares | Each conversation has exactly one type. When more than one applies, the first match in this order wins: **Externally shared**, then **Direct message** or **Group DM**, then **Private channel**, then **Public channel**. For example, a private channel shared with a partner organization is **Externally shared**, so a **Private channel** rule doesn't match it. Select both types to cover it. ### What a rule matches * **Read** checks the channels, messages, and files that Slack tools return. **Filter** removes matching items and returns the rest. **Block** denies the whole result if any item matches. * **Write** checks where a message is posted. Before the message is sent, Barndoor looks up the target channel and blocks the post if it matches. * **All tools** applies both checks. ## Examples **Hide finance channels from the Support group:** * When: **Channel** is `#finance`, `#finance-ops` * Applies to: **Read** * Then: **Filter** * Target Group / Role: `customer-support` **Stop agents from posting to externally shared channels:** * When: **Channel type** is **Externally shared** * Applies to: **Write** * Then: **Block** **Keep project channels out of agent reads and writes:** * When: **Channel** is `proj-*` (typed wildcard) * Applies to: **All tools** * Then: **Block** ## Troubleshooting > [accordion] A channel is missing from the list > > The list only shows channels the connected service account can see, up to > 2,000 channels. Type the channel name instead, or reconnect the service > account with a Slack user who is a member of that channel. > [accordion] "Pasted Slack ids are not saved" > > Barndoor doesn't save channel IDs or links that you paste. Pick the channel > from the list, or type its name. > [accordion] "That looks like a Slack ID" > > The value you typed looks like a Slack channel ID. Type a lowercase channel > name such as `proj-*`, or pick the channel from the list. > [accordion] "To cover every channel, use a Channel type rule" > > A wildcard on its own, such as `*` or `#*`, isn't accepted. Create a rule > with **When** set to **Channel type** and select the kinds of channel to > cover. # Masking & Partial Redaction Source: https://docs.barndoor.ai/how-tos/data-control-center/masking Replace a detected value with a placeholder, or keep the first or last few characters readable and mask the rest — credit-card style. The **Mask** action replaces a detected value in place. By default the whole value becomes a typed placeholder such as ``. With a **mask format**, the value keeps its shape: the first or last few characters stay readable and everything else is replaced with a mask character, the way a receipt shows `XXXX XXXX XXXX 1234`. Use masking when an agent or a downstream tool still needs to *recognise* a value without *seeing* it — matching a support ticket to an account by its last four digits, telling two commit SHAs apart by their prefix, or keeping a record id searchable. > [!NOTE] > > Masking is irreversible. If you need to restore the original value later, use **Tokenize** instead. If nothing downstream needs the value at all, **Redact** or **Block** is the safer choice. ## Mask versus Redact and Tokenize | Action | Output | Reversible | Value stays recognisable | | - | - | - | - | | **Redact** | `<…:REDACTED>` placeholder | No | No | | **Mask** (no format) | `` | No | No | | **Mask** (keep last 4) | `XXX-XX-6789` | No | Yes | | **Tokenize** | `` reversible token | Yes, via detokenize | No | Mask is available on every profile type that reports it under **Supported Actions** on the Protection Profiles dashboard, and on both MCP policies and LLM policies. ## Choose Mask in a policy Masking is configured per policy, in the **Profiles & Action** step of the MCP policy wizard or the LLM policy wizard. 1. Create or edit a policy ([MCP Policies](/how-tos/data-control-center/mcp-policies)). 2. In **Profiles & Action**, select the protection profiles to run. 3. Set **Action** to **Mask**. The **Mask format** panel appears under the action. ![MCP policy wizard on the Profiles & Action step with Mask selected](https://mintcdn.com/barndoor/yevux3y69kkMDW-p/images/data-control-center/platform-data-protection-mask-format--mcp-policy-wizard.png?fit=max\&auto=format\&n=yevux3y69kkMDW-p\&q=85\&s=2acea213051e94e70749bac73e8268b7) 4. Choose a **Mask format** (see below), then save the policy. The format applies to every value the policy's profiles detect. To mask different types differently — for example last-4 for SSNs and first-8 for order ids — create two policies with single-type profiles and order them by priority. ## Mask formats ### Full placeholder The default. Every detected value becomes ``, where `TYPE` is the detection type (`SSN`, `CREDIT_CARD`, and so on). This is the same behaviour as Redact with a different label, and it is what existing Mask policies do. ### Keep suffix Keeps the **last N characters** readable and masks the rest. This is the card and SSN convention: the tail is enough to match a record, and the head is what makes the value sensitive. ![Mask format set to Keep suffix, keeping the last 4 characters](https://mintcdn.com/barndoor/yevux3y69kkMDW-p/images/data-control-center/platform-data-protection-mask-format--keep-suffix.png?fit=max\&auto=format\&n=yevux3y69kkMDW-p\&q=85\&s=61f516a79a5ee95ed559bc1275e06f3c) | Setting | Meaning | | - | - | | **Keep last (characters)** | How many characters at the end stay readable, 1 to 16. Separators count. | | **Mask character** | The character written over the hidden part. Default `X`. One character; not a digit, not a space, and not `<`, `>`, `"` or `\`. | | **Keep separators** | On by default. Dashes, spaces and dots inside the masked region are left in place so `111-22-6789` becomes `XXX-XX-6789` rather than `XXXXXX6789`. | The **Preview** line shows the format applied to a sample card number, exactly as the runtime would render it. ### Keep prefix Keeps the **first N characters** readable and masks the rest. Use it for identifiers whose leading part is the meaningful one: a commit SHA, an order or record id with a fixed prefix, an API key's vendor prefix. ![Mask format set to Keep prefix, keeping the first 8 characters with \* as the mask character](https://mintcdn.com/barndoor/yevux3y69kkMDW-p/images/data-control-center/platform-data-protection-mask-format--keep-prefix.png?fit=max\&auto=format\&n=yevux3y69kkMDW-p\&q=85\&s=2b31f3bdc606b1318cbc04bba469f53b) The settings are the same as Keep suffix, with **Keep first (characters)** in place of Keep last. ## Examples With **Keep separators** on and `X` as the mask character: | Detected value | Format | Result | | - | - | - | | `111-22-6789` (SSN) | Keep suffix 4 | `XXX-XX-6789` | | `111-22-6789` (SSN) | Keep prefix 7 | `111-22-XXXX` | | `4111 1111 1111 1234` (card) | Keep suffix 4 | `XXXX XXXX XXXX 1234` | | `9f86d081884c7d659a2f…` (40-character SHA) | Keep prefix 8 | `9f86d081XXXXXXXX…` | | `ACCT-Zoë-00917` (custom type) | Keep prefix 8 | `ACCT-Zoë-XXXXX` | | `555-0142` (phone) | Keep prefix 8 | `` — see the reveal floor below | Characters are counted the way a person reads them, not as bytes: an accented letter or an emoji is one character. The masked value is emitted bare, not wrapped in `<…>`. That keeps the residue usable in a follow-up tool call, and re-scanning already-masked output with the same policy leaves it unchanged. ## What is always fully masked Two safeguards stop a partial format from revealing more than intended. Both fall back to the **full placeholder**, never to passing the value through. ### The reveal floor A partial format is only applied when enough of the value is actually hidden: **at least 4 characters, and at least a third of the value's letters and digits**. Otherwise the whole value becomes ``. This lets the standard forms through (last-4 of a 9-digit SSN, first-6 and last-4 of a 16-digit card) and rejects the abuses (keep 12 of a 16-digit card, keep 8 of a 10-digit phone number). A format tuned for 40-character SHAs cannot leak most of a short phone number the same profile happens to catch. ### Free-text and payload-level types Some detection types have no meaningful prefix or suffix to keep. Values of these types are always fully masked, whatever format the policy sets: * **Names, places and addresses** — `PERSON`, `ORGANIZATION`, `LOCATION`, `ADDRESS` * **Emails and dates of birth** — `EMAIL`, `DATE_OF_BIRTH` * **Passwords** — every character is secret; there is no conventional visible tail * **Payload-level verdicts** — prompt injection, guardrail interventions, code-execution and obfuscation findings When a selected profile emits one of these types, the Mask format panel lists it under the settings so you know which of the policy's detections will get the placeholder instead. ![Mask format panel noting that EMAIL, LOCATION and PERSON are always fully masked](https://mintcdn.com/barndoor/yevux3y69kkMDW-p/images/data-control-center/platform-data-protection-mask-format--free-text-types-always-fully-masked.png?fit=max\&auto=format\&n=yevux3y69kkMDW-p\&q=85\&s=91d944abcf8cd5567c92b71c340846b1) Everything pattern-shaped is eligible for partial masking: government and financial identifiers, phone numbers, every secret and API-key type, and all [custom detection types](/how-tos/data-control-center/protection-profiles#create-a-custom-detection-type). ## Custom patterns are full-match A custom regex detection type always masks the **whole** match. A pattern such as `^(.{8}).*$` does not keep the first eight characters — capture groups are ignored, and the pattern matches the entire line, so the entire line is masked. To keep a prefix, write the pattern to match the identifier itself and set the policy's mask format to **Keep prefix**. ## Verify a mask policy * **Test Workbench** — go to **Data Control Center → Test**, paste a sample payload, and run the policy. The output shows the masked form the runtime will produce. * **Dry run** — turn on **Dry Run** on the policy to record detections without rewriting anything, then check **Detection Activity** to see what the policy would mask. * **Audit** — each masked finding's audit record carries how many characters were left readable and whether the reveal floor forced the full placeholder. The revealed text itself is never recorded. ## API The same setting is exposed on the enforcement-policy API as an optional `mask_format` object, valid only when `action` is `POLICY_ACTION_MASK`: ```json theme={null} { "action": "POLICY_ACTION_MASK", "mask_format": { "keep": "SUFFIX", "keep_chars": 4, "mask_char": "X", "preserve_separators": true } } ``` Omit it, or send `null`, for the full placeholder. Sending a format with any other action is rejected. The detection-type catalog reports `partial_mask_eligible` for each type. > [!NOTE] > > The Terraform provider's `enforcement_policy` resource does not yet expose `mask_format`. Configure it through the console or the API until that binding ships. # MCP Policies Source: https://docs.barndoor.ai/how-tos/data-control-center/mcp-policies Govern enforcement on MCP tool calls — the structured requests and responses between AI agents and connected servers. An **MCP Policy** governs what happens when a protection profile's detections fire on **MCP tool calls** — the structured requests and responses that flow between AI agents and connected servers (Salesforce, ticketing systems, internal APIs, and so on). > [!NOTE] > > At least one [Protection Profile](/how-tos/data-control-center/protection-profiles) must exist before you can create an MCP policy. ## View your MCP policies Navigate to **Data Control Center → MCP Policies**. ![MCP Policies overview](https://mintcdn.com/barndoor/7paGZw3np6ad1pBK/images/data-control-center/platform-data-protection-mcp-policies--overview.png?fit=max\&auto=format\&n=7paGZw3np6ad1pBK\&q=85\&s=3db90e2eb6edf4ceb02d72f3d2b005aa) The policy list shows each policy with: * **Order** / **Priority** — policies run in priority order; lower numbers run first * **Policy name** * **MCP Server** — which server(s) this policy targets * **Audience** — which groups or roles it scopes to (blank = everyone) * **Protection Profiles** — the detection engines attached * **Last Updated** — who changed it and when * **Status** — Active or Dry Run * **Action** — Block, Redact, Alert Only, etc. Policies are grouped by their audience scope: **All Users** (unscoped) and **Audience-Specific** (scoped to groups or roles). ## Create a policy 1. Click **New policy** at the top of the MCP Policies tab. 2. **Name** — enter a clear, descriptive name that captures what the policy protects and why. For example: * *Block regulated customer identifiers across revenue and support tool calls* * *Redact credentials before MCP responses return to agents* 3. **MCP Server** — choose the server this policy applies to. You can also select **All Servers** to apply the policy globally. > [!WARNING] > > Once the policy is saved, the MCP server cannot be changed. To target a different server, create a new policy. 4. **Protection Profiles** — select one or more profiles to run. All selected profiles run in parallel on matching traffic. 5. **Action** — choose what to do when any detection fires: | Action | Effect | | - | - | | Block | Rejects the request or response entirely | | Redact | Replaces detected spans with typed placeholders | | Mask | Replaces detected spans with a placeholder, or keeps a prefix or suffix readable and masks the rest — see [Masking & Partial Redaction](/how-tos/data-control-center/masking) | | Tokenize | Replaces detected spans with reversible tokens | | Alert Only | Logs the detection and passes traffic through unchanged | | Bypass | Explicitly exempts this traffic from enforcement | When you choose **Mask**, a **Mask format** panel appears under the action. Leave it on **Full placeholder**, or pick **Keep prefix** / **Keep suffix** and set how many characters stay readable. 6. **Scope (optional)** — add groups or roles to restrict who this policy applies to. Leave blank to apply the policy to everyone. 7. **Dry run** — toggle on to observe detections without enforcing the action. Useful for validating a policy before activating it. 8. Click **Save**. ## Edit a policy 1. Find the policy in the list. 2. Click **⋮ → Edit** on the policy row. 3. Update any field except the MCP Server. 4. Save the changes. The updated policy takes effect within seconds. ## Change policy priority Policies run in priority order — lower numbers run first. When multiple policies match the same traffic, the first matching policy's action is applied. To change priority, drag a policy row up or down using the **⠿** drag handle on the left. The updated order saves immediately. ## Delete a policy 1. Click **⋮ → Delete** on the policy row. 2. Confirm the deletion. Deleted policies are removed immediately and stop enforcing. Historical detection events attributed to the policy remain in the audit log. ## Test a policy ### Using dry run Enable **Dry run** on the policy before activating it. In dry run mode the policy evaluates traffic and logs detection events but does not block or modify anything. After a few minutes of real traffic, check **Detection Activity** to see what the policy would have caught. When you are satisfied with the coverage, edit the policy and disable dry run to activate enforcement. ### Using the Test Workbench For controlled testing without live traffic: 1. Navigate to **Data Control Center → Test**. 2. Choose the **MCP** mode and select the server and tool to simulate. 3. Paste a sample tool payload. 4. Run the test and review which policies matched, which detection types fired, and what the redacted output would look like. ### Verifying in the Audit Center After a policy has been active for some time: 1. Navigate to **Audit Center** from the main navigation. 2. Filter by **Event type → Data Protection** to see policy enforcement events. 3. Each event shows the policy name, detection type, action taken, the tool call involved, and the principal context. To see all enforcement activity for a specific policy, click the policy name in the audit log — it links directly to the policy configuration. ## Common patterns **Global block on secrets across all MCP traffic:** * Server: All Servers * Profiles: Your secrets detection profile * Action: Block * Scope: (none — applies to everyone) **Audit-only monitoring for a new integration:** * Server: the new integration's MCP server * Profiles: your PII and secrets profiles * Action: Alert Only * Dry run: on (initially) * Promote to active enforcement after reviewing activity logs **Scope a strict policy to a high-sensitivity team:** * Server: Revenue Ops Salesforce * Profiles: Regulated identifiers profile * Action: Block * Scope: Group `enterprise-customer-success-managers` A separate, less-restrictive policy for the same server (scoped to everyone else) can use Alert Only — the stricter scoped policy runs first for matching principals. # Data Control Center Source: https://docs.barndoor.ai/how-tos/data-control-center/overview Detect, block, redact, or observe sensitive data as it flows through AI agents and the MCP layer. The Data Control Center is where platform administrators configure how sensitive data is handled as it moves through AI agents and the MCP layer. It gives security teams a single place to define **what** data is sensitive, **where** to enforce protection, and **what to do** when a detection fires. ![Data Control Center overview](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/trial-dcc-overview.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=7fb8e51e043f5b3fb23bc27674c2f526) ## How it works Every prompt sent to an LLM, every response returned, and every MCP tool call — input and output — flows through the platform's inspection layer. The Data Control Center controls that layer through three building blocks: 1. **Protection Profiles** — define what to detect (email addresses, AWS keys, credit cards, custom patterns, etc.) 2. **MCP Policies** and **LLM Policies** — define where to enforce and what action to take when a detection fires 3. **Field Controls** — define which JSON fields to pass through or remove from specific tool outputs, independently of text-based detection The flow is always the same: add profiles first, then attach them to policies. ## Core concepts ### Protection Profile A **Protection Profile** is a named detection engine. It bundles together a set of detection types (e.g., "Social Security Number", "AWS Secret Access Key") with the runtime stages it scans and the actions it supports. Profiles are reusable — create one and attach it to many policies. When the detection logic changes, update the profile and all policies using it inherit the change automatically. **Built-in profile types:** | Type | What it detects | | - | - | | Sensitive Identifiers | Social Security Numbers, credit cards, emails, phone numbers, passports, dates of birth | | Names & Locations | Person names, organizations, addresses, locations | | Secrets | Cloud keys (AWS, GCP, Azure), API tokens, database credentials, CI/CD secrets, cryptographic material | | Prompt Injection | Prompt injection and jailbreak attempts | | Custom Detections | Patterns your organization defines using regex or literal rules | External providers (AWS Comprehend PII, AWS Bedrock Guardrails) are also available as catalog options. ### MCP Policy An **MCP Policy** governs what happens when a protection profile's detections fire on **MCP tool calls** — the structured calls AI agents make to connected servers (Salesforce, ticketing systems, internal APIs, and so on). Each policy specifies: * Which **MCP Server(s)** to apply to (or all servers) * Which **Protection Profiles** to run * The **action** to take when a detection fires * Optionally, which **groups or roles** the policy scopes to MCP policies inspect both the agent's tool input (what it sends to the tool) and the tool's response (what the tool returns to the agent). ### Field Controls **Field Controls** give you precise, field-level governance over structured tool output — independently of text-based detection. Instead of scanning free text for patterns, you name exact JSON field paths to either remove or allow through. Each rule specifies: * The **MCP Server** and **tool** it targets * The **direction** (input or output) * The **mode**: * **Redact listed** — the fields you name are removed; everything else passes through * **Allow only listed** — only the fields you name pass through; everything else is removed * Optionally, which **groups or roles** the rule scopes to Use field controls when you know the exact field paths — for example, always strip `AnnualRevenue` and `BillingAddress` from Salesforce Account records before an agent in the support group can read them. [Conditional rules](/how-tos/data-control-center/field-controls/conditional-rules) are field controls that match a value in the data instead — a Google Drive label or a Slack channel — and filter or block matching items across every tool on the server. ## Policy actions | Action | Effect | | - | - | | **Block** | Rejects the entire request or response. The agent receives an error. | | **Redact** | Replaces detected spans with a typed placeholder such as `[EMAIL_ADDRESS]`. The rest of the payload continues. | | **Mask** | Replaces detected spans with a placeholder, or keeps the first or last few characters readable and masks the rest (`XXX-XX-6789`). Irreversible. See [Masking & Partial Redaction](/how-tos/data-control-center/masking). | | **Tokenize** | Replaces detected spans with a reversible token the platform can detokenize later. | | **Alert Only** | Records a detection event and passes the payload through unchanged. Use for monitoring without enforcement. | | **Bypass** | Explicitly exempts matching traffic from further enforcement. | ### Dry run mode Any policy can be toggled into **dry run**. In dry run the policy runs and logs detections but does not enforce them. Use this to validate a new policy before making it active. There is also a **global dry run** that applies to all policies at once. ## Runtime stages | Stage | What it covers | | - | - | | **Request** | The message an agent sends to an LLM | | **Response** | The text the LLM returns to the agent | | **Tool Input** | The arguments an agent passes to an MCP tool | | **Tool Output** | The data the MCP tool returns to the agent | ## Enabling the runtime The global **Enabled** toggle at the top of the Data Control Center controls whether the inspection layer runs at all. When disabled, no policies execute and all traffic passes through uninspected. Changes take effect within seconds. ## In this section > [card] [Protection Profiles](/how-tos/data-control-center/protection-profiles) > > Create and manage detection engines that define what data to scan for. > [card] [MCP Policies](/how-tos/data-control-center/mcp-policies) > > Govern enforcement on MCP tool call traffic. > [card] [Field Controls](/how-tos/data-control-center/field-controls) > > Field-level JSON redaction for specific tools. > [card] [Masking & Partial Redaction](/how-tos/data-control-center/masking) > > Keep a prefix or suffix readable and mask the rest. # Protection Profiles Source: https://docs.barndoor.ai/how-tos/data-control-center/protection-profiles Create named detection engines that define which data types to scan for. Policies can't be created until at least one profile exists. A **Protection Profile** is a named detection engine. It defines which data types to scan for, which runtime stages to inspect, and which enforcement actions are available to policies that use it. Policies cannot be created until at least one profile exists. ## View your profiles Navigate to **Data Control Center → Protection Profiles**. ![Protection Profiles dashboard](https://mintcdn.com/barndoor/ycLd3Cg8QdOmsIcT/images/data-control-center/platform-data-control-center-protection-profiles--dashboard.png?fit=max\&auto=format\&n=ycLd3Cg8QdOmsIcT\&q=85\&s=aa532b09d4635847a2b4efc77066d15c) The dashboard lists every profile in your organization with: * **Profile name** — the display name you gave it * **Type** — the underlying detector (Regex Detector, Custom Regex, Classifier, External Provider) * **Supported Actions** — the enforcement actions available to policies that use this profile (Block, Redact, Mask, Tokenize, Alert Only, Bypass) ## Create a profile 1. Click **Add Protection Profile** in the top-right corner of the Protection Profiles tab. The catalog opens: ![Protection Profile catalog](https://mintcdn.com/barndoor/pLFO391oE4pFHeuq/images/data-control-center/platform-data-control-center-protection-profiles--catalog.png?fit=max\&auto=format\&n=pLFO391oE4pFHeuq\&q=85\&s=7d2a56741f534525f65c86a9dbd3ee36) 2. Choose a profile type: | Type | Best for | | - | - | | **Sensitive Identifiers** | SSNs, credit cards, emails, phone numbers, passports, dates of birth — structured personal data | | **Names & Locations** | Free-text NLP detection of people, organizations, and places | | **Secrets** | Cloud keys, API tokens, database credentials, CI/CD secrets, cryptographic material | | **Prompt Injection** | Detecting injection and jailbreak attempts in prompts and tool outputs | | **Custom Detections** | Your organization's own data patterns via regex or literal rules | | **AWS Comprehend PII** | Cloud-based PII detection via AWS Comprehend | | **AWS Bedrock Guardrails** | AWS-managed guardrails enforced at runtime | If a built-in type already exists in your org, the button reads **Add Another**. You can have multiple profiles of the same type with different detection-type selections. 3. On the configuration screen, give the profile a descriptive name (for example, "Regulated customer identifiers — revenue ops"). Select which detection types within the category to enable. 4. Click **Save** to create the profile. ## Edit a profile 1. On the Protection Profiles dashboard, find the profile you want to change. 2. Click the **⋮** menu on the right side of the row and select **Edit**. 3. Update the name or the enabled detection types. 4. Save the changes. All policies that reference this profile inherit the updated detection set immediately. ## Delete a profile 1. On the Protection Profiles dashboard, click **⋮ → Delete** on the profile row. 2. A confirmation modal lists any active policies that reference this profile. Deleting the profile removes it from those policies; policies that lose all profiles are archived automatically. 3. Confirm the deletion. > [!NOTE] > > Deleting a profile does not remove historical detection events that used it. Past audit records are preserved. ## Create a custom detection type Custom detection types let you define regex or literal patterns for data formats unique to your organization — for example, an internal customer ID with a known prefix. 1. On the Protection Profiles dashboard, click **New custom type**. 2. Enter a name, description, and one or more patterns: * **Regex** — a regular expression (e.g., `cust_[0-9]{8}`) * **Literal** — an exact string match 3. Save. The custom type becomes available when configuring any profile of type **Custom Detections**. ## Test that detections work Use the **Policy Test Workbench** to verify that a profile detects the data it should before attaching it to an enforcing policy. 1. Navigate to **Data Control Center → Test**. 2. Paste a sample payload containing the data you expect the profile to detect. 3. Select the runtime stage and choose the protection profiles to run. 4. Review the findings: which detection types fired, at what spans, and with what confidence. If a detection fires when you expect it to, the profile is configured correctly. If not, check that the relevant detection types are enabled in the profile's configuration. ## Monitor detection activity After profiles are running in production, check **Data Control Center → Detection Activity** to see what they are finding. Filter by detection type to see only the signals your profile generates. Each row shows the detection type, action taken, runtime stage, timestamp, and confidence score. # Connect Microsoft Entra ID as your IdP Source: https://docs.barndoor.ai/how-tos/entra-idp-setup Step-by-step guide for configuring Microsoft Entra ID (formerly Azure AD) as an OIDC Identity Provider with SCIM Provisioning ## Overview This guide walks you through configuring **Microsoft Entra ID** as an OIDC Identity Provider for Barndoor. Once complete, your users will be able to sign in to Barndoor with their Entra ID credentials and their group memberships will flow through for automatic role mapping. > [!NOTE] > > **Prerequisites**: > > * Admin access to your Barndoor account > * Admin access to a Microsoft Entra ID tenant (Global Administrator or Application Administrator role) > * Your Entra **Tenant ID** handy (find it on the Entra Overview page) > [!NOTE] > > For the generic, IdP-agnostic version of this flow (Okta, Google Workspace, JumpCloud, etc.), see the [Connect your IdP](/how-tos/idp-setup) guide. *** ## Part 1 — Configure the application in Entra You'll do all the Entra-side work first, then come back and configure Barndoor with the values you collect along the way. ### Step 1: Create the Enterprise App **1. Open Entra Enterprise Apps** In the [Microsoft Entra admin center](https://entra.microsoft.com), go to **Identity** → **Applications** → **Enterprise Apps**, then click **+ New application**, then click **+ Create your own application**. **2. Fill in the registration form** * **Input Name**: Anything you'd like (e.g. `Barndoor.ai`) * **App Type**: Choose the non-gallery option * **Click `Create`**. ![Entra register an enterprise application](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/01-enterprise-app-registration.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=595a131eabd0096cbbaf453156c3d377) **3. Go to the app registration** The following steps will involve configuring the app registration for this enterprise app. Go to **Identity** → **Applications** → **App registrations**, then find and click your newly created app. *** ### Step 2: Add the email claim to the ID token **1. Open Token configuration** From your new app registration's left nav, click **Token configuration** → **+ Add optional claim**. **2. Add the email claim** * **Token type**: **ID** (this is the one that matters for Barndoor) * Check the **email** claim and click **Add**. If Entra prompts you to enable the **email** Microsoft Graph permission to make this claim work, accept it. ![Add optional claim panel with ID token type selected and the email claim highlighted](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/02-token-config-email-claim.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=15f7b62c16d974209924f83c6699e5be) *** ### Step 3: Add the groups claim **1. Add groups claim** Still on **Token configuration**, click **+ Add groups claim**. **2. Choose which groups to include** Pick one of: * **Security groups** or **All groups** — simple, includes every group the user is in. * **Groups assigned to the application** — recommended for larger tenants; only sends groups that have been explicitly assigned to the Barndoor app. This keeps the token small and limits exposure. **3. Set the group identifier to sAMAccountName** Under **ID**, **Access**, and **SAML** sub-sections, change **Group ID** to **sAMAccountName**. ![Edit groups claim panel showing sAMAccountName selected under ID, Access, and SAML](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/03-groups-claim-samaccountname.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=78aad76c5c6f7312e463b328f01c1337) > [!TIP] > > Optionally, also tick **Emit groups as role claims** — this sends groups as `roles` instead of `groups`. By default Barndoor maps them as groups, which is what most teams want. Click **Add**. *** ### Step 4: Edit the manifest (two changes the UI can't make) There are two adjustments Entra's UI doesn't surface that you must make in the raw manifest. **1. Open the manifest editor** From the left nav, click **Manifest**. Use Ctrl/Cmd-F to find the `optionalClaims` block. ![Entra app manifest JSON open with optionalClaims block visible](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/04-manifest-essential-cloud-display-name.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=0b0c0fdf25eebe4ca9fb297985bbf913) **2. Mark the email claim as essential (ID token only)** Find the `email` entry **under `idToken`** and set `essential` to `true`: ```json theme={null} { "name": "email", "source": null, "essential": true, "additionalProperties": [] } ``` > [!WARNING] > > Only set `essential: true` on the entry inside `idToken`. Do **not** mark it essential in `accessToken` or `saml2Token`. **3. Add cloud\_displayname for groups** Find each groups entry (you'll see `sam_account_name` listed) and add `cloud_displayname` to `additionalProperties`. Do this in **all three** of `idToken`, `accessToken`, and `saml2Token`: ```json theme={null} { "name": "groups", "source": null, "essential": false, "additionalProperties": [ "sam_account_name", "cloud_displayname" ] } ``` This is the signal that tells Entra to emit group names rather than UUIDs. **4. Save the manifest** Click **Save** at the top of the manifest editor. *** ### Step 5: Grant API permissions **1. Add Microsoft Graph delegated permissions** From the left nav, click **API permissions** → **+ Add a permission** → **Microsoft Graph** → **Delegated permissions**. Tick the following four scopes: * `email` * `offline_access` * `openid` * `profile` Click **Add permissions**. ![Entra API permissions screen showing email, offline\_access, openid, profile granted for Microsoft Graph](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/05-api-permissions-microsoft-graph.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=9b963aadbc19bab62308422ca11ffcb1) **2. Grant admin consent** Back on the API permissions screen, click **Grant admin consent for *your tenant*** and confirm. The **Status** column should flip to green checkmarks for all four scopes. ![API permissions with the Successfully granted admin consent banner and all scopes showing green checkmarks](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/06-grant-admin-consent.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=325958ef7bb38797c31ba50882e32eca) *** ### Step 6: Create a client secret **1. Generate a new client secret** Go to **Certificates & secrets** → **Client secrets** tab → **+ New client secret**. * **Description**: e.g. `Barndoor SSO` * **Expires**: Max the value (`24 months` at time of writing). Entra requires an expiration. Click **Add**. **2. Copy the Value immediately** Once the secret is created, **copy the `Value` column (not the `Secret ID`)** to your clipboard. ![Entra Certificates and secrets page showing newly created client secret with Value column highlighted](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/07-client-secret-value.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=8014b1420c0e4fea5b0a6425c4a34707) > [!WARNING] > > Entra only displays the secret value **once**. As soon as you navigate away from this page it is masked permanently. If you miss it, you'll need to delete the secret and create a new one. > [!NOTE] > > **Mark your calendar.** When the secret expires (24 months max), SSO will silently break. Rotate it in Entra and update Barndoor's IdP config before the expiration date. *** ### Step 7: Collect the remaining values You'll need three more values from Entra before switching over to Barndoor. **1. Get the Application (client) ID** Go back to **Overview**. Copy the **Application (client) ID**. Also note your **Directory (tenant) ID** — you'll need it in Step 9. ![Entra app Overview page with Application (client) ID and Directory (tenant) ID visible in the Essentials panel](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/08-overview-application-id.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=37dabe37ce78777700e9b70d09b0e11e) **2. Get the Issuer URL from Endpoints** Still on **Overview**, click **Endpoints** in the top bar. A side panel opens with a list of URLs. Copy **OpenID Connect metadata document** (.well-known discovery). ![Entra Endpoints side panel listing OAuth, OpenID, SAML, and Federation metadata URLs](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/09-endpoints.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=f563e72a79f5aa6f729d9f590b7755b9) Open a new browser tab and navigate to that URL. It should display the OIDC Discovery document. From the document, copy the value for `issuer`. It should be the format of `https://login.microsoftonline.com/{tenant-id}/v2.0`. ![Entra Endpoints side panel listing OAuth, OpenID, SAML, and Federation metadata URLs](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/09-endpoints-openid-discovery.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=60b820e6c4a2d42f84086264a6fa50e9) You'll use this URL in Barndoor to auto-discover the OIDC endpoints. Go to the next steps. *** ## Part 2 — Configure the IdP in Barndoor ### Step 8: Open the Barndoor IdP setup form **1. Navigate to Identity Provider settings** In Barndoor, go to [**Identity Provider**](https://app.barndoor.ai/idp) and start the **Set up single sign-on (SSO)** flow. **2. Fill in the basic fields** * **Display name**: Whatever you'd like (e.g. `Entra — Acme Corp`) * **Client ID**: The Application (client) ID from Entra Overview (Step 7) * **Client Secret**: The secret **Value** you copied in Step 6 *** ### Step 9: Set the Issuer URL to trigger OIDC discovery Entra publishes one URL in its metadata, but **stamps a different URL into the `iss` claim of every token it issues**. Barndoor verifies the `iss` claim against the issuer URL you provide, so the two must match exactly — including a trailing slash. **1. Use the Issuer URL to perform OIDC discovery** Paste the Issuer URL from Step 7 into the **Issuer URL** field. Barndoor will use it to auto-fill **Authorization URL**, **Token URL**, **JWKS URL**, etc. ![Barndoor IdP setup form with Issuer URL set and other endpoint fields auto-filled](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/11-barndoor-issuer-discovery.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=0c9bdc79f34dc2718830197b2877d968) > [!WARNING] > > If using the v1 OAuth endpoints, note the issuer is a separate domain from the OAuth endpoints. You will know you are using v1 if your OpenID discovery URL does not contain a version path. > > Example: `https://login.microsoftonline.com/{tenant-id}/.well-known/openid-configuration` > > **The issuer URL must match the OpenID Metadata document exactly (including trailing slash).** If you omit it, SSO sign-in will fail with a `issuer mismatch` error and there will be no useful surface-level UI feedback; only failed login attempts. > > Example: `https://sts.windows.net/{tenant-id}/` **2. Save the connection** Click **Save connection**. Barndoor will store the configuration and reveal the **Redirect URI** in Step 2 of the setup wizard. *** ### Step 10: Register the Redirect URI back in Entra **1. Copy the Redirect URI from Barndoor** On the Barndoor SSO setup page, you'll see a **Redirect URI** that looks like `https://auth.barndoor.ai/realms/.../broker//endpoint`. Click the copy icon. **2. Add it to Entra's Authentication settings** Back in your Entra app registration, click **Authentication** in the left nav → **+ Add a platform** → **Web**. Paste the Redirect URI into the **Redirect URIs** field, then click **Configure**. ![Entra Authentication page with a Web platform configured and Barndoor Redirect URI added](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/10-entra-redirect-uri.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=6473a222b3a861e1512dcacd8a261f91) > [!NOTE] > > Leave the **Front-channel logout URL** and **Home page URL** fields empty. Entra's initiate-login behavior doesn't interoperate with Barndoor's flow today; setting these can cause confusing redirect loops. *** ### Step 11: Test SSO end-to-end **1. Trigger the Test SSO flow** Back in Barndoor's IdP setup, click **Test SSO**. A popup window opens and should redirect you to Entra's sign-in page. ![Barndoor Test Connection](https://mintcdn.com/barndoor/DcRyhDAk08_8J-Az/images/entra/testSSO.png?fit=max\&auto=format\&n=DcRyhDAk08_8J-Az\&q=85\&s=3e200b917358f87b729f9bcc9f808eee) **2. Sign in with an Entra user** Complete authentication. You should be returned to Barndoor with a success page that also shows your federated identity. Validate your identity contains the `groups` claim configured in earlier steps. ![Barndoor SSO test success](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/12-test-sso-success.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=182f8297f89f622c6c531f6524ce5c8c) > [!TIP] > > SSO is wired up. Users can now log in to Barndoor with their Entra ID credentials. *** ### Step 12 (optional): Map Entra groups to Barndoor roles Once SSO works, you can map Entra groups to Barndoor's Admin role using the standard role-mapping flow — see [Connect your IdP — Step 3: Configure Role Mapping](/how-tos/idp-setup#step-3-configure-role-mapping-auto-provision-admins). > [!WARNING] > > **Entra Free tier caveat.** On Entra ID Free (which most trial tenants use), the `cloud_displayname` property added in Step 4 is **silently ignored** and groups arrive as UUIDs rather than human-readable names. Group claims still work — they just aren't pretty. > > To get group display names in tokens you need **Entra ID P1 or higher**. If you're stuck on Free, you have two options: > > 1. Enter group **Object IDs** (UUIDs) in Barndoor's role mapping configuration instead of group names. They're stable per-group, just ugly. > 2. Update your Entra tier to a higher plan to support cloud groups. *** ## Part 3 — SCIM provisioning **SCIM** (System for Cross-domain Identity Management) is an open standard that lets Entra automatically push user and group changes to Barndoor — when someone joins, changes roles, or leaves your organization, Entra provisions, updates, or deprovisions their Barndoor access without anyone touching Barndoor directly. SCIM provisioning is the **recommended way to manage users in Barndoor**. While SSO (Parts 1–2) handles authentication at login time, SCIM keeps your user directory continuously in sync — ensuring access is granted and, just as importantly, revoked promptly as your team changes. ### Step 13: Configure SCIM Provisioning > [!WARNING] > > **Already set up SSO using the app registration method?** If your existing > Barndoor SSO connection was created using the older **app registration** > approach (rather than the **enterprise app** method described in this guide), > you will **not** be able to enable SCIM provisioning on it — the option will > appear disabled. > > To use SCIM provisioning, you must recreate the SSO connection using the > enterprise app method described above > (Part 1 — [Create the Enterprise App](#step-1-create-the-enterprise-app)), > then configure SCIM provisioning against the new connection. > > ![SCIM provisioning disabled for app registration based SSO connections](https://mintcdn.com/barndoor/Bm3Zg6PZezC6Azbs/images/entra/entra-scim-disabled.png?fit=max\&auto=format\&n=Bm3Zg6PZezC6Azbs\&q=85\&s=70423277892781290c54923782cd75f6) **1. Enable SCIM Provisioning in Barndoor** In the Barndoor Platform, do the the Identity Provider page and go to the section labeled SCIM Provisioning. * Click `Configure SCIM Provisioning` * Choose an authentication method (OAuth - Client Credentials OR API Token) then click 'Continue' * Copy the sensitive values from the next dialog. You can only view these once and will need them in the next step * The SCIM Provisioning card will now show a list of relevant endpoints needed to setup SCIM provisioning in Entra ![Enable SCIM in Barndoor](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/13-enable-scim-barndoor.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=982274a93bd315798fd012cf87561e07) **2. Configure SCIM Provisioning in Entra** In the [Microsoft Entra admin center](https://entra.microsoft.com), go to **Identity** → **Applications** → **Enterprise Apps** -> Select your Enterprise -> **provisioning** in the sidebar, then click **+ New Configuration**. Based on the authentication method chosen the previous step, follow either 1 or 2 next. 1. OAuth Client Credentials * Select 'OAuth2 client credentials grant' as the method for authentication * Fill in Tenant URL with the `SCIM Base URL` endpoint found on the SCIM Provisioning card in Barndoor * Fill in OAuth token endpoint with the `Token Endpoint` endpoint found on the SCIM Provisioning card in Barndoor * Fill in the Client ID and Client Secret values with the same sensitive values from the previous step 2. API Token * Select 'Bearer authentication' as the method for authentication * Fill in Tenant URL with the `SCIM Base URL` endpoint found on the SCIM Provisioning card in Barndoor * Fill in the Secret Token with the same API Token from the previous step Finally, click `Test Connection` to ensure authentication is setup properly. If successful, finish by clicking `Create`. ![Enable SCIM in Entra](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/14-enable-scim-entra.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=cde83c7bf91ac9def59e47906feee47f) **3. Assign Users and Groups to sync with Barndoor** Upon SCIM configuration creation, Entra will redirect back to the provisioning overview. * Find `Provisioning` in the sidebar and ensure provisioning mode is set to 'automatic' and Provisioning Status is 'On' * Optionally, modify attribute mappings to meet your requirements. Entra defaults are a good starting point. * Find 'Users and Groups' in the sidebar and add users and groups you would like to synchronize with Barndoor. * Finally, select 'Overview' and click 'Start Provisioning' to start and initial sync of users and groups. ![Entra Configure SCIM](https://mintcdn.com/barndoor/HZp7A7Y18buB2HM0/images/entra/15-entra-scim-configure.png?fit=max\&auto=format\&n=HZp7A7Y18buB2HM0\&q=85\&s=bc0c990b4cbe57edee550ee38c5dc288) > [!TIP] > > On success, you should see assigned users and groups propogate in the 'User' tab within Barndoor. *** ## Part 4 — Roll out SSO enforcement After your IdP connection is saved and SSO sign-in works, the **Roll out SSO enforcement** section on the [Identity Provider](https://app.barndoor.ai/idp) page lets you require SSO for every member of your organization. Until you enforce SSO, users can still sign in with Barndoor passwords in addition to your IdP. > [!NOTE] > > If you don't see **Roll out SSO enforcement** controls on the Identity Provider page, organization-wide SSO enforcement may not be enabled for your workspace yet. Contact your Barndoor account team. > [!WARNING] > > **Enforcing SSO is irreversible in production.** It permanently clears Barndoor passwords for all members, terminates every active session (including yours), and requires all future logins through your IdP—except the dedicated break-glass account described below. ### What changes when you enforce SSO When you confirm enforcement, Barndoor: * Requires all organization members to sign in through your IdP * Permanently clears saved Barndoor passwords for every member * Leaves password sign-in enabled **only** for the break-glass admin email you configure * Terminates all active sessions, including the administrator who enabled enforcement After enforcement succeeds, sign out and sign back in through your IdP to continue working as an administrator. ### Prerequisites Both items in **Before you can enforce SSO** must be complete before **Enforce SSO** is enabled: **1. Test SSO sign-in** Click **Test SSO sign-in**. Barndoor opens a pop-up window and runs the full IdP login path—not just a connection preflight. Complete authentication in the pop-up. When the test succeeds, the row is marked complete. You can run the test again anytime to confirm sign-in still works. > [!TIP] > > If the pop-up is blocked, allow pop-ups for the Barndoor site and run the test again. **2. Configure break-glass admin email** Click **Manage** on the **Break-glass admin email** row and set an emergency mailbox your security or platform team can use if your IdP is unavailable. * The address must use your organization's IdP email domain (shown as `@your-domain` in the dialog) * It must **not** already belong to an existing Barndoor user * You **cannot** use your own administrator email as the break-glass account Click **Save**. Barndoor stores the address as the configured break-glass email. The dedicated break-glass user account is created when you enforce SSO. ### Enable organization-wide SSO **1. Review the rollout card** When both prerequisites are complete, click **Enforce SSO** at the bottom of the rollout card. **2. Acknowledge each consequence** In the confirmation dialog, check every acknowledgement: * Future logins will be exclusively via IdP SSO * All Barndoor passwords will be permanently cleared * Only your break-glass email will be able to sign in via password going forward * All active sessions—including your current one—will be terminated The dialog also shows your IdP connection name and redirect URI for a final sanity check. **3. Confirm enforcement** Click **Confirm Enforcement**. On success, Barndoor shows **SSO enforcement is active** and prompts you to **Sign out and sign in with SSO**. > [!NOTE] > > If enforcement succeeds but Barndoor shows a warning that not all member passwords were cleared or sessions could not be terminated, SSO enforcement is still active. Sign out and sign in again with SSO, verify member access, and contact support if the warning persists. > [!TIP] > > SSO enforcement is active. All organization members must sign in through your Identity Provider. Password login is disabled for everyone except the break-glass account. ### Set up the break-glass account When enforcement completes, Barndoor provisions a dedicated **Barndoor Break Glass** administrator account at the email you configured and sends a setup email to that mailbox. The recipient must: 1. Open the setup email and follow the link to set a password 2. At first sign-in, complete the email one-time passcode (OTP) sent to that mailbox—the same second factor used during an IdP outage Store break-glass credentials in your organization's secure emergency-access process (for example, a sealed envelope or privileged-access vault)—not in shared chat or email threads. ### Manage break-glass access after enforcement After SSO is enforced, the rollout card shows **SSO enforcement** as active and lets you manage the break-glass email: * **Resend invite** — If the break-glass account has not finished password setup, resend the setup email from the break-glass dialog * **Change break-glass email** — Opens a destructive change flow. Enter the new address, check the acknowledgement that the current account will lose password sign-in, then click **Save**. The new mailbox must complete password and OTP setup before it can be used > [!WARNING] > > Changing the break-glass email while SSO is enforced removes the previous break-glass account's password credentials and requires the new mailbox to complete setup from scratch. ### Sign in with break-glass during an IdP outage If your IdP is unavailable and you need emergency administrator access: 1. On the Barndoor sign-in page, choose password sign-in (not SSO) 2. Enter the break-glass email address and password 3. Complete the email one-time passcode sent to that mailbox Password sign-in and email OTP at login are available **only** for the break-glass account once SSO is enforced. All other members must use IdP SSO. ### Remove the SSO connection (optional) To disconnect IdP integration before or after enforcement, open the **actions menu** (⋯) on the rollout card and choose **Remove SSO**. Confirm when prompted. > [!WARNING] > > Removing the SSO connection immediately revokes IdP-based access for your organization. Only users who can still authenticate with a Barndoor password—including the break-glass account, if configured—can sign in. SSO enforcement remains on for the organization; re-connecting an IdP does not restore member password login. ### SSO enforcement troubleshooting > [accordion] Test SSO sign-in pop-up blocked or closes early > > **Common causes:** > > * Browser blocked pop-ups for the Barndoor site > * The sign-in window was closed before authentication finished > > **Solution:** Allow pop-ups for your Barndoor portal origin, then click **Test SSO sign-in** again. If the test times out, cancel and retry. > [accordion] Break-glass email rejected on Save > > **Common causes:** > > * Address is outside your organization's IdP email domain > * Address already belongs to an existing Barndoor user > * You entered your own administrator email > > **Solution:** Use a dedicated emergency mailbox on your IdP domain that is not yet a Barndoor user. Enter only the part before `@`—the domain is shown in the dialog. > [accordion] Break-glass setup email not received > > **Solution:** From the break-glass **Manage** dialog after enforcement, click **Resend invite**. Check spam filters and confirm the mailbox is monitored. The recipient must complete password setup from the link before the account can sign in. > [accordion] Enforcement succeeded with a warning > > **Cause:** SSO enforcement is active, but Barndoor could not clear every member password or terminate every session. > > **Solution:** Sign out and sign back in with SSO. Verify affected members can still reach the app through your IdP. Contact Barndoor support if the warning remains or members report unexpected password login. *** ## Troubleshooting > [accordion] Login fails with 'issuer mismatch' > > **Cause**: The Issuer URL in Barndoor doesn't exactly match the `iss` claim Entra stamped into the token. > > **Fix**: Ensure the Issuer URL matches **exactly** the issuer set in the OpenID Metadata document. Including trailing slashes. If you are using the v1 OAuth endpoints, `https://sts.windows.net//` — including the **trailing slash** — is the issuer. See Step 9. > [accordion] Test SSO loops or returns silently with no user info > > **Common causes**: > > * The **email** claim isn't in the ID token. Re-check Step 2 and confirm `essential: true` is set in the manifest under `idToken` only (Step 4). > * The user signing in doesn't have an email attribute populated in Entra. Verify on the user's profile. > > **Fix**: Ensure the email claim is configured and the user has an email attribute set. Steps 2–4. > [accordion] Groups appear as UUIDs instead of names > > **Cause**: Entra ID Free does not honor the `cloud_displayname` additional property — it's a paid-tier feature. > > **Fix**: Either upgrade to Entra ID P1+, configure Barndoor role mapping against Object IDs (Step 3). > [accordion] SSO worked, then suddenly stopped > > **Cause**: Most likely the Entra client secret expired. Entra caps secrets at 24 months and SSO breaks silently the moment they expire. > > **Fix**: Rotate the secret in **Certificates & secrets**, copy the new Value, and update it in Barndoor's IdP settings. Set a calendar reminder a few weeks before the next expiration. > [accordion] Redirect URI mismatch on login > > **Cause**: The Redirect URI registered in Entra's **Authentication** settings doesn't exactly match the one Barndoor is sending. > > **Fix**: In Barndoor, recopy the Redirect URI from Step 2 of the SSO setup wizard. Paste it into Entra's **Authentication → Web → Redirect URIs**. URLs are case- and trailing-slash-sensitive. *** ## Recap | Value | Where it comes from | Where it goes | | :- | :- | :- | | Application (client) ID | Entra app → Overview | Barndoor Client ID | | Client Secret (Value) | Entra app → Certificates & secrets | Barndoor Client Secret | | Issuer URL (from OpenID Metadata) | Entra app → Overview → Endpoints → OpenID Metadata | Barndoor Issuer URL | | Redirect URI | Barndoor SSO setup → Step 2 | Entra app → Authentication → Web platform | You've now connected Microsoft Entra ID to Barndoor for SSO, SCIM provisioning (if enabled), and optional organization-wide SSO enforcement with break-glass emergency access. # Connect your IdP Source: https://docs.barndoor.ai/how-tos/idp-setup Set up SSO login and automatically provision user roles using any OIDC / SAML 2.0 compatible IdP ## Overview This guide demonstrates how to integrate an Identity Provider (IdP) such as Okta or Entra ID with Barndoor to enable: * **SSO Login**: Allow all users in your organization to authenticate via your IdP * **Automatic Role Mapping**: Provision users as admins or standard users based on IdP group membership * **Centralized User Management**: Onboard and offboard users directly from your IdP Barndoor works with any OIDC or SAML 2.0 compatible IdP. If you use Okta or Microsoft Entra ID, follow the dedicated provider guide below for screenshots and provider-specific gotchas. Otherwise, use the generic flow on this page. ## Choose your provider > [card] [Okta](/how-tos/okta-oin-setup) > > Official Okta Integration Network app with SCIM provisioning. > [card] [Microsoft Entra ID](/how-tos/entra-idp-setup) > > Entra (Azure AD) app registration, issuer URL gotcha, and group claims. > [!NOTE] > > Using a different IdP (Google Workspace, JumpCloud, OneLogin, Ping, etc.)? The generic OIDC / SAML 2.0 flow below applies to all of them. ## Video Walkthrough [Connecting Accounts Demo](https://fast.wistia.net/embed/iframe/57a4lzi4ju?seo=false\&videoFoam=true) > [!NOTE] > > **Prerequisites**: > > * Admin access to your Barndoor account > * Admin access to your IdP (Okta, Entra, etc.) > * An IdP application configured with OIDC/OAuth or SAML 2.0 ## How it works At a high level, connecting any IdP follows the same stages: 1. **Configure the connection** in Barndoor with your IdP's Issuer URL, Client ID, and Client Secret. 2. **Verify SSO login** works for a standard user. 3. **Configure role mapping** so IdP group membership provisions Barndoor admins automatically. 4. **Test offboarding** by removing a user from the admin group. 5. **(Optional) Enforce organization-wide SSO** and configure a break-glass emergency administrator. 6. **(Optional) Remove the SSO connection** when you need to disconnect. The rest of this page walks through each stage generically. For provider-specific UI and screenshots, use the [Okta](/how-tos/okta-oin-setup) or [Entra ID](/how-tos/entra-idp-setup) guides above. *** ## Step 1: Configure IdP Connection in Barndoor **1. Navigate to Identity Provider Settings** Go [here](https://app.barndoor.ai/idp) in your Barndoor dashboard. **2. Complete IdP Setup Form** * Provide a display name, such as your domain name. From your IdP application collect: * **Issuer URL**: Your organization's Issuer URL * **Client ID**: OAuth client ID from your IdP app * **Client Secret**: OAuth client secret from your IdP app \[!TIP] Auto discover will prefill your Authorization, Token, User Info, JWKS, and Logout URLs. If they are not autodiscovered, enter them manually. **3. Test the Connection** Click **Test Connection** to verify that Barndoor can communicate with your IdP. ✅ **Expected result**: "Connection successful" message **4. Save Configuration** Click **Save** to activate the IdP connection. *** ## Step 2: Verify SSO Login Works **1. Log Out of Barndoor** Sign out of your current Barndoor session. **2. Attempt Login with Enterprise User** Try logging in with the enterprise test user from Step 1 using a user's email connected to your IdP. You should now be redirected to your IdP's login page. **3. Authenticate via IdP** Complete authentication through your IdP (enter credentials, complete MFA if required). **4. Verify Access to Barndoor** After successful IdP authentication, you should be logged into Barndoor. ✅ **Expected result**: User is logged in but has **standard user** permissions (not admin yet). > [!TIP] > > SSO is now working! Users can authenticate via your IdP. *** ## Step 3: Configure Role Mapping (Auto-Provision Admins) Now we'll set up automatic role assignment based on IdP group membership. ### Create Admin Group in IdP **1. Navigate to Groups in IdP** In your IdP (Okta/Entra ID), go to **Directory** → **Groups**. **2. Create or Select Admin Group** Create a new group called **"Barndoor Admins"** (or use an existing admin group). **3. Assign Users to Admin Group** Add the test user to the **Barndoor Admins** group. 💡 **Note**: Any user in this group will automatically receive admin permissions in Barndoor. ### Send IdP Groups to Barndoor Barndoor can only map roles and evaluate group-based policies when your IdP sends group names during login. For OIDC connections, include a claim named exactly `groups` in the ID token or UserInfo response. > [!WARNING] > > Role mappings are synced on login. If the mapped group claim is missing or does not match exactly, the corresponding Barndoor role can be removed the next time the user signs in. **1. Configure the groups claim** In your IdP application, add a groups claim with: * **Claim name**: `groups` * **Claim values**: Group display names, not group IDs * **Included groups**: At minimum, the group you want to map to Barndoor admin access, such as `Barndoor Admins` **2. Use your provider's exact steps** The way you emit the `groups` claim differs per IdP. Follow the dedicated guide for the precise UI: * **Okta**: [map admin access from a pushed group](/how-tos/okta-oin-setup#map-admin-access-optional) * **Entra ID**: [add a groups claim and set the group identifier](/how-tos/entra-idp-setup#step-3-add-the-groups-claim) **3. Verify the emitted claim** Use your IdP's token preview, logs, or a fresh test login to confirm the token or UserInfo response contains `groups` with the exact group name you will configure in Barndoor. ### Map IdP Group to Barndoor Admin Role **1. Open Map groups to roles** On the [Identity Provider](https://app.barndoor.ai/idp) page, open the **Map groups to roles** card for your SSO connection. **2. Configure Admin Group Mapping** Set the group name that defines administrators: * **Admin Role Group Name**: Enter `Barndoor Admins` (exact name from your IdP) * Optionally enable **IdP-Only Role Binding** so roles can only be assigned through IdP group mappings (recommended for production SSO rollouts) **3. Save Role Mapping** Click **Save Role Settings**. ✅ **Expected result**: Role mapping saved successfully ### Verify Role Provisioning **1. Log Out and Back In** Sign out of Barndoor and log back in with the test user. **2. Verify Admin Access** After logging in, confirm: * ✅ User now has **Admin** role * ✅ Additional admin functionality is visible in the UI * ✅ User appears in the **Barndoor Admins** user group > [!TIP] > > Role mapping is working! Users in the IdP admin group automatically receive admin permissions. *** ## Step 4: Test User Offboarding (Remove Admin Access) **1. Remove User from Admin Group in IdP** In your IdP, go to **Directory** → **Groups** → **Barndoor Admins**. Remove the test user from the **Barndoor Admins** group. **2. Log Out and Back In** In Barndoor, sign out and log back in with the test user. **3. Verify Standard User Access** Confirm that: * ✅ User is now a **standard user** (no longer admin) * ✅ Admin-only functionality is no longer visible * ✅ User group reflects the change > [!NOTE] > > Changes to IdP group membership are reflected immediately upon next login to Barndoor. *** ## Roll out SSO enforcement After your IdP connection is saved and SSO sign-in works, the **Roll out SSO enforcement** section on the [Identity Provider](https://app.barndoor.ai/idp) page lets you require SSO for every member of your organization. Until you enforce SSO, users can still sign in with Barndoor passwords in addition to your IdP. > [!NOTE] > > If you don't see **Roll out SSO enforcement** controls on the Identity Provider page, organization-wide SSO enforcement may not be enabled for your workspace yet. Contact your Barndoor account team. > [!WARNING] > > **Enforcing SSO is irreversible in production.** It permanently clears Barndoor passwords for all members, terminates every active session (including yours), and requires all future logins through your IdP—except the dedicated break-glass account described below. ### What changes when you enforce SSO When you confirm enforcement, Barndoor: * Requires all organization members to sign in through your IdP * Permanently clears saved Barndoor passwords for every member * Leaves password sign-in enabled **only** for the break-glass admin email you configure * Terminates all active sessions, including the administrator who enabled enforcement After enforcement succeeds, sign out and sign back in through your IdP to continue working as an administrator. ### Prerequisites Both items in **Before you can enforce SSO** must be complete before **Enforce SSO** is enabled: **1. Test SSO sign-in** Click **Test SSO sign-in**. Barndoor opens a pop-up window and runs the full IdP login path—not just a connection preflight. Complete authentication in the pop-up. When the test succeeds, the row is marked complete. You can run the test again anytime to confirm sign-in still works. > [!TIP] > > If the pop-up is blocked, allow pop-ups for the Barndoor site and run the test again. **2. Configure break-glass admin email** Click **Manage** on the **Break-glass admin email** row and set an emergency mailbox your security or platform team can use if your IdP is unavailable. * The address must use your organization's IdP email domain (shown as `@your-domain` in the dialog) * It must **not** already belong to an existing Barndoor user * You **cannot** use your own administrator email as the break-glass account Click **Save**. Barndoor stores the address as the configured break-glass email. The dedicated break-glass user account is created when you enforce SSO. ### Enable organization-wide SSO **1. Review the rollout card** When both prerequisites are complete, click **Enforce SSO** at the bottom of the rollout card. **2. Acknowledge each consequence** In the confirmation dialog, check every acknowledgement: * Future logins will be exclusively via IdP SSO * All Barndoor passwords will be permanently cleared * Only your break-glass email will be able to sign in via password going forward * All active sessions—including your current one—will be terminated The dialog also shows your IdP connection name and redirect URI for a final sanity check. **3. Confirm enforcement** Click **Confirm Enforcement**. On success, Barndoor shows **SSO enforcement is active** and prompts you to **Sign out and sign in with SSO**. > [!NOTE] > > If enforcement succeeds but Barndoor shows a warning that not all member passwords were cleared or sessions could not be terminated, SSO enforcement is still active. Sign out and sign in again with SSO, verify member access, and contact support if the warning persists. > [!TIP] > > SSO enforcement is active. All organization members must sign in through your Identity Provider. Password login is disabled for everyone except the break-glass account. ### Set up the break-glass account When enforcement completes, Barndoor provisions a dedicated **Barndoor Break Glass** administrator account at the email you configured and sends a setup email to that mailbox. The recipient must: 1. Open the setup email and follow the link to set a password 2. At first sign-in, complete the email one-time passcode (OTP) sent to that mailbox—the same second factor used during an IdP outage Store break-glass credentials in your organization's secure emergency-access process (for example, a sealed envelope or privileged-access vault)—not in shared chat or email threads. ### Manage break-glass access after enforcement After SSO is enforced, the rollout card shows **SSO enforcement** as active and lets you manage the break-glass email: * **Resend invite** — If the break-glass account has not finished password setup, resend the setup email from the break-glass dialog * **Change break-glass email** — Opens a destructive change flow. Enter the new address, check the acknowledgement that the current account will lose password sign-in, then click **Save**. The new mailbox must complete password and OTP setup before it can be used > [!WARNING] > > Changing the break-glass email while SSO is enforced removes the previous break-glass account's password credentials and requires the new mailbox to complete setup from scratch. ### Sign in with break-glass during an IdP outage If your IdP is unavailable and you need emergency administrator access: 1. On the Barndoor sign-in page, choose password sign-in (not SSO) 2. Enter the break-glass email address and password 3. Complete the email one-time passcode sent to that mailbox Password sign-in and email OTP at login are available **only** for the break-glass account once SSO is enforced. All other members must use IdP SSO. ### Remove the SSO connection (optional) To disconnect IdP integration before or after enforcement, open the **actions menu** (⋯) on the rollout card and choose **Remove SSO**. Confirm when prompted. > [!WARNING] > > Removing the SSO connection immediately revokes IdP-based access for your organization. Only users who can still authenticate with a Barndoor password—including the break-glass account, if configured—can sign in. SSO enforcement remains on for the organization; re-connecting an IdP does not restore member password login. ### SSO enforcement troubleshooting > [accordion] Test SSO sign-in pop-up blocked or closes early > > **Common causes:** > > * Browser blocked pop-ups for the Barndoor site > * The sign-in window was closed before authentication finished > > **Solution:** Allow pop-ups for your Barndoor portal origin, then click **Test SSO sign-in** again. If the test times out, cancel and retry. > [accordion] Break-glass email rejected on Save > > **Common causes:** > > * Address is outside your organization's IdP email domain > * Address already belongs to an existing Barndoor user > * You entered your own administrator email > > **Solution:** Use a dedicated emergency mailbox on your IdP domain that is not yet a Barndoor user. Enter only the part before `@`—the domain is shown in the dialog. > [accordion] Break-glass setup email not received > > **Solution:** From the break-glass **Manage** dialog after enforcement, click **Resend invite**. Check spam filters and confirm the mailbox is monitored. The recipient must complete password setup from the link before the account can sign in. > [accordion] Enforcement succeeded with a warning > > **Cause:** SSO enforcement is active, but Barndoor could not clear every member password or terminate every session. > > **Solution:** Sign out and sign back in with SSO. Verify affected members can still reach the app through your IdP. Contact Barndoor support if the warning remains or members report unexpected password login. *** ## Summary You've successfully configured IdP integration with Barndoor! Here's what you accomplished: ✅ **Connected IdP** for SSO/OIDC authentication\ ✅ **Enabled automatic role provisioning** based on IdP groups\ ✅ **Tested user onboarding** (SSO login and admin access)\ ✅ **Tested user offboarding** (removed admin access via IdP)\ ✅ **(Optional) Enforced organization-wide SSO** with a break-glass emergency account ### Key Benefits **Centralized authentication**: Users log in via your existing IdP **Automated role management**: No manual user provisioning needed **Streamlined onboarding**: New employees automatically get access **Instant offboarding**: Removing users from IdP immediately revokes access *** ## Troubleshooting > [accordion] SSO Login Redirects but Fails > > **Common causes:** > > * Incorrect Client ID or Client Secret > * IdP application not configured with correct redirect URIs > * OIDC endpoints not properly discovered > * domain mismatch > > **Solution**: Double-check credentials in both Barndoor and your IdP. Re-test the connection and review IdP application logs. > [accordion] Role Mapping Not Working > > **Common causes:** > > * Group name mismatch (case-sensitive) > * User not actually in the IdP group > * OIDC `groups` claim is missing from the ID token or UserInfo response > * IdP sends group IDs, paths, or a different claim name instead of the group display name > * Role mapping not saved properly > > **Solution**: Verify the exact group name in IdP matches Barndoor configuration. Confirm user membership in IdP groups. For OIDC, preview the token or UserInfo response and confirm it includes `groups` with the expected value, such as `Barndoor Admins`. Re-save role mapping settings and have the user sign out and back in. > [accordion] Users Can't Access After IDP Connection > > **Common causes:** > > * Users not assigned to the IdP application > * IdP application deactivated or suspended > * Network/firewall blocking communication > > **Solution**: Verify users are assigned to the Barndoor application in your IdP. Check IdP application status. Test connection from Barndoor settings. # IP Allow Listing Source: https://docs.barndoor.ai/how-tos/ip-allowlisting Configure your firewall to allow Barndoor MCP traffic ## Overview Barndoor uses a dedicated set of static IP addresses for all outbound MCP (Model Context Protocol) traffic to customer infrastructure. You can whitelist these IPs in your firewall to ensure only authenticated traffic from Barndoor reaches your environment. ## Static IP Addresses All outbound MCP traffic from Barndoor originates from the following IP addresses: * `136.114.185.55` * `34.121.81.24` * `34.172.10.253` * `35.226.250.15` * `35.188.204.49` > [!NOTE] > > These IP addresses are stable and shared across all Barndoor customers. You only need to whitelist them for custom MCP servers you host in your own infrastructure — hosted third-party MCP servers (like Slack, Notion, or GitHub) are reached over their providers' public APIs and require no firewall changes on your side. ## Firewall Configuration To whitelist Barndoor traffic in your firewall: 1. **Add inbound rules** allowing traffic from the IP addresses listed above 2. **Configure the appropriate ports** for your MCP server (typically HTTPS/443) 3. **Test the connection** after updating your firewall rules ### Example Firewall Rule ```bash theme={null} # Allow HTTPS traffic from Barndoor IPs (example) iptables -A INPUT -p tcp --dport 443 -s 34.121.81.24 -j ACCEPT ``` ## Regional Availability Currently, all IPs are hosted in the **United States**. As Barndoor expands to additional regions, we will: * Add region-specific IPs to this documentation * Maintain high availability with automatic failover within the dedicated IP pool ## IP Change Policy These IP addresses are stable and change rarely. When a change is unavoidable, Barndoor provides **at least 30 days' advance notice** before the new addresses take effect, so you have time to update your firewall rules. We will: * Notify org administrators by email ahead of the change * Update the address list on this page * Keep the previous addresses active during the transition window so connectivity is never interrupted ## Troubleshooting If you're experiencing connection issues after whitelisting: 1. **Verify the IP addresses** are correctly entered in your firewall rules 2. **Check that the correct ports** are open (typically 443 for HTTPS) 3. **Review firewall logs** to confirm traffic from Barndoor IPs is being allowed 4. **Contact support** if issues persist: [support@barndoor.ai](mailto:support@barndoor.ai) ## Frequently Asked Questions > [accordion] Do I need to whitelist IPs for third-party MCP servers? > > No. Hosted third-party MCP servers (Slack, Notion, GitHub, etc.) are reached over their providers' public APIs and need no firewall changes on your side. Only custom MCP servers you host in your own infrastructure require whitelisting. > [accordion] Are these IPs shared with other customers? > > Yes. These IPs are used by all Barndoor customers for outbound MCP traffic. Traffic is still authenticated and encrypted using your unique MCP server credentials. > [accordion] What happens if one of these IPs fails? > > Barndoor maintains high availability. If an IP becomes unavailable, traffic automatically fails over to another IP within the dedicated pool. No action is required from you. > [accordion] Can I restrict access to specific Barndoor users? > > IP whitelisting allows traffic from the Barndoor platform but doesn't distinguish between individual users. For user-level access control, implement authentication at your MCP server level. ## Need Help? If you have questions about IP whitelisting or need assistance configuring your firewall, reach out to our support team at [support@barndoor.ai](mailto:support@barndoor.ai). # Get the most out of your Claude subscription Source: https://docs.barndoor.ai/how-tos/llm-gateway-failover Run Claude Code on your Claude subscription through the Barndoor LLM Gateway and keep working past your rate limit with automatic failover, so each developer gets the full value of the seat you pay for. A Claude subscription is a flat per-seat price, which makes it far cheaper per token than the API for heavy coding. The catch is the rate limit: hit your cap mid-task and you are blocked until the window resets. The Barndoor LLM Gateway lets each developer run Claude Code on **their own** subscription as the primary path, and automatically spill to a cheaper fallback model the moment they hit the cap. The seat you already pay for does the bulk of the work, the session never stalls on a rate limit, and you pay marginal cost only on the overflow. That is the full value of the subscription without the leash: cheap-flat economics as your floor, graceful overflow on top. ### How it works **1. Request enters the gateway** Claude Code talks to the gateway using the Anthropic Messages API. Your Claude subscription token is forwarded through to Anthropic (OAuth passthrough), so the request is served on your subscription. **2. Primary target is tried first** The gateway resolves the model to a route. The highest-priority target is your Claude subscription. **3. Failover on a cap** If Anthropic returns a rate-limit error (HTTP 429) or its usage-limit error (HTTP 400), the gateway reroutes the same request to the next target in the route, such as an open model, with no action from the developer. The response comes back on the fallback and the session continues. ### Prerequisites > [!NOTE] > > You need a Barndoor account with admin privileges, the LLM Gateway enabled for > your organization, and an active Claude subscription for the developer using it. > New to gateway administration? Work through the [Quickstart Guide](/how-tos/llm-gateway-quickstart) > first — this page assumes you know your way around **LLM Management**. ### 1. Configure the providers In the Barndoor web UI, go to **LLM Management** > **Providers**. 1. Add an **Anthropic** provider and set **Authentication** to **Claude OAuth passthrough**. This is the passthrough provider: it stores no API key and forwards the caller's subscription token. 2. Add a **fallback** provider for the model you want to overflow to (for example an open model on a cloud you already use). Give it whatever credentials that provider needs. ### 2. Create a route with failover Go to **Model Routes** and create a route under a single model name (the alias Claude Code will target). Add two targets, in priority order: | Priority | Target | Purpose | | :- | :- | :- | | 1 (highest) | Anthropic (Claude OAuth passthrough) | Primary, served on your subscription | | 2 | Fallback provider | Overflow when the subscription is rate-limited | ![A model route with two priority-ordered targets, a primary and a fallback](https://mintcdn.com/barndoor/FOxx1F5NIxLmngoh/images/llm-gateway-failover-route.png?fit=max\&auto=format\&n=FOxx1F5NIxLmngoh\&q=85\&s=c401abc5db1ae381378aa47bbf79e04d) > [!NOTE] > > Targets are tried top to bottom. Set the primary's **Rate limit retries** count if > you want the gateway to briefly retry the subscription before spilling; leave it at > 0 to fail over immediately. ### 3. Create a gateway API key Each developer creates their **own** key under [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys). This authenticates Claude Code *to the gateway*; it is separate from your Claude subscription token, which the gateway forwards to Anthropic. > [!NOTE] > > Use a per-user key, not an unassigned org key from **LLM Management → API Keys**. > This pattern routes each developer's own seat, so per-user attribution in the > usage dashboard — and any user-scoped model access policy — depends on the key > carrying a user identity. ### 4. Point Claude Code at the gateway Stay logged into Claude Code with your Claude subscription so it sends its OAuth token, then set these environment variables and launch `claude`: ```bash Environment theme={null} # Do NOT set ANTHROPIC_API_KEY or ANTHROPIC_AUTH_TOKEN — either one replaces # the subscription token Claude Code sends unset ANTHROPIC_API_KEY unset ANTHROPIC_AUTH_TOKEN export ANTHROPIC_BASE_URL="https:///api/llm-gateway" export ANTHROPIC_CUSTOM_HEADERS="x-api-key: " # Point Claude Code's models at your route's alias. export ANTHROPIC_MODEL="" export ANTHROPIC_SMALL_FAST_MODEL="" ``` The split is the key detail: the **`x-api-key`** header authenticates you to the gateway, while Claude Code's **`Authorization: Bearer`** subscription token is what the gateway forwards to Anthropic. > [!TIP] > > For the full Claude Code reference — both auth modes, the env-var checklist, and > how to verify your setup before launching `claude` — see [Connecting Your Tools to > the LLM Gateway](/how-tos/connect-tools-to-llm-gateway#connect-your-tools). ### 5. Verify Run a normal Claude Code request. It should complete on your subscription. To see the failover, drive the seat until Anthropic rate-limits it: the gateway logs the rate-limit error and reroutes to the fallback, and the request still returns a completion. > [!WARNING] > > Subscription terms. Provider subscriptions are intended for individual, > interactive use. Route each developer's own seat and keep usage interactive. > Pooling seats behind a shared gateway, or driving them as shared automated > capacity, may violate the provider's terms of service. Review your model > provider's terms before enabling this pattern, especially at scale. # Failover, Cooldowns, and Route Health Source: https://docs.barndoor.ai/how-tos/llm-gateway-failover-and-cooldowns How a model route's ordered targets fail over, which errors trigger it, and how cooldowns and route health keep traffic off failing targets. A **model route** is a client-facing model name — the value callers put in `model` — backed by one or more **targets**. Each target is one provider model. Targets are tried top to bottom: the gateway sends the request to the first target, and if that target fails in a way another target might not, it sends the same request to the next one. This page explains exactly when that happens and how the gateway keeps traffic away from targets that keep failing. For the most common use of it — running Claude Code on each developer's own Claude subscription, with a fallback model for when they hit their rate limit — see [Get the most out of your Claude subscription](/how-tos/llm-gateway-failover). > [!NOTE] > > You need a Barndoor account with admin privileges and the LLM Gateway enabled for your organization. New to gateway administration? Work through the [Quickstart Guide](/how-tos/llm-gateway-quickstart) first — this page assumes you know your way around **LLM Management**. ## Routes and targets Routes live under **LLM Management → Model Routes**. * **Create Route** asks for a **Route Name** (the name users put in API calls) and one or more provider models to add as targets. * Expand a route to see its targets, numbered in priority order. Drag a target by its handle to change the order. **Add Targets** adds more; the row's actions menu has **Rename route**, **Duplicate route**, and **Delete route**. * Each target has its own controls on the right of its row: | Control | What it sets | | - | - | | **Rate limit retries** | How many times to retry *this* target when the provider rate-limits the request, before failing over. See [Rate-limit retries](#rate-limit-retries). | | **Timeouts** | **Request timeout (s)** — the total time a non-streaming request may take (1–600, default 120). **Stream idle (s)** — the longest gap allowed between streamed chunks (1–300, default 180). | | Power | Disables this target only. The provider keeps serving the model to other routes. | | Remove | Removes the target from this route. The provider keeps serving the model. | ![Model Routes filtered to eng- routes, with eng-claude-opus-5-5 expanded: Anthropic OAuth as target 1 and Anthropic API as target 2, both serving claude-opus-5-5](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/10-model-route-targets.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=e3044a367257f1644b842c2f039efe93) A target that can't serve shows a badge explaining why — for example **Provider disabled**, **Provider model disabled**, **Provider not serving** (the provider is failing its connection health check), a budget-exhausted badge, or a cooldown badge (see [Route health](#route-health-and-cooldowns)). Disabled or blocked targets are skipped; the rest of the route keeps serving. ## When the gateway fails over The gateway moves on to the next target when the current one fails with an error another provider might not share: | Upstream result | Fails over? | | - | - | | `401` / `403` — credential rejected | Yes | | `404` — model not available on this provider | Yes | | `429` — rate limited (after any configured retries) | Yes | | `400` that says the account's API usage limit has been reached | Yes | | `5xx`, including Anthropic's `529` overloaded | Yes | | Timeout, or a connection failure while sending the request | Yes | | Any other `4xx` (for example a malformed request) | **No** — the next target would reject it too, so the error is returned as is | | A Barndoor-side refusal (authentication, model access, budget, DLP) | **No** | | A passthrough target (**Claude OAuth passthrough**) reached without the caller's own Claude sign-in token | **No** — the request fails with `401` rather than trying the next target, so a caller without a subscription token doesn't walk the whole route | Failover happens before the response starts. Once a target has begun streaming a response back, a later failure in that stream is not replayed on another target. When every target fails, the caller gets one error that lists each attempt under `error.metadata.attempts`. Its status is: * `401` if every target was skipped because the caller's own credential was rejected; * `429`, with `Retry-After`, if every target was rate-limited, out of quota, or cooling down; * the shared status if every attempt returned the same one; * otherwise `502`. > [!TIP] > > Successful responses on `POST /v1/chat/completions` and `POST /v1/messages` carry `x-bd-provider-route-attempt` (which target served it, `1` = first), `x-bd-provider-route-count`, and `x-bd-provider-failover-count`. See [Observability Headers](/how-tos/llm-gateway-quickstart#observability-headers). ### Rate-limit retries By default a rate-limited target fails over immediately. The **Rate limit retries** popover on each target changes that: * **Retry count** (0–10) — how many times to retry the same target on a rate limit before failing over. `0` means fail over immediately. * **Max wait (s)** (0–180) — when set, the gateway waits for the provider's `Retry-After` between retries, up to this many seconds. At `0` it waits about one second between retries and ignores `Retry-After`. The popover's **Effective behavior** line spells out what the current values do. A target with custom retries shows a small retry-count badge. ## Route health and cooldowns On top of per-request failover, the gateway tracks the recent results of every target and puts one that keeps failing into a **cooldown**. While a target is cooling down, requests skip it and go straight to the next target, rather than paying for a failed attempt first. Health is tracked per **provider and upstream model**, not per route. Two routes that both use `claude-opus-5-5` on the same provider share one health record, so a cooldown triggered through one route applies to both. ### What starts a cooldown | Trigger | Default cooldown | | - | - | | **10 failures within 60 seconds** — `5xx`, timeouts, connection failures, and `401`/`403` on a provider with a stored key. Successes in between don't reset the count. | 30 seconds, doubling each time the target fails again on recovery, up to 300 seconds | | **A single `429`** | The provider's `Retry-After`, or 30 seconds if it sent none; never longer than 300 seconds | | **A single `529` overloaded** | The provider's `Retry-After`, or 10 seconds. Doesn't count toward the failure threshold and doesn't escalate. | | **A single "API usage limit reached" `400`** | 300 seconds (the longest cooldown allowed) | Other `4xx` responses, including `404`, never start a cooldown — the provider answered, it just refused that request. When a cooldown expires, the target is *recovering*: the gateway lets a few requests through (three at a time) to test it. After three successes it is healthy again. If a test request fails, the target cools down again — for server failures, for twice as long as last time. ### Passthrough providers cool down per user On a provider using **Claude OAuth passthrough** or **ChatGPT OAuth passthrough**, each request carries the caller's own subscription token. A `429` or usage-limit `400` there is that one person's quota, and a `401`/`403` is that one person's token. So those errors cool down **only that caller's credential**; the target stays healthy for everyone else. A rejected token cools down for the longest window (300 seconds by default), because it won't fix itself — the user needs to sign in again. Server errors, timeouts, and `529` overloaded responses still cool the target for everyone, since they aren't about any one person's credential. ### Seeing it in the portal In **Model Routes**, a target in cooldown shows a badge; hover it for the reason and when it recovers: | Badge | Meaning | | - | - | | **Temporarily unavailable** | Cooling down for everyone | | **Recovering** | Cooldown expired; test requests are being let through | | **Unavailable for you** / **Recovering for you** | Cooling down only for your own credential | | **Reconnect required** | The provider rejected your own credential; sign in again | A collapsed route shows **N of M available** when some of its targets are cooling down, or **Temporarily unavailable** when all of them are. Users see the same badges on their own models under **Settings → My Models**. ### Custom cooldown policies The thresholds above are per-target defaults. A target whose cooldown policy differs from the defaults shows a **Custom cooldown** badge; its tooltip lists every value, with the non-default ones in bold: | Tooltip row | Default | Notes | | - | - | - | | **Failures to cool down** | 10 | `0` turns off cooldowns for everyone on this target | | **Failure window** | 60s | | | **First cooldown** | 30s | Doubles on each failed recovery | | **Longest cooldown** | 300s | Caps every other window | | **Rate-limited (429) cooldown** | 30s | Used when the provider sends no `Retry-After` | | **Overloaded (529) cooldown** | 10s | `0` counts a `529` as an ordinary failure instead | Cooldown policies are changed through the admin API (the cooldown fields on [Create a model route](/api-reference/llm-gateway/model-routes/createRoute) and [Update a model route](/api-reference/llm-gateway/model-routes/updateRoute)), not in the portal. The Terraform provider does not expose them yet. Because routes to the same upstream model share one health record, each route judges that shared record against its own policy. ### Clearing a cooldown Cooldowns clear on their own: once the window passes, the gateway sends recovery probes and returns the target to service when they succeed. There is no manual reset in the portal — if you need a target back in service sooner (for example, right after fixing a provider-side outage), contact Barndoor support. ## Route groups A **Route Group** is a named set of model routes that a [model access policy](/how-tos/use-llm-controls) can target as a whole — for example "Engineering" — instead of listing every route and editing the policy whenever a route is added. * Open **Model Routes → Route Groups** to create, rename, or delete groups and choose their routes. * Add routes to a group from a route's actions menu, or select several routes and add them in bulk. * A route can belong to several groups. The **Route Groups** column and filter on the routes list show membership. A group contains whole routes, not individual targets. Like every model access target, a group grants nothing on its own: it narrows an allowlist or blocks through a denylist. Deleting a route removes it from its groups automatically. > [!WARNING] > > Renaming a route doesn't always carry its group memberships over. If the route's targets are also the models' enablement on their providers — typically when the route name matches the upstream model name, such as `claude-opus-5-5` → `claude-opus-5-5` — the renamed route drops out of its groups, and any model access policy that targets those groups stops covering it. After renaming, check the **Route Groups** column and re-add the route if it's missing. Budgets and rate limits whose **Target** is the old route name also keep the old name, so update them too. ## Related * [Get the most out of your Claude subscription](/how-tos/llm-gateway-failover) — a worked example: each developer's own Claude seat as the primary target, with automatic overflow to a fallback model. * [Routing policies](/how-tos/llm-routing-policies) — choose the model per request instead of always starting at the first target. * [LLM Controls](/how-tos/use-llm-controls) — budgets, rate limits, and model access, including how target-bound budgets make a route fail over. # Quickstart Guide Source: https://docs.barndoor.ai/how-tos/llm-gateway-quickstart Configure the Barndoor LLM Gateway as an admin — credentials, providers, models, routes, and governance — then send requests and troubleshoot. > [!NOTE] > > **This guide is for admins.** The gateway has to be configured — credentials, providers, models, and routes — before anyone can call it. For an overview and architecture first, see [Using the LLM Gateway](/how-tos/use-llm-gateway). If your admin has already set this up and you just want to point a tool at it, go to [Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway). ## Admin: Configure the Gateway All admin configuration happens in **LLM Management** in the Barndoor portal — a single hub whose left-hand nav groups every piece of the gateway. Work top to bottom: connect a provider, enable models, give them route names, mint a key, send a test request, then layer on governance. | Group | Section | What it configures | | - | - | - | | **Connections** | **Credentials** | Reusable upstream credentials — API keys, AWS IAM roles, Google service accounts, Entra ID service principals. | | **Connections** | **Providers** | Named upstream connections, each using one set of credentials. | | **Models** | **Models** | The upstream models enabled on each provider. | | **Models** | **Model Pricing** | Per-million-token prices used for cost reporting and spending budgets. | | **Models** | **Model Routes** | Client-facing model names (for example `gpt-5.4-mini`) and the ordered provider models each one resolves to. | | **Models** | **Client settings** | Native capabilities for governed Claude Code and Codex sessions launched with Barndoor Bridge — see [Client settings](/how-tos/barndoor-bridge/client-settings). | | **Models** | **Routing Policies**, **Routing Rules** | Virtual model names that pick a model per request, and rules that constrain the pick — see [Routing Policies](/how-tos/llm-routing-policies). | | **Keys** | **API Keys** | `bd-…` keys assigned to a user, a group, or neither (developers mint their own under [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys)). | | **Controls** | **Budgets**, **Rate Limits**, **Model Access** | Governance policies — token and spending budgets, request and token throttles, and model allow/deny lists. Covered in [Configuring LLM Controls](/how-tos/use-llm-controls). | > [!NOTE] > > **Client settings**, **Routing Policies**, and **Routing Rules** appear only when those features are enabled for your organization — contact Barndoor if you need them. In some organizations the **Models** section is replaced by a **Models** panel on each provider's detail page; see [Step 3](#step-3-enable-models). Per-request usage and cost reporting lives separately, under **Reporting → LLM Usage Dashboard** — see [Reading the LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard). ![LLM Management hub showing the Connections, Models, Access, and Controls section groups in the left navigation](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/03-llm-config-tabs.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=06086093434924ea94a508eddc2dbf7e) ### Step 1: Add Provider Credentials **Credentials** are what authorize Barndoor against your upstream account. Save them once in **LLM Management → Credentials** and any number of providers can use them. You can also skip this step and create credentials inline while creating the provider in [Step 2](#step-2-create-a-provider) — they're saved to the Credentials section either way. The two OAuth passthrough providers store no credentials at all and are set up entirely on the **Providers** section: * **Anthropic OAuth** — see the [Anthropic OAuth passthrough](#step-1-add-provider-credentials) accordion below. * **OpenAI Codex OAuth** — see [Use Codex with the LLM Gateway](/how-tos/use-codex-with-llm-gateway). ![Add Credentials dialog with the Model Provider picker, name, base URL, API key, and reason fields](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/04-add-credential-dialog.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=d569cb17750eda40dade95cc7fed393a) > [accordion] API-key providers (OpenAI, Anthropic, Azure OpenAI, Google AI, and others) > > The simplest case — pick the provider and paste a key. > > 1. Click **Add Credentials**. The dialog opens with a **Model Provider** picker at the top; the rest of the form is disabled until you pick one. > 2. Pick the provider. The **Base URL** fills in with the catalog default, and any provider-specific fields appear. > 3. Give the credentials a **Name** (for example `Production Anthropic Key`) — this is how you'll find them when creating a provider. > 4. Paste the API key. > 5. Click **Create**. The key is stored in Barndoor's encrypted secret store and is never returned to the browser. > > To connect an OpenAI-compatible service that isn't in the catalog, pick the custom option in **Model Provider** and enter its base URL and key yourself. > [accordion] AWS Bedrock > > Bedrock supports three authentication methods, chosen in **Bedrock Auth Method**. **AWS IAM Role is the recommended production setup**; the others are useful for pilots or environments that can't grant cross-account roles. > > | Method | When to use | > | - | - | > | **AWS IAM Role** | Production. Barndoor assumes a role in your AWS account at request time — no long-lived secrets stored. | > | **Static AWS Keys** | Pilot or fallback. Access key + secret key (+ optional session token). | > | **Bedrock API Key** | If your team prefers AWS's first-party Bedrock API key feature. | > > Every method needs an **AWS Region** — where Barndoor sends Bedrock Runtime requests (for example `us-east-1`). Make sure the models you want are enabled in that region in AWS. > > > [!NOTE] > > > > Which Bedrock API the gateway calls — **Claude / Anthropic Messages** or **Bedrock Converse** — is chosen per provider (**Bedrock API Family**, in [Step 2](#step-2-create-a-provider)), not on the credentials. One IAM role can back a provider for each family. > > #### Setting up an AWS IAM Role > > The dialog walks you through this with a **Bedrock setup checklist**. > > 1. Pick **AWS IAM Role** as the **Bedrock Auth Method**. > 2. Fill in **AWS Region** and your **Customer IAM Role ARN**. Barndoor generates an **External ID** and shows its own **Barndoor Principal ARN** for this environment in the same dialog. > 3. Click **Copy trust policy** — Barndoor builds the JSON for you, pre-filled with its principal ARN and your external ID. > 4. In **AWS IAM**, create (or update) the role you named in step 2 and paste the copied trust policy into its trust relationship. > 5. Grant the role permission to invoke Bedrock — at minimum `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream`. (The AWS-managed read-only Bedrock policies do **not** include these actions.) For a proof of concept, `Resource: "*"` is fine; **for production, narrow `Resource` to the specific Bedrock model ARNs / inference profiles and regions you route to.** > 6. Back in Barndoor, click **Validate role access**. The portal attempts the same assume-role chain it uses at runtime and shows the AWS error verbatim if something's off — adjust the trust policy or role permissions until it validates. > 7. Click **Create**. The **AWS Trust Info** dialog opens; you can reopen it any time from the credentials' row menu (**AWS trust info**) to recheck the principal or external ID. > > #### Setting up Static AWS Keys > > Paste the **AWS Access Key ID**, **AWS Secret Access Key**, and an optional **AWS Session Token** (if you're using temporary credentials). There's no validate button for this mode — failures show up on the first real request. > > #### Setting up a Bedrock API Key > > Paste the **Bedrock API Key** issued by the AWS Bedrock console. > [accordion] Google Vertex AI > > Vertex supports three authentication methods, chosen in **Google Auth Method**: > > | Method | When to use | > | - | - | > | **Workload Identity / ADC** | The easiest path. Barndoor uses its platform-managed Google identity; you grant that identity Vertex access on your project. No keys to paste. | > | **Service Account Impersonation** | Recommended for production. Create a service account in your GCP project with Vertex permissions (the **Target Service Account**), then grant Barndoor's runtime principal `roles/iam.serviceAccountTokenCreator` on it. Barndoor impersonates your service account at request time. | > | **Service Account Key** | Pilot or fallback. Paste a service account's email and private key (the values inside a downloaded JSON key file). | > > Every method needs: > > * **GCP Project ID** — your project. > * **Vertex AI Location** — the region (default `us-central1`). > > #### Setup steps > > 1. Pick the auth method and fill in the fields. > > 2. In your GCP project, enable the **Vertex AI API** and any partner-model access (for example, Claude on Vertex requires explicit model enablement). > > 3. Grant **`roles/aiplatform.user`** (or a narrower Vertex role) on the project to whichever principal actually calls Vertex — Barndoor's runtime identity (Workload Identity / ADC), your target service account (impersonation), or the key's service account. > > 4. For Service Account Impersonation only: grant **`roles/iam.serviceAccountTokenCreator`** on your target service account to Barndoor's runtime principal. > > 5. Click **Validate Vertex Access**. Barndoor fetches a token with your chosen method and asks Vertex about a model, confirming that both auth and model access work. > > > [!NOTE] > > > > The **Service Account Key** method asks for the **email** and **private key** as separate fields, plus an optional **Token URI**. Paste the values into the form — uploading the raw JSON file is not supported. > > Which Vertex API the gateway calls is chosen per provider (**Vertex API Family**, in [Step 2](#step-2-create-a-provider)): **Gemini Generate Content**, **Claude / Anthropic Messages**, or **OpenAI-compatible (Model Garden MaaS, e.g. GLM)**. > > > [!NOTE] > > > > **Gemini on Vertex doesn't support streaming, tool calls, or structured `response_format` through the gateway yet.** Streaming requests to a Gemini Generate Content provider are rejected with a `400`. Claude on Vertex and the OpenAI-compatible family stream normally. For Gemini with streaming, use a **Google AI (Gemini)** provider instead. > [accordion] Microsoft Foundry > > Microsoft Foundry (formerly Azure AI Foundry) serves Claude and OpenAI GPT / o-series models from one Foundry resource. Pick the method in **Azure Auth Method**: > > | Method | What you enter | > | - | - | > | **Deployment API key** | The resource's API key. | > | **Entra ID service principal** | **Entra Tenant ID**, **Application (Client) ID**, and **Client Secret** for an app registration. The app registration needs the **Cognitive Services User** role on the Foundry resource. | > > Some Foundry Claude models are only reachable with Entra ID. > > Which of the resource's model APIs a provider targets — **Claude (Anthropic Messages)** or **GPT / o-series (Azure OpenAI)** — is chosen per provider (**Model API Family**, in [Step 2](#step-2-create-a-provider)), so one set of credentials covers both. > [accordion] Anthropic OAuth passthrough (Claude Code subscribers) > > Use this when your developers use **Claude Code** with their own Claude subscriptions and you want each request billed against that developer's subscription rather than a shared API key. > > Instead of storing a Claude API key, Barndoor authenticates the caller with their `bd-…` gateway API key and **forwards the caller's own Claude OAuth token** (`sk-ant-oat…`) to Anthropic on the upstream request. > > > [!NOTE] > > > > Anthropic OAuth passthrough is configured on the **Providers** section — there's nothing to save in Credentials. > > #### Setup > > 1. Go to **Providers → Add Provider** and pick the **Anthropic OAuth** card (one of the two Anthropic cards). > 2. Name the provider (for example `Anthropic via Claude OAuth`). **Credentials** shows **Claude OAuth passthrough — no stored credential**, and no API key field appears. > 3. Click **Create**, and enable the Claude models you want to expose. > 4. Add those models to a [Model Route](#step-5-define-model-routes). > > You can also switch an existing Anthropic provider to passthrough by setting its **Authentication** to **Claude OAuth passthrough**. > > #### What callers send > > Every request carries **two** headers: > > | Header | Value | Purpose | > | - | - | - | > | `x-api-key` | `bd-…` | Authenticates the caller to the Barndoor gateway. | > | `Authorization` | `Bearer sk-ant-oat…` | The caller's Claude OAuth token, forwarded to Anthropic. | > > Claude Code sends both automatically — see the Claude Code section of [Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway#connect-your-tools) for the setup. > > #### Smoke-test with curl > > To verify the two-header path without Claude Code: > > ```bash theme={null} > export BARNDOOR_LLM_GATEWAY_ENDPOINT="https://app.barndoor.ai/api/llm-gateway/v1" > export BD_API_KEY="bd-…" > export CLAUDE_OAUTH="sk-ant-oat…" # from your local Claude login > > curl -i "$BARNDOOR_LLM_GATEWAY_ENDPOINT/messages" \ > -H "content-type: application/json" \ > -H "anthropic-version: 2023-06-01" \ > -H "x-api-key: $BD_API_KEY" \ > -H "authorization: Bearer $CLAUDE_OAUTH" \ > -d '{ > "model": "claude-opus-5-5", > "max_tokens": 32, > "messages": [{"role": "user", "content": "Say pong."}] > }' > ``` > > A `200` with a normal Anthropic response body confirms both headers flowed correctly. A `401` means one of the two headers is missing or malformed. > > #### Limitations to know about > > * **Endpoint scope:** the Claude OAuth token is forwarded only on **`POST /v1/messages`**. A request that reaches an Anthropic OAuth provider through any other endpoint — for example `/v1/chat/completions` — fails with `401` and the message `Anthropic provider requires an incoming Claude OAuth bearer token`. (`/v1/messages/count_tokens` is answered by the gateway itself and never reaches Anthropic.) > * **Token management:** Barndoor never stores or refreshes Claude OAuth tokens. Expiry and refresh are handled by Claude Code on the developer's machine. > * **A missing token doesn't fail over.** It's treated as a caller error (`401`), not an upstream failure, so the gateway doesn't move on to the route's other targets. > > #### Pairing OAuth with a fallback > > A common production setup puts the OAuth provider first and a cheaper or shared provider second on the same route, so each developer's subscription absorbs everyday traffic and the fallback takes over when the subscription hits its limit or Anthropic is degraded. [Get the most out of your Claude subscription](/how-tos/llm-gateway-failover) walks through that setup end to end. > [!WARNING] > > Credentials are encrypted at rest and never leave Barndoor in the clear once saved. When you rotate an upstream key, update it on the credentials in Barndoor; every provider that uses them picks up the new value. ### Step 2: Create a Provider A **Provider** is a named upstream connection that uses one set of credentials. Open **Providers** and click **Add Provider** to open the **Add a Provider** card grid: 1. Search, or filter the catalog with **All / Official / Custom**. **Official** cards come from Barndoor's provider catalog (see [Supported Providers](/how-tos/use-llm-gateway#supported-providers)). The **Custom Provider** card connects any OpenAI-compatible endpoint you configure yourself. 2. Click the card for the upstream you want. Anthropic shows two cards — the standard API-key card and **Anthropic OAuth**. A dialog opens with the catalog defaults filled in. 3. Give the provider a **Name**. Pick it with care: it appears in the providers list, in usage reports, and in the provider-prefixed model names callers can use (for example `OpenAI Prod/gpt-5.4-mini`). 4. For **AWS Bedrock**, **Google Vertex AI**, and **Microsoft Foundry**, pick the provider's API family — **Bedrock API Family**, **Vertex API Family**, or **Model API Family**. It decides which models this provider can serve. To use more than one family from the same account, create one provider per family, all using the same credentials. 5. Pick the **Credentials** — a saved set from [Step 1](#step-1-add-provider-credentials), or **+ Create new credentials** to enter them here. New credentials are given a **Credential name** and saved to the Credentials section, where other providers can reuse them. 6. Review the provider settings: | Setting | What it does | | - | - | | **Block traffic on failed health check** | On by default, and recommended. Suspends the provider from routing while its connectivity check is failing. Turn it off to keep routing to it anyway. See [Provider health](#provider-health). | | **Auto-Sync models with Barndoor Catalog** | Official providers only. **Off** leaves model enablement to you. **Add Only** enables every model Barndoor lists for the provider, and new ones as they appear. **Full Sync** also disables models Barndoor retires. | | **Calculate token cost** | On by default: cost is calculated from [model pricing](#step-4-configure-model-pricing-optional). Turn it off for flat-rate, self-hosted, or separately billed providers — usage is still tracked, but cost is recorded as `$0`, and a **Billing arrangement** is required. | 7. Click **Create** (**Create and add route** for AWS Bedrock). If Auto-Sync is **Off**, an **Enable Models** dialog opens next — continue with [Step 3](#step-3-enable-models) there, or click **Skip**. You can create several providers from the same vendor or even the same credentials — for example one for production OpenAI and one for an Azure OpenAI deployment in another region. The providers list shows each provider's credentials, a **Source** column (Official or Custom) you can filter on, and a status pill. > [!NOTE] > > For **Azure OpenAI** (and Foundry GPT providers), **Azure API Mode** chooses between **OpenAI v1 paths (default)** and **Deployment paths (dated api-version)**. Deployment paths don't serve the Responses API, so Codex and other Responses clients need the v1 mode. #### Provider health Barndoor tracks whether each provider is reachable and serving, and shows it as a status pill on the provider's row: | Pill | Meaning | | - | - | | **Enabled** (green) | Healthy and serving traffic. | | **Enabled · not serving** (red) | The health check is failing and the provider is suspended from routing — the gateway skips it and uses other targets. | | **Enabled · health failing (override)** (amber) | The health check is failing, but **Block traffic on failed health check** is off for this provider, so it still receives traffic. | | **Disabled** (grey) | You've turned the provider off; it serves nothing. | When a provider is failing, hover the pill to see the underlying error, and use **Re-check health** from the row's menu to re-run the check straight away (useful right after you fix a credential or trust policy). Unhealthy targets are skipped during [failover](#failover-retries-and-streaming), so one degraded provider doesn't take down a route that has healthy fallbacks. ![Add OpenAI provider dialog with the health-check, Auto-Sync, Calculate token cost, and Credentials settings](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/05-add-provider-dialog.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=95effd63a6520b08599a9918c041bf4d) ### Step 3: Enable Models A provider serves only the models enabled on it. If you skipped the **Enable Models** dialog, or want to change what's enabled later, open the **Models** section: each provider is listed with its models, and you toggle on every upstream model your organization should be able to call (for example `gpt-5.4-mini`, `claude-sonnet-5`, `text-embedding-3-large`). To add a model that isn't in Barndoor's catalog, type its exact upstream name as a custom model. These are the *upstream* model identifiers — the names sent to the provider. An enabled model is immediately callable by its provider-prefixed name, `/` (for example `OpenAI Prod/gpt-5.4-mini`). To give it a plain name, add it to a route in [Step 5](#step-5-define-model-routes). > [!NOTE] > > In some organizations the **Models** section is replaced by a **Models** panel on each provider's own page: click the provider's name on **Providers**, then enable models there. The panel also has **Sync now** for providers with Auto-Sync on. If **Require pricing for Model Routes** is on, a model can't be enabled until it has a price — a model without one shows an **Add pricing** shortcut that takes you to [Model Pricing](#step-4-configure-model-pricing-optional). ![Models panel on a provider's page, listing enabled upstream models with their prices](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/06-models-tab.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=60a6152356a1d483827b008ac56eb54c) ### Step 4: Configure Model Pricing (optional) Barndoor already prices every request against its **managed default catalog** of market-rate prices, so the cost-aware features work without any setup: * **Spending budgets** in [LLM Controls](/how-tos/use-llm-controls) * The **estimated cost** recorded for every request * Per-team, per-user, and per-model cost on the **Reporting → LLM Usage Dashboard** Use **Model Pricing** only when you want to **override** those defaults — negotiated rates, custom models, or prices you'd rather manage yourself. See [Managing Model Pricing](/how-tos/manage-model-pricing) for the full guide, including the **Require pricing for Model Routes** safety setting. ### Step 5: Define Model Routes This is the step that gives callers a stable model name. A **Model Route** maps a *client-facing* model name to one or more enabled provider models, tried in priority order. 1. Open **Model Routes** and click **Create Route**. 2. Enter the **Route Name** callers will use, for example `gpt-5.4-mini` or `team-coding-model`. This is the value callers put in the `model` field. 3. Pick a provider in **Browse provider** and check one or more of its **Provider Models**. Switch **Browse provider** to add targets from other providers to the same route. 4. Optionally open **Advanced settings** to set per-target **Rate limit retries** and **Timeouts**. 5. Click **Create Route**. The first target is the primary. If it fails with a failover-eligible error — a 5xx, a network error, a timeout, or a 429 that outlasts its retries — the gateway tries the next target. You can reorder targets after the route is created. See [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns) for exactly which errors fail over. ![Create Model Route dialog with the route name eng-claude-opus-5-5 and claude-opus-5-5 selected on two providers, Anthropic OAuth and Anthropic API](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-gateway/07-add-route-dialog.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=9b81c88d6c5cac0174d03d165a4f9c4d) > [!TIP] > > **Backing one route with more than one provider.** A `gpt-5.4-mini` route can have one target on an OpenAI provider and a second on an Azure OpenAI provider. Callers send `gpt-5.4-mini` and the gateway tries the targets in order, failing over if one errors. To reach one specific provider with no failover, callers use that provider's own model name instead — `OpenAI Prod/gpt-5.4-mini` — as described in [Model Naming](#model-naming). **Route Groups** (next to **Create Route**) bundle routes so a single [model access policy](/how-tos/use-llm-controls) can cover the whole group instead of listing every route. ### Step 6: Create an API Key To send a test request you need a `bd-…` key. Either: * Create your own under [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) → **Create Key**, or * Create one in **LLM Management → API Keys → Create Key**. Give it a **Name**, then optionally **Assign to User** or **Assign to Group**. Leave both unset for an organization-wide key — the usual choice for services and CI. Group members share group-scoped budgets, rate limits, and model access. Set an **Expiration** with the picker (from **1 hour** to **1 year**, or a date and time), or choose **No expiry** if your organization allows it. The gateway rejects the key once it expires; rotate it to renew it. See [Managing LLM API Keys](/how-tos/manage-llm-api-keys) for rotation, expiration alerts, and key policies. The key is shown **once**, in the **API Key Created** dialog. Copy it before closing — Barndoor keeps only a hash. > [!NOTE] > > Where agents are connected to the LLM Gateway, **Create API Key** also offers **Assign to Agent**, so the key's usage is attributed to that agent. A key belongs to at most one of a user, a group, or an agent. This option may not be enabled for your organization yet — contact Barndoor if you need it. ### Step 7: Send a Test Request List the models your key can call, then send a request to one of them: ```bash theme={null} export BARNDOOR_API_KEY="bd-…" curl https://app.barndoor.ai/api/llm-gateway/v1/models \ -H "Authorization: Bearer $BARNDOOR_API_KEY" curl https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer $BARNDOOR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.4-mini", "messages": [{"role": "user", "content": "Say pong."}] }' ``` Replace `gpt-5.4-mini` with a route name from Step 5 (or a `provider/model` name from Step 3). A `200` with a normal chat completion means the gateway is working end to end. The request shows up on **Reporting → LLM Usage Dashboard**. If it fails, see [Troubleshooting](#troubleshooting). ### Step 8: Add Governance (optional) Once routes are live, layer on usage policies. They live under the **Controls** group of **LLM Management** and are enforced inside the gateway on every request, so they apply to every client and SDK alike. * **Budgets** — token and spending caps per period, with alert thresholds. * **Rate Limits** — request and token throughput caps. * **Model Access** — allow or deny specific models and routes for the organization, a group, a role, a user, or an API key. See [Configuring LLM Controls](/how-tos/use-llm-controls) for scopes, the order Barndoor evaluates policies in, and what callers see when a request is denied. *** ## Sending Requests The gateway speaks two API dialects on the same base URL, `https://app.barndoor.ai/api/llm-gateway/v1`: | Endpoint | Use it from | | - | - | | `POST /v1/chat/completions` | OpenAI SDKs, LangChain, LlamaIndex, most chatbots | | `POST /v1/completions` | Legacy OpenAI text-completion clients | | `POST /v1/embeddings` | OpenAI / LangChain embeddings clients | | `POST /v1/responses` | OpenAI Responses API clients, including Codex | | `POST /v1/messages` | Anthropic Messages clients (Claude Code, Anthropic SDK) | | `POST /v1/messages/count_tokens` | Anthropic clients that pre-flight token counts. Answered by the gateway with an estimate; it isn't sent upstream and doesn't count against rate limits or budgets. | | `GET /v1/models` | Any client that lists models on startup (OpenAI or Anthropic shaped — see [List Available Models](#list-available-models)) | Send your key as `Authorization: Bearer bd-…` or `x-api-key: bd-…`. When both headers are present the gateway reads the key from `x-api-key`, so Anthropic-compatible clients can pass a provider-side OAuth token in `Authorization`. Request bodies can be up to 32 MB by default, enough for a full-context Claude Code conversation. ### List Available Models Enumerate what a key can call instead of hardcoding model names — the set changes as admins add providers, enable models, or adjust access policies. ```bash curl theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/models \ -H "Authorization: Bearer bd-…" ``` ```python OpenAI SDK theme={null} import os from openai import OpenAI client = OpenAI( api_key=os.environ["BARNDOOR_API_KEY"], base_url="https://app.barndoor.ai/api/llm-gateway/v1", ) for model in client.models.list(): print(model.id) ``` ```python Anthropic SDK theme={null} import os import anthropic client = anthropic.Anthropic( api_key=os.environ["BARNDOOR_API_KEY"], base_url="https://app.barndoor.ai/api/llm-gateway", ) for model in client.models.list(): print(model.id, model.display_name) ``` Note the two base URLs differ: the OpenAI client takes the `/v1` form, the Anthropic client the bare one — it appends `/v1` itself. Both are shown on the **LLM Gateway Endpoint** card under [**Settings → My Models → Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) for your own tenant. The listing is filtered by the policies that apply to your key, so it reflects what that key can actually invoke rather than the organization's full inventory. **The response shape follows the client.** The request above returns the OpenAI envelope (`{"object": "list", "data": [...]}`), which is the default. Send an `anthropic-version` header — as the Anthropic SDKs and Claude Code do — or authenticate with `x-api-key` and no `Authorization: Bearer` header, and you get Anthropic's envelope instead (`{"data": [{"type": "model", "id": …, "display_name": …}], "has_more": false}`), so `client.models.list()` parses against either SDK: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/models \ -H "x-api-key: bd-…" \ -H "anthropic-version: 2023-06-01" ``` Each entry also carries an additive `barndoor` object — the serving provider and upstream model (when every target agrees on them), whether the name is a multi-target fallback group, and how many targets it has. It is extra metadata on top of the standard fields, so strict OpenAI and Anthropic clients ignore it safely. ### Non-Streaming Chat Completion ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.4-mini", "messages": [ {"role": "system", "content": "You are a terse assistant."}, {"role": "user", "content": "Summarize Barndoor in one sentence."} ] }' ``` ### Streaming Chat Completion Set `"stream": true` and the gateway streams the response back as server-sent events in the format of the endpoint you called, whichever provider serves it. ```bash theme={null} curl -N https://app.barndoor.ai/api/llm-gateway/v1/chat/completions \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-sonnet-5", "stream": true, "messages": [{"role": "user", "content": "Stream a haiku about gateways."}] }' ``` ### Embeddings ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/embeddings \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "text-embedding-3-large", "input": ["Hello", "World"] }' ``` ### Anthropic Messages (Claude Code) The gateway also accepts native Anthropic-style requests: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/messages \ -H "x-api-key: bd-…" \ -H "anthropic-version: 2023-06-01" \ -H "Content-Type: application/json" \ -d '{ "model": "claude-sonnet-5", "max_tokens": 256, "messages": [{"role": "user", "content": "Hello"}] }' ``` *** ## Connect Your Tools Cursor, Claude Code, Codex, LangChain, the OpenAI and Anthropic SDKs, and plain `curl` each need your API key, a model route name, and the gateway endpoint. Step-by-step configuration for each lives on its own page: > [card] [Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway) > > Create a key, copy your model route and endpoint, and wire up your editor, agent, or SDK. *** ## Model Naming The string in the `model` field decides how the gateway routes the request. There are three forms: | Form | Example | What the gateway does | | - | - | - | | **Route name** | `gpt-5.4-mini` | Looks up the [Model Route](#step-5-define-model-routes) with that name and tries its targets in priority order, failing over if one errors. | | **Provider-prefixed model** | `OpenAI Prod/gpt-5.4-mini` | Sends the request to that upstream model on that one provider, with no failover. Works for any model [enabled on the provider](#step-3-enable-models), whether or not it's in a route. | | **Routing policy name** | `smart` | Picks a model for each request from the policy's options. See [Routing Policies](/how-tos/llm-routing-policies). | The prefix is the provider's **Name** as configured in **Providers**, matched case-insensitively — not a fixed vendor slug. So `openai/gpt-5.4-mini` works only if a provider is named `openai`; a provider named `Azure OpenAI Prod` is addressed as `Azure OpenAI Prod/gpt-5.4-mini`. The part after the prefix is always an **upstream model name**, never a route name. To pin one target of a route, address that target's upstream model directly on its provider; `/` returns `404`. > [!NOTE] > > If your organization requires routing policies, only routing policy names are callable — route names and provider-prefixed models are refused, and `GET /v1/models` lists only routing policies. See [Require requests to use a routing policy](/how-tos/llm-routing-policies#require-requests-to-use-a-routing-policy). Don't guess names: `GET /v1/models` returns every identifier the calling key can use, already filtered by your model access policies. Call it once on startup rather than on every request. ## Observability Headers Successful responses on `POST /v1/chat/completions` and `POST /v1/messages` include headers you can log to understand routing — useful for client-side monitoring, comparing providers, and post-incident analysis. | Header | Meaning | | - | - | | `x-bd-provider-route-attempt` | 1-indexed position of the target that succeeded (`1` = primary, `2` = first fallback). | | `x-bd-provider-route-count` | Total number of targets on the route. | | `x-bd-provider-failover-count` | Number of targets that failed before one succeeded. | | `x-bd-provider-retry-count` | Same-target 429 retries the gateway performed. | | `x-bd-provider-retry-sleep-ms` | Time spent waiting between 429 retries. | These are emitted on successful responses only — not on errors, and not on `/v1/completions`, `/v1/embeddings`, or `/v1/responses`. Every response, including errors, also carries `x-bd-request-id`. Send your own `x-bd-request-id` (or `x-request-id`) on the request and the gateway echoes it back; otherwise it generates one. Include it when you contact support. For per-request usage and cost, use **Reporting → LLM Usage Dashboard** in the Barndoor portal ([guide](/how-tos/read-llm-usage-dashboard)), where you can break traffic down by model, provider, user, group, API key, status code, and more. ## Failover, Retries, and Streaming * If a target returns a 5xx, a network error, a timeout, or a 429 that outlasts its retry budget, the gateway tries the next target in the route's priority order. The response headers above show which target served the request. * Same-target 429 retries are configured per target (**Rate limit retries** in the route's advanced settings). The gateway retries with backoff, then either succeeds or fails over. * Targets that keep failing are put in a short cooldown and **skipped** until they recover, and providers failing their health check are skipped too (see [Provider health](#provider-health)) — so failover prefers targets that are actually up. A provider with **Block traffic on failed health check** turned off stays in the rotation regardless. * A streaming request fails over if the upstream sends no response within 60 seconds. * Streaming responses (`stream: true`) preserve the provider's SSE framing and pass through token usage where the provider reports it. For the full rules, see [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns). *** ## Troubleshooting Gateway errors use the error shape of the endpoint you called: `{"error": {"message", "type", "code"}}` on OpenAI endpoints, and `{"type": "error", "error": {"type", "message"}}` on `/v1/messages` and `/v1/messages/count_tokens`. The `message` says what went wrong; the `type` is the stable value to branch on. > [accordion] `401` — `invalid API key` / `missing or invalid Authorization or x-api-key header` > > * Confirm the header is `Authorization: Bearer bd-…` (with a space after `Bearer`) or `x-api-key: bd-…`. > * Make sure the key hasn't expired, or been revoked or disabled (check [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) or **LLM Management → API Keys**). > * Keys only work in the organization and environment they were created in. A key from a trial environment won't work against production, and vice versa. > * A `401` that names a provider (for example `Anthropic provider requires an incoming Claude OAuth bearer token`) is about the upstream side — see the OAuth passthrough limitations in [Step 1](#step-1-add-provider-credentials). > [accordion] `404` — `model '…' not found or not available` > > * Call `GET /v1/models` to see exactly which names your key can use. > * If you expected a name to be there, check with an admin that the route exists in **Model Routes** with at least one enabled target, and that the model is enabled on its provider. > * `model '…' not found for provider '…'` means a provider-prefixed name didn't match. The part after `/` must be an upstream model enabled on that provider — not a route name. Call a route by its plain name. > [accordion] `403` — model access denied > > * Model access denials read `Model '…' is not allowed by access policy`. Check **LLM Management → Model Access** for the policy that applies to the key's user, group, or role. See [Configuring LLM Controls](/how-tos/use-llm-controls). > [accordion] `429` — rate limit or budget exhausted > > * Barndoor's rate limits (`type: rate_limit_error`, with a `Retry-After` header) and budgets (`type: budget_exhausted`) can return `429` before the request reaches any provider. The message says which limit fired. On `/v1/responses`, both return `type: usage_limit_reached` instead, with the original type in `code`; see [What callers see when something is denied](/how-tos/use-llm-controls#what-callers-see-when-something-is-denied). > * Upstream 429s are retried per the route's retry settings and may then fail over. Check the `x-bd-provider-retry-count` and `x-bd-provider-failover-count` headers to see what happened. > [accordion] `502` — every target failed > > * When every target on a route fails, the message lists the providers tried and the last failure, and `error.metadata.attempts` has the detail for each attempt. The status matches the upstream failure where they all agree (for example `401` if every provider rejected its credentials), `429` if every attempt was rate limited, and `502` otherwise. > * An attempt that timed out has a `code` starting with `upstream_timeout_` (for example `upstream_timeout_first_byte` when a streaming request got no response within 60 seconds). > * Check the providers' status pills in **Providers** — see [Provider health](#provider-health). > [accordion] `400` — streaming or tools rejected on Vertex Gemini > > * Gemini on Google Vertex AI doesn't support streaming, tool calls, or structured `response_format` through the gateway yet. Send a non-streaming request, or route to a **Google AI (Gemini)** provider or a Claude model instead. > [accordion] Streaming connection closes early > > * Make sure your HTTP client supports SSE and doesn't buffer (`curl -N`, `requests.post(..., stream=True)`, `fetch` with a manual reader, and so on). > * A premature close usually means the upstream provider closed first. Check the failover headers and the **LLM Usage Dashboard** for that request. > [accordion] Anthropic SDK / Claude Code can't reach the gateway > > * The Anthropic SDK appends `/v1/messages` itself: set its base URL to `https://app.barndoor.ai/api/llm-gateway` (without `/v1`). Both forms are on the [**Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) card. > * Send the Barndoor key in `x-api-key`. If your client only knows `ANTHROPIC_API_KEY`, set that to your `bd-…` key — it's sent in the same header. ## Frequently Asked Questions > [accordion] Do I have to use OpenAI's SDK? > > No. Any HTTP client that can speak OpenAI's request/response shape — or Anthropic's Messages shape on `/v1/messages` — works. SDKs are a convenience, not a requirement. > [accordion] Where do upstream API keys live? > > In Barndoor's encrypted secret store, attached to **Credentials**. The gateway loads them at request time; they're never shown in the browser or returned by any API. > [accordion] Can I see how many tokens / how much money my agents are using? > > Yes. **Reporting → LLM Usage Dashboard** shows usage and cost by user, group, model, provider, and API key. Costs come from Barndoor's default prices unless you override them in **Model Pricing**. > [accordion] What's the difference between user keys and org keys? > > * **User keys** ([Settings → My Models → API Keys](https://app.barndoor.ai/settings/models?section=api-keys), or an admin key assigned to a user) are tied to one user. Usage and policies attribute to that user. > * **Group keys** (assigned to a group in **LLM Management → API Keys**) share that group's budgets, rate limits, and model access. > * **Org keys** (no user or group) are typically used for services and CI. They have an organization scope but no individual user. > [accordion] What happens when an upstream provider is down? > > If the route has more than one target, the gateway fails over automatically and the response headers show which target succeeded. If every target fails, the caller gets an error listing each attempt — see the `502` entry in [Troubleshooting](#troubleshooting). ## Need Help? Reach out to [support@barndoor.ai](mailto:support@barndoor.ai) with: * The endpoint you called, the HTTP status code, and the `error.message`. * The `x-bd-request-id` response header, or the approximate time of the request and the value you sent in the `model` field. * A redacted request body if the issue reproduces consistently. # Routing Policies Source: https://docs.barndoor.ai/how-tos/llm-routing-policies Give callers one model name — like smart — and let the gateway pick the cheapest model strong enough for each request, constrained by plain-English routing rules, model access, and budgets. A **routing policy** is a model name that doesn't point at one model. Callers put its name — say `smart` — in the `model` field, and for each request the gateway picks one of the policy's **slots**: an ordered list of models from least to most capable. Simple requests go to a cheap slot; harder ones go higher. The choice is made by a **determiner**, a small, fast model you pick that reads the request and returns a slot. **Routing rules** let you constrain that choice in plain English — for example, "contract review never goes below Sonnet". > [!NOTE] > > Routing policies replace the earlier **Smart Models** feature. Existing smart models carried over as routing policies with the same name, so callers don't need to change anything. > > **Routing Policies** and **Routing Rules** may not be enabled for your organization yet — contact Barndoor if you don't see them under **LLM Management**. ## Key terms | Term | Meaning | | - | - | | **Slot** | One position in the policy's ordered list. Slot 0 is the least capable (and usually cheapest); the last slot is the most capable. Each slot targets a model route or a specific provider model. | | **Determiner** | The model that reads each request and picks a slot. Its call is a real, billed LLM request. | | **Context threshold** | A request size, in estimated tokens, at which requests start at a higher slot regardless of what the determiner says. | | **Posture** | Which way the determiner leans when two slots are about equally suitable. | | **Routing rule** | A plain-English description of a kind of request, plus a floor ("never below") and/or bans ("never use"). | ## Create a routing policy **1. Open LLM Management → Routing Policies** Click **Add Routing Policy**. **2. Name it** **Routing policy name** is the value callers put in `model` (for example `smart`). It can't be the same as an existing model route's name. **Description** is optional. Leave **Enabled** on. **3. Pick a posture** **Savings** prefers the cheaper slot when the choice is close, **Quality** prefers the stronger one, and **Balanced** (the default) has no preference. Posture only breaks ties — it never overrides a model access limit or a rule. **4. Fill the model slots** A policy needs at least two slots, ordered least → most capable (the form starts with **Fast**, **Standard**, and **Premium**). For each slot: * **Label** — a name for the slot. * **Target** — switch between **Route** (one of your [model routes](/how-tos/llm-gateway-failover-and-cooldowns), which keeps that route's failover) and **Model** (a specific provider model). The target must have at least one enabled route, and can't be the policy itself. * **Routing guidance** (optional) — what this slot is best for, for example "code" or "long-form writing". The determiner sees this next to the slot. Between each pair of slots, **Requests of at least N tokens start at** *next slot* sets a context threshold. Thresholds must increase down the list (defaults: 8,000 and 32,000). **5. Configure the determiner** * **Determiner model** — the model or route that picks a slot: a chat model that supports JSON-mode output (`response_format: json_object`), or Jev (see [Using Jev as the determiner](#using-jev-as-the-determiner)). A small, fast model is usually right. * **Characters of the request it reads** — how much of the request is sent to the determiner (default 12,000). Lower is cheaper and faster; too low and it judges on an unrepresentative excerpt. * **Determiner instructions** (optional) — replaces the default instructions. The slot list, request details, and required JSON output format are always added automatically. * **Fallback slot** — the slot used when the determiner errors or returns no usable answer (default: slot 1). **6. Test it, then save** Under **Test routing**, enter a sample request and click **Preview routing**. The result shows the slot and model it would get, what decided it, and the determiner's reason — without saving anything. If you change the configuration afterwards, the result is marked stale. Click **Save**. Each saved policy appears as a card showing its posture, whether it's enabled, the determiner, the slots, and the context thresholds. > [!WARNING] > > Deleting a policy asks you to type its name to confirm. Clients calling that name stop resolving, and the policy's routing rules are deleted with it. Disabling a policy is not a soft delete either: requests to a disabled policy are **refused** with a `400`, rather than served by some other model with the same name. ## Using Jev as the determiner The determiner can be [Jev](/how-tos/use-jev-classifier), TypeSafe's classifier, served by the TypeSafe AI provider or by OpenRouter. Instead of asking a chat model to write a JSON answer, the gateway asks Jev two typed questions: * **Which slot.** Jev gives the probability that each slot, cheapest first, is the least capable one that would still answer the request fully. The gateway picks the cheapest slot where the running total reaches the policy's posture: **50%** for Savings, **70%** for Balanced, and **85%** for Quality. * **Which routing rule**, if the policy has enabled rules. As with a chat determiner, Jev only names a rule; the gateway applies that rule's floor and bans itself. Compared with a chat determiner: * **Its answer is always usable.** There's no JSON to get wrong or cut off. * **It's faster and cheaper per request.** In Barndoor's testing, a pick took about 160 ms, against about 1.2 s for Claude Haiku. * **Determiner instructions are not used.** Jev's questions are fixed. * **It can rank at most 10 slots.** A policy offering a caller more than 10 slots uses the **Fallback slot** for every request. The **Characters of the request it reads** limit applies to Jev the same way. Jev's reason, shown in **Preview routing** and the audit log, gives the probabilities behind the pick in plain English. ## How a slot is chosen For each request to a routing policy, the gateway: 1. **Estimates the request's size** from all its text, and sets a minimum slot from your context thresholds. 2. **Skips the determiner when the answer is already clear.** A request containing images goes to the top slot. A request at or above the last context threshold also goes to the top slot. 3. **Asks the determiner.** It sees the latest user message only — not the whole conversation, system prompt, or tool definitions — cut to the character limit you set. (Claude Code's injected `` context is removed first, so it doesn't make every request look complex.) Along with it, the determiner sees the slots it may choose from, their guidance, the policy's enabled rules, whether the request uses tools or images, and the posture. 4. **Never goes below the minimum slot**, whatever the determiner picked. If the determiner fails, the **Fallback slot** is used (still no lower than the minimum). 5. **Applies model access and rules** — see [Constraints](#constraints-model-access-and-rules). 6. **Sends the request to the chosen slot's target**, which fails over across its own targets as usual. ### Constraints: model access and rules The determiner's pick can still be moved after it is made. None of these ever grant access — they only narrow what a request reaches. * **Model access.** Slots the caller isn't allowed to use are left out of what the determiner sees. If it still lands on one, the request moves **up** to the next slot the caller may use. If the caller may use none of the policy's slots, the request is refused with a `403`. * **Routing rules.** If the determiner says the request matches a rule, the gateway looks that rule up itself and applies its floor and bans. A ban removes a slot; a floor raises the pick to at least that slot. When the two can't both be met, **the ban wins**. If a rule's floor is above anything the caller may use, they get the best slot they can reach rather than an error. If a ban removes every slot the caller could use, the request is refused with a `403`. * **Size and images.** The minimum slot from step 1 is never traded away. If the caller isn't allowed any slot at or above it, the request is refused with a `403` asking an administrator to widen their model access, rather than answered by a model too small for it. The determiner can only *name* a rule; the floor and bans always come from the rule as you saved it. A determiner that names a rule that doesn't exist, or a disabled one, applies nothing. ### Conversations stay on one model Switching models mid-conversation makes agents incoherent and discards the provider's prompt cache, so the gateway **pins** a conversation to the slot it was first routed to. A conversation is identified by the organization, the API key, and the text of its first user message. A pin lasts 55 minutes and is refreshed on every turn that uses it. On each later turn: | Turn | What happens | | - | - | | A tool result coming back | Stays on the pinned model | | A short acknowledgement ("yes", "go ahead", "thanks") | Stays on the pinned model | | Newly needs tools or images, or grows past a context threshold | Re-routed, and only ever to a **stronger** model | | Already on the strongest model the caller may use, and no rule on the policy bans anything | Stays on the pinned model | | Anything else | The determiner runs again, so a rule can apply to something pasted mid-conversation (for example a contract in the sixth message). This re-check can move the conversation to a different model, including a cheaper one — for example when a rule bans the model it was on. | > [!NOTE] > > Two conversations under the same API key that open with exactly the same first message share a pin. This mostly affects automated agents that always start with the same boilerplate. ## Routing rules Rules are written per policy under **LLM Management → Routing Rules**. Choose the policy from **Routing policy**, then click **Add Rule**. | Field | What it does | | - | - | | **Name** | How the rule is shown (up to 120 characters). | | **When does this apply?** | A plain-English description of the requests it covers (up to 2,000 characters). This is what the determiner matches against — describe the requests, not the rule. No example prompts needed. | | **Never below** (optional) | The least capable slot ever acceptable for matching requests. | | **Never use** (optional) | Slots matching requests must never go to. | | **Enabled** | A disabled rule is ignored. | A rule needs a floor, a ban, or both — one with neither would never change anything. A floor or ban is stored as a slot position, so if you later remove slots from the policy, a floor or ban on a slot that no longer exists stops applying (it's dropped, not moved to the new top slot). A rule conflicts when its floor can never be met — because it bans every slot at or above its own floor, or because another rule bans them. Saving still succeeds, but the tab shows a warning banner and the rule carries a **Conflict** badge. If both rules match a request, the ban wins. Deleting a rule tells you which slots its matching requests may be routed to again. ### Test a request The **Test a request** panel runs sample text through the selected policy's determiner and rules. The result shows the slot and model the request would get, **Rule: *name*** or **No rule matched**, and — when something moved the determiner's pick — what it picked and why it moved (a model access policy, a tools or images requirement, the rule's floor, or the rule's ban). Sample text is never stored or logged. > [!TIP] > > **Preview routing** in the policy editor tests an unsaved configuration, so it doesn't apply the policy's rules. To see rules take effect, use **Test a request** on the Routing Rules tab. ## Require requests to use a routing policy By default, callers can still name a model or model route directly, which bypasses routing policies entirely. To stop that, turn on **Require requests to use a routing policy** at the top of **Routing Policies** and confirm **Require routing policies**. The badge changes from **Optional** to **Required**. While it's on: * A request must name an **enabled** routing policy. Naming a model (`anthropic/claude-…`) or a model route is refused with a `400` that lists the policies available — never silently routed somewhere else. * Integrations that name models directly will start failing, so turn this on only after they've moved to a policy name. > [!WARNING] > > If there are no enabled routing policies, every request would be refused. The confirmation warns you, and deleting the last enabled policy while this is on warns you again. ## Budgets, model access, and cost * **Model access** is checked against both the policy name the caller sent *and* the model the policy chose. To allow or block a policy itself, target it with **Model Route or Routing Policy** in [Model Access](/how-tos/use-llm-controls). * **Budgets and rate limits** targeted at **Model Route or Routing Policy** match the name the caller sent — the policy's name — not the slot it was routed to. A budget on `smart` counts everything sent to `smart`, whichever model served it. To cap one underlying model however it's reached, target its **Upstream Model** instead. See [LLM Controls](/how-tos/use-llm-controls). * **The determiner call is billed to the caller.** It counts against their budgets and rate limits and is recorded under the determiner model's name, not the policy's. On the [LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard), grouping by **Routing Role** separates **User requests** from **Routing overhead** (determiner calls) and **Routing preview (admin)** (determiner calls made by **Preview routing** and **Test a request**). Preview spend is recorded but never counts against anyone's budget or rate limit. ## Seeing why a request went where it did **Response headers.** Responses to a routing-policy request include `x-bd-router-*` headers, among them: | Header | Meaning | | - | - | | `x-bd-router-model` | The policy name the caller sent | | `x-bd-router-target-model` | The model or route it was sent to | | `x-bd-router-slot-index` | The slot served (0 = least capable) | | `x-bd-router-source` | What decided: `heuristic`, `determiner`, `default_on_failure`, `sticky_stay`, or `pin_break` | | `x-bd-router-reason` | A short explanation, written by the determiner or the gateway | | `x-bd-router-clamp-reason` | What moved the pick, if anything: `none`, `model_access`, `capability_floor`, `rule_floor`, or `rule_ban` | | `x-bd-router-picked-before-clamp` | The slot the determiner picked, when something moved it | | `x-bd-router-matched-rule-name` | The rule that constrained the request, if any | | `x-bd-router-skipped-reason` | On a pinned turn, why the determiner didn't run: `tool_turn`, `at_max_slot`, or `no_new_content` | > [!WARNING] > > The determiner writes `x-bd-router-reason` about the request it read, so it can quote the request's text. **Audit History.** Routed requests can be filtered by: | Filter | Values | | - | - | | **Routing Decision** | **Heuristic** (decided by size or images), **Determiner**, **Determiner failed** (fallback slot used), **Sticky pin** (stayed on the conversation's model), **Pin break** (the conversation was re-routed) | | **Routing Override** | **Not overridden**, **Access limit**, **Capability required**, **Rule floor**, **Rule ban** | | **Routing Re-check** | Why a pinned turn skipped the determiner: **Tool turn**, **Highest model reached**, **No new content** | Filtering **Routing Override** to anything other than **Not overridden** finds every request where a limit or rule changed the model. # Export audit logs to your own storage Source: https://docs.barndoor.ai/how-tos/log-export Stream Barndoor audit events to your own S3-compatible or Azure Blob storage in near real time ## Overview Barndoor can stream every audit event from your tenant — authentication, authorization decisions, AI agent requests, tool calls, policy changes, and more — to storage you own: an S3-compatible bucket or an Azure Blob Storage container. Events are batched, gzipped, and uploaded as JSON Lines files partitioned by date and hour. Once configured, logs land in your storage within a minute of being generated and remain under your retention and access policies. This guide walks through configuring a destination, choosing an authentication method, and verifying that events are flowing. The delivery format is identical for both destination types — only the connection fields and the credential differ. > [!NOTE] > > **Estimated time**: 10–20 minutes (longer if you need to provision a new bucket, container, or IAM role) ## Before You Begin You'll need a Barndoor account with **admin** privileges on the organization whose events you want to export, plus one of the two destinations below. **For an S3-compatible destination:** * A bucket you own. AWS S3, Google Cloud Storage (via the S3 interop endpoint), MinIO, and SeaweedFS are all supported. * Either: * **An IAM role** (AWS S3 only) whose trust policy permits Barndoor to assume it, **or** * **An access key pair** with `s3:PutObject` permission on your bucket **For an Azure Blob Storage destination:** * An Azure storage account and a container that already exists. Barndoor writes into the container but doesn't create it. * Either: * **The storage account's access key**, **or** * **The ability to mint a container-scoped SAS** (shared access signature) with **Read**, **List**, **Write**, and **Create** permissions > [!TIP] > > If your bucket is in AWS S3, we strongly recommend IAM-role authentication over access keys. It avoids handing long-lived credentials to Barndoor and is the standard pattern for cross-account access in AWS. > > On Azure, the equivalent least-privilege choice is a container-scoped SAS token rather than the storage account's access key — it limits Barndoor to the one container you're exporting to. ## Authentication Methods Pick a credential when you configure the destination — you can switch later without recreating the export. The options depend on which destination type you choose. ### S3-compatible destinations | | **IAM role** (AWS only) | **Access keys** | | - | - | - | | **Cloud support** | AWS S3 only | AWS S3, GCS, MinIO, SeaweedFS, any S3-compatible service | | **Credentials in Barndoor** | None — we assume your role on every batch via STS | Long-lived `access_key_id` / `secret_access_key` stored in our secret vault | | **Rotation** | Automatic — Barndoor mints short-lived credentials each batch | Manual — you rotate the keys and re-paste them into the Barndoor UI | | **Setup effort** | Create one IAM role with trust + permissions policies | Create one IAM user and generate access keys | ### Azure Blob Storage destinations | | **Account key** | **SAS token** | | - | - | - | | **Scope** | The entire storage account — every container in it | Whatever you sign; scope it to the single container you're exporting to | | **Expiry** | None — valid until you regenerate the key | Built into the token, so exports stop when it lapses | | **Rotation** | Regenerate the key in Azure, paste the new value into Barndoor | Mint a fresh token before the current one expires and re-save the destination | | **Setup effort** | Copy one value out of the Azure portal | Generate a signature with the permissions and expiry you want | A container-scoped SAS is the recommended choice: it's the least-privilege option, and rotating it is a single field edit. Use the account key when a SAS doesn't fit your workflow and you'd rather not track an expiry date. ## Configure with IAM Role Authentication This is the recommended path for AWS S3 destinations. ### Step 1: Start the configuration in Barndoor 1. Sign in to your Barndoor portal and navigate to **Audit Log Export** in the side nav. 2. For the destination provider, choose **Amazon S3 / S3-compatible**. 3. Fill in the connection details: * **Endpoint URL** — `https://s3..amazonaws.com` (e.g. `https://s3.us-east-1.amazonaws.com`) * **Bucket Name** — the bucket events will land in * **Region** — matching AWS region (e.g. `us-east-1`) * **Path Prefix** *(optional)* — key prefix for every object. Defaults to `audit-events/`. 4. Under **Authentication**, choose **IAM role (AWS only)**. The UI will display two values you'll need in the next step: * **Barndoor principal** — the IAM role ARN that Barndoor will use to assume your role * **External ID** — a random 64-character string unique to your destination. This is a shared secret used as the `sts:ExternalId` to defend against the [confused-deputy problem](https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html). Leave this tab open while you set up the role in AWS. ### Step 2: Create the IAM role in your AWS account In the AWS console, go to **IAM → Roles → Create role**: 1. **Trusted entity type**: **Custom trust policy**. Paste the snippet below, substituting `` and `` with the values from the Barndoor UI: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "" }, "Action": "sts:AssumeRole", "Condition": { "StringEquals": { "sts:ExternalId": "" } } } ] } ``` > [!TIP] > > The Barndoor UI provides a copy-pasteable version of this exact policy with the values filled in — click the copy button next to "Trust policy JSON". 2. **Permissions**: skip the AWS managed-policies screen — we'll add an inline policy after the role is created. 3. **Name**: any name you like, e.g. `barndoor-audit-export`. **Copy the role ARN** once it's created. 4. On the role's detail page, **Add permissions → Create inline policy**. Paste the snippet below, replacing ``: ```json theme={null} { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:ListBucket", "s3:GetBucketLocation" ], "Resource": [ "arn:aws:s3:::", "arn:aws:s3:::/*" ] } ] } ``` > [!NOTE] > > `ListBucket` and `GetBucketLocation` are used by Barndoor's "Check connection" health check. `PutObject` is what audit-consumer uses at runtime to upload event files. ### Step 3: Paste the role ARN back into Barndoor Back in the Audit Log Export page: 1. Paste the role's ARN into **IAM Role ARN**. 2. Pick the event types to include (see [Selecting event types](#selecting-event-types) below) or leave the default (all types). 3. Click **Save Configuration**. The destination saves in a **paused** state so you can verify the connection before any events flow. 4. Click **Check Connection**. Barndoor assumes your role, performs a `HeadBucket` against your destination, and reports the result. If you see **Connection Healthy**, you're done with setup. If not, jump to [Troubleshooting](#troubleshooting). ### Step 4: Start the stream Once the connection is healthy, click **Start** in the **Current Status** card. The badge flips to **Streaming Active** and new audit events begin flowing to your bucket within \~30 seconds. ## Configure with Access Keys Use this path for non-AWS S3-compatible destinations or when an IAM user fits your team's workflow better. ### Step 1: Create the IAM user / equivalent In AWS: 1. **IAM → Users → Create user**, name it (e.g. `barndoor-audit-export`). 2. Skip the AWS Management Console access option — this user only needs programmatic access. 3. Once the user is created, **Security credentials → Create access key → Application running outside AWS** (or equivalent). Save the access key and secret. 4. **Add inline policy** with the same S3 permissions snippet from [Step 2 of the IAM-role flow](#step-2-create-the-iam-role-in-your-aws-account). For non-AWS S3 services (GCS HMAC, MinIO, SeaweedFS), follow the service's instructions for creating an access key pair scoped to your bucket. ### Step 2: Paste the keys into Barndoor 1. Navigate to **Audit Log Export**, choose **Amazon S3 / S3-compatible** as the destination provider, and fill in **Endpoint URL**, **Bucket Name**, **Region**, **Path Prefix**. 2. Under **Authentication**, choose **Access keys**. 3. Paste the **Access Key ID** and **Secret Access Key**. 4. Click **Save Configuration**, then **Check Connection**, then **Start** — same flow as the IAM-role path. > [!WARNING] > > The access key and secret never leave Barndoor's encrypted secret store and are never displayed again in the UI. To rotate, edit the destination and paste new values. ## Configure with Azure Blob Storage Use this path when your events should land in an Azure storage account instead of an S3-compatible bucket. Region, path-style addressing, and the IAM-role flow are S3-only concepts — they don't apply here and the form doesn't ask for them. ### Step 1: Get a credential from Azure Pick whichever method you settled on in [Authentication Methods](#azure-blob-storage-destinations). **Account key** 1. In the Azure portal, open the storage account that holds your container. 2. Go to **Security + networking → Access keys**. 3. Click **Show** next to **key1** (or **key2**) and copy the **Key** value. Barndoor wants that key on its own — not the full connection string. **Container-scoped SAS token** 1. In the Azure portal, open the storage account and go to **Data storage → Containers**. 2. Click the container you're exporting to, then **Shared access tokens** in its menu. 3. Under **Permissions**, select at least **Read**, **List**, **Write**, and **Create**. 4. Set an expiry you're comfortable rotating on, then click **Generate SAS token and URL**. 5. Copy the **Blob SAS token** — the query string, not the full blob URL. The same signature from the Azure CLI: ```bash theme={null} az storage container generate-sas \ --account-name \ --name \ --permissions rlwc \ --expiry 2027-01-01T00:00:00Z \ --output tsv ``` > [!TIP] > > Paste the SAS token with or without its leading `?` — Barndoor accepts either. ### Step 2: Fill in the destination in Barndoor 1. Sign in to your Barndoor portal and navigate to **Audit Log Export** in the side nav. 2. For the destination provider, choose **Azure Blob Storage**. 3. Fill in the connection details: * **Blob Service URL** — the blob service root for your account, `https://.blob.core.windows.net`. It must be `https`, and it must not include the container — that's a separate field. * **Container** — the name of the existing container events will land in. * **Path Prefix** *(optional)* — blob-name prefix for every upload. Defaults to `audit-events/`. 4. Under **Authentication**, choose **Account key** or **SAS token** and paste the value you copied into the credential field. 5. Pick the event types to include (see [Selecting event types](#selecting-event-types) below) or leave the default (all types). 6. Click **Save Configuration**. The destination saves in a **paused** state so you can verify the connection before any events flow. > [!NOTE] > > Sovereign clouds work the same way — only the endpoint domain changes, for example `https://.blob.core.chinacloudapi.cn` or `https://.blob.core.usgovcloudapi.net`. ### Step 3: Verify and start the stream 1. Click **Check Connection**. Barndoor reads the container's properties with the credential you supplied and reports the result. The credential needs at least **Read**, **List**, and **Write** on the container — the health check reads, and delivery writes. 2. If you see **Connection Healthy**, click **Start** in the **Current Status** card. The badge flips to **Streaming Active** and new audit events begin flowing to your container within \~30 seconds. Delivery is identical to the S3 path: batched, gzipped JSON Lines blobs, partitioned by date and hour under your path prefix. See [Object format and partitioning](#object-format-and-partitioning). ### Rotating a SAS token A SAS token carries its own expiry, so plan a rotation before it lapses. Rotating is just re-saving the destination: 1. Mint a fresh token with the same permissions. 2. Open the destination, paste the new token into the **SAS token** field, and save. Delivery picks up the new token automatically within a minute — no need to pause, remove, or recreate the destination. > [!WARNING] > > If a token expires before you replace it, the **Current Status** card starts reporting delivery errors. Saving a fresh token clears them and delivery resumes. Account keys don't expire, but they're account-wide — regenerate them on whatever schedule your team uses for storage credentials. ## Selecting Event Types The right-hand panel of the configuration form lets you pick which event categories to export. By default all 16 event types are included. Available categories: * **Policy** — `AUTHORIZATION`, `POLICY_DECISION` * **Identity** — `AUTHENTICATION`, `SESSION_CREATED`, `SESSION_TERMINATED`, `SESSION_UPDATED`, `TOKEN_EXCHANGE` * **AI Agent & Data** — `AI_REQUEST`, `DATA_ACCESS`, `TOOL_CALL` * **Platform & Activity** — `AUDIT`, `REQUEST_COMPLETED`, `REQUEST_FORWARDED`, `REQUEST_RECEIVED`, `SYSTEM`, `USER_ACTION` Click a category header to expand it and toggle individual event types. The badge shows how many you've selected out of the total. **Select all** / **Clear all** reset the selection for the whole list. Event-type filters apply only to future events. Changing them doesn't backfill or remove already-exported objects. ## Object Format and Partitioning Exported objects use this layout: ``` //dt=YYYY-MM-DD/hour=HH/archive_HHMMSS...json.gz ``` For example, with the default prefix `audit-events/`: ``` my-bucket/audit-events/dt=2026-05-15/hour=07/archive_073825.0000.96568337-7073-4ab6-b431-c7d3d7251877.json.gz ``` Azure Blob destinations use the same naming, with your container standing in for the bucket. Inside each gzipped file is one JSON object per line, in a shape compatible with Datadog's log-ingestion format. Trace and span IDs are included on events that originated within a traced request so you can correlate audit logs with traces in your observability stack. Batches flush every 30 seconds or when the buffer reaches 100 events, whichever comes first. ## Pausing and Resuming The **Pause** / **Start** button on the destination page is independent of the destination configuration. Pausing buffers new audit events on the Barndoor side; resuming drains the buffer to your destination. You can also delete the destination entirely with **Remove** — this clears any stored credential (access keys, an Azure account key, or a SAS token) and stops exports until a new destination is configured. ## Troubleshooting ### "Connection Unhealthy" after Check Connection (S3) Look at the message under the badge. Common causes: * **`AccessDenied` on `HeadBucket`** — the IAM role or user is missing `s3:ListBucket` and `s3:GetBucketLocation` on the bucket. Re-check the inline permissions policy. * **`not authorized to perform: sts:AssumeRole`** — the trust policy's `Principal` doesn't match Barndoor's principal ARN exactly. Re-copy from the Barndoor UI. * **`Invalid ExternalId`** — the `sts:ExternalId` in your trust policy doesn't match what Barndoor expects. Open the destination in the UI and re-copy the External ID; the value is stable per destination. * **`NoSuchBucket`** — bucket name typo, or the bucket is in a different region than what you entered. ### "Last delivery issue: ... AccessDenied" but Check Connection passes Health check uses `HeadBucket` (`ListBucket` / `GetBucketLocation` permissions). Actual uploads use `PutObject`. If health check is green but uploads fail with `AccessDenied`, your role / user is missing `s3:PutObject`. Add it to the inline permissions policy. ### "Connection Unhealthy" or delivery errors on an Azure destination * **`AuthorizationPermissionMismatch` or `AuthenticationFailed`** — the credential needs at least **Read**, **List**, and **Write** on the container (a container SAS also needs **Create**). Re-mint the signature with the missing permissions, or check that you pasted the account key rather than the connection string. * **`AuthenticationFailed` with a signature-expiry message** — the SAS token has passed its expiry. Mint a new one and save it on the destination; see [Rotating a SAS token](#rotating-a-sas-token). * **`ContainerNotFound`** — container name typo, or the container doesn't exist. Barndoor writes into an existing container and never creates one. * **`ResourceNotFound` or connection errors on the endpoint** — the **Blob Service URL** must be the account root (`https://.blob.core.windows.net`) over `https`, with no container path appended. Move the container name into the **Container** field. ### No objects appearing in the bucket or container even though the stream is "Active" Audit events are only emitted when traffic flows through Barndoor. If you've just configured an empty test organization and there's no activity, the buffer may genuinely have nothing to upload. Generate some events by logging in/out, navigating around the portal, or making an API call against your tenant — anything that crosses Barndoor's authorization or proxy paths. ### Switching between IAM-role and access-keys mode Editing an existing destination to switch modes is supported. When you switch from access keys to IAM role, Barndoor automatically deletes the stored access keys from its vault. When you switch the other way, you'll be prompted to enter new access keys. ### Switching between S3 and Azure Blob Storage Editing an existing destination to switch providers is also supported. Changing the provider — or the authentication method — always requires entering the new destination's credentials; the previously stored credential is replaced when you save. The export itself (delivery settings, event-type selection) carries over unchanged, and streaming resumes against the new destination once its connection check passes. ## Frequently Asked Questions > [accordion] What happens if my IAM role's trust policy or bucket permissions change? > > The next upload attempt will fail. The destination's status banner in the Barndoor UI will show the AWS error message. Re-check the trust and permissions policies — Barndoor doesn't cache anything that survives an updated AWS-side configuration. > [accordion] Can the same IAM role serve multiple Barndoor organizations? > > Each Barndoor destination has its own External ID, so even within a single AWS account a single role can support multiple Barndoor tenants by allowing multiple `sts:ExternalId` values in the trust policy. In practice we recommend one role per Barndoor organization for clean auditing. > [accordion] Is there a backfill option for historical events? > > Not currently — exports start from the moment you click **Start**. Historical events remain queryable in the Barndoor portal but aren't replayed to your bucket. > [accordion] What's the data retention on Barndoor's side while paused? > > Buffered events are retained for 30 days while the stream is paused. If you resume within that window, all buffered events stream out in order. If you exceed it, older buffered events are dropped. # Managing LLM API Keys Source: https://docs.barndoor.ai/how-tos/manage-llm-api-keys Set expirations on LLM Gateway API keys, rotate them without an outage, extend them, filter and act on them in bulk, and limit how long users' own keys may live. ## Overview Every request to the LLM Gateway carries a `bd-…` API key. Keys can expire, and they can be rotated, extended, disabled, and revoked. Admins can also limit how long the keys users create for themselves may live. | Where | Who | What you can do | | - | - | - | | **LLM Management → API Keys** | Admins | Every key in the organization: create, rotate, change expiration, disable, enable, revoke, and act on many keys at once | | **LLM Management → Key Policies** | Admins | The organization's limit on how long self-serve keys may live, with group and user overrides | | [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) | Every user | Your own keys: create, rotate, disable, enable, and revoke | ## Before You Begin You'll need: * A Barndoor account. Any user can manage their own keys; **LLM Management** needs **admin privileges**. * The LLM Gateway set up for your organization — see the [LLM Gateway Quickstart](/how-tos/llm-gateway-quickstart). ## Key Status Each key is in exactly one status. The **Status** column shows it, and the gateway enforces it on every request. | Status | Requests | What it means | | - | - | - | | **Active** | Accepted | The key works and isn't due to expire within 7 days | | **Expiring soon** | Accepted | The key expires within 7 days. The **Expires** column shows how long is left. | | **Disabled** | Rejected | An admin or the owner turned the key off. **Enable** turns it back on with the same secret. | | **Expired** | Rejected | The expiration has passed. Rotate the key, or have an admin change its expiration, to bring it back. | | **Revoked** | Rejected | Permanently off. A revoked key can't be brought back. | ![LLM Management API Keys list filtered to the default Active, Expiring soon, and Disabled statuses, with Expired and Revoked chips unselected; keys show Disabled, Expiring soon with days left, Active with no expiry, and Active with a Rotating note](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/11-api-keys-list.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=ca4ab4898cdda2c5baac44511e409821) A rejected key gets a `401` from the gateway. See [What callers see when something is denied](/how-tos/use-llm-controls#what-callers-see-when-something-is-denied). ## Create a Key With an Expiration 1. Go to **LLM Management → API Keys** and click **Create Key**, or to **Settings → My Models → API Keys** for a key of your own. 2. Enter a **Name**. On **LLM Management**, optionally **Assign to User** or **Assign to Group**. 3. Under **Expiration**, open the picker and choose when the key stops working: * a quick pick — **1 hour**, **1 day**, **7 days**, **30 days**, **90 days**, or **1 year**; * a date on the calendar, which expires at the end of that day (23:59) unless you type a time; or * **No expiry**, if your organization allows it. Use the **Local** / **UTC** switch to read and set the time in your own time zone or in UTC. The expiration is stored as a single moment, so it means the same thing wherever the key is used. 4. Click **OK**, then **Create**. ![Create API Key dialog on My Models with an expiration 30 days out and a note that the organization requires keys to expire within 90 days](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/01-create-api-key.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=e889e4d13747dee4289695935064340e) 5. Copy the key from the **API Key Created** dialog. It's shown only once — Barndoor keeps only a hash. When the expiration passes, the gateway rejects the key. Nothing else about it changes, so you can still see it, its bindings, and its usage history. > [!NOTE] > > If your organization has a [key policy](#limit-key-lifetimes-with-key-policies), the picker on **Settings → My Models** only offers expirations within your limit and says what the limit is. If your organization sets a fixed lifetime, there's no picker: the dialog shows when the key will expire instead. Keys created on **LLM Management** are exempt from key policies. ## Rotate a Key Rotating replaces a key's secret but keeps the key itself, so its ID, name, user or group binding, and usage history carry over. Rotate on a schedule, when a key is about to expire, or when a secret may have leaked. 1. Open the key's **⋮** menu and choose **Rotate**. On **Settings → My Models**, click the key's rotate icon. 2. Choose a **Grace period for the old key**: | Grace period | What happens to the old secret | | - | - | | **None** | Stops working immediately. Use this when a secret has leaked. | | **1 hour**, **24 hours**, **7 days** | Keeps working for that long alongside the new one, so you can update clients without an outage | 3. Set the **New expiration**. It starts at the key's current expiration, and leaving it unchanged keeps it. If the key has already expired, or its expiration is outside your key policy, you must pick a new one. ![Rotate API Key dialog with a 24-hour grace period for the old key and the new expiration left unchanged](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/12-rotate-api-key.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=5a5d1bd876762684f007a315234c778a) 4. Click **Rotate Key**, then copy the new secret. Like a new key, it's shown only once. While a grace period is running, the **Expires** column notes that the previous secret still works and until when. > [!TIP] > > To renew a key that's about to expire, rotate it with a later **New expiration** and a grace period long enough to roll the new secret out. For a user's own key under a fixed-lifetime policy, a rotation always renews the key to exactly that many days. ## Change a Key's Expiration Admins can extend, shorten, or remove a key's expiration without issuing a new secret, so the key's clients keep working unchanged. 1. On **LLM Management → API Keys**, open the key's **⋮** menu and choose **Change expiration**. 2. Pick the new expiration, or **No expiry**. 3. Click **Save**. * **Extending** takes effect at once. * **Shortening** also takes effect at once. The new expiration must still be in the future; to stop a key now, disable or revoke it. * **An expired key** becomes usable again, with the same secret, when you save an expiration in the future. Changing an expiration isn't limited by key policies, and it's only on **LLM Management**. On **Settings → My Models**, users renew their own keys by rotating them. ## Disable or Revoke a Key * **Disable** blocks the key temporarily. The secret stays issued, and **Enable** turns the key back on without handing out a new one. * **Revoke** blocks the key permanently. Applications using it lose access immediately, and it can't be rotated, extended, or re-enabled. To replace it, create a new key. ## Find and Act on Many Keys On **LLM Management → API Keys**: * **Search** by key name, user, group, or key ID. * **Filter by status** with the chips above the table. Each chip shows how many keys have that status. By default the list shows **Active**, **Expiring soon**, and **Disabled** keys; turn on **Expired** or **Revoked** to see those too, or click **Reset** to go back to the default. The filter is kept in the page address, so you can bookmark or share a filtered view. * **Sort** by any column, including **Status** and **Expires**. To act on several keys at once: 1. Click **Select keys**. 2. Tick the keys you want, or click **Select all** to take every key that matches the current search and filter, including keys on other pages. 3. Click **Disable**, **Enable**, or **Revoke**. Each button shows how many of the selected keys it applies to. A key that's already disabled isn't disabled again, for example. 4. Click **Cancel selection** when you're done. If some keys in a bulk action fail, the message names them; the others are still changed. On **Settings → My Models → API Keys**, expired keys are hidden until you tick **Show expired**. ## Limit Key Lifetimes With Key Policies **LLM Management → Key Policies** controls how long the API keys that users create for themselves may live. Keys that admins create on **LLM Management → API Keys** are exempt. > [!NOTE] > > Key Policies may not be enabled for your organization yet — contact Barndoor if you don't see **Key Policies** in **LLM Management**. ![Key Policies page with an organization default of at most 90 days, group overrides for contractors (exactly 30 days) and engineering (at most 180 days), and a user override with no limit](https://mintcdn.com/barndoor/wVRWtdDvuAdONzeK/images/llm-gateway/13-key-policies.png?fit=max\&auto=format\&n=wVRWtdDvuAdONzeK\&q=85\&s=7105eefa7913d52db4a21d8891414a6a) ### What a policy sets Each policy — the organization default, a group override, or a user override — combines three settings: | Setting | Effect | | - | - | | **Max lifetime** (days) | Keys must expire within this many days of being created or rotated. Leave it empty for no maximum. | | **Require an expiration** | Keys can't be created with **No expiry**. Implied when a max lifetime is set. | | **Fixed (users can't choose)** | Every key gets exactly the max lifetime, and users don't pick an expiration. Needs a max lifetime. | The policy list summarizes each one as **Exactly 30 days**, **At most 90 days**, **Expiry required**, or **No limit**. ### Set the organization default 1. Go to **LLM Management → Key Policies**. 2. Under **Organization default**, set the **Max lifetime** and the boxes you want. Leave the max empty and the boxes unticked for no limit. 3. Click **Save default**. ### Add group and user overrides An override replaces the default for the people it covers, so it can be longer or shorter than the default. 1. Under **Group overrides** or **User overrides**, search for and pick one or more groups or users. 2. Set the limit, then click **Add override** (or **Add user override**). Every group or user you picked gets its own override with the same settings, which you can then edit or remove one at a time. To exempt a group or a user, add an override with no max and no required expiration. ### Which policy applies For a given user, the gateway uses the first of these that exists: 1. **The user's own override.** It wins over everything else, so it can be looser or stricter than their groups and the default. 2. **Their group overrides.** A user in several overridden groups gets the strictest of those overrides. 3. **The organization default.** ### When a policy is checked A policy is checked when a user **creates** or **rotates** a key, on the portal and through the API alike. Changing a policy doesn't shorten keys that already exist: they keep their expiration until they're next rotated, and at that point the new expiration has to fit the policy. ## Expiration Alerts The gateway checks for expiring keys every 15 minutes and raises these [alerts](/how-tos/notifications): | Alert type | Severity | When it fires | | - | - | - | | **LLM API key expiring** | Warning | When a key has 7 days left, and again when it has 1 day left. A key created or extended into a window gets only the alert for the window it's in. | | **LLM API key expired** | Critical | Once, after the key's expiration passes | | **LLM API key revoked** | Info | When an admin or the key's owner revokes it | Each alert fires once per key and stage. Rotating or extending a key to a new expiration starts its alerts over. Each alert links to the key on **LLM Management → API Keys**. To receive these alerts, turn the alert types on for your inbox, email, or an organization-wide channel — see [Notifications](/how-tos/notifications). ## Manage Keys Through the API or Terraform Everything on this page is also available through the API — see **API Keys** and **Key Lifetime Policies** in the [LLM Gateway API reference](/api-reference/llm-gateway/introduction). To manage keys and key policies as code, use the [Barndoor Terraform provider](/terraform/llm-gateway). ## Troubleshooting > [accordion] A client suddenly gets 401 errors > > Check the key's status on **LLM Management → API Keys**. Turn on the **Expired** and **Revoked** filter chips if you don't see it. An **Expired** key can be rotated or have its expiration changed; a **Disabled** key can be enabled; a **Revoked** key must be replaced with a new one. > [accordion] The expiration I want is greyed out > > Your organization's key policy limits how long your keys may live. The picker says what the limit is. Ask an admin for an override, or for an admin-created key, which isn't subject to key policies. > [accordion] Rotating asks for a new expiration > > The key has already expired, or its current expiration is outside your key policy. Keeping it would leave the new secret unusable or break the policy, so pick a new expiration. > [accordion] The old secret stopped working right after rotating > > The rotation used a grace period of **None**. Rotate again with a grace period to give clients time, or update them to the new secret. ## Need Help? Contact [support@barndoor.ai](mailto:support@barndoor.ai) if you have questions about API keys or key policies. # Managing Model Pricing Source: https://docs.barndoor.ai/how-tos/manage-model-pricing Control the per-million-token prices the Barndoor LLM Gateway uses to cost requests, so spending budgets and cost reporting are accurate. ## Overview **Model Pricing** sets how much each model costs per million tokens. Those prices drive every cost figure on the platform: * **spending budgets** in [LLM Controls](/how-tos/use-llm-controls#budgets) * the **cost recorded for each request** * cost in **Reporting → LLM Usage Dashboard** — see [Reading the LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard) Model Pricing lives in the Barndoor portal under **LLM Management → Model Pricing**. ![Model Pricing section showing the Org rules, Archive, and Barndoor defaults tabs](https://mintcdn.com/barndoor/la1TQbfBQ5KqGqlz/images/model-pricing/01-pricing-tab.png?fit=max\&auto=format\&n=la1TQbfBQ5KqGqlz\&q=85\&s=c806abd559e0df2384c69baf2658b2b5) > [!NOTE] > > Barndoor maintains a curated catalog of default prices for common models across OpenAI, Anthropic, AWS Bedrock, Google Vertex AI, Azure OpenAI, and more, and applies it automatically. **Those models are costed out of the box, with no setup.** You only need your own rules to override a Barndoor price (a negotiated discount, a different vendor rate) or to price a model the catalog doesn't cover (a fine-tune, a private deployment, a brand-new model). > [!WARNING] > > A request for a model that no rule covers — neither yours nor a Barndoor default — still succeeds, but is recorded at **\$0**. Spending budgets don't move and reports show zero cost. These models are shown as **Unpriced** wherever the portal lists pricing. ## Before You Begin * A Barndoor account with **admin** privileges. * An LLM Gateway with at least one provider and one model configured — see [Using the LLM Gateway](/how-tos/use-llm-gateway). ## The Three Tabs | Tab | What it lists | | - | - | | **Org rules** | Your organization's own pricing rules — imported defaults and custom rules — with scope, catalog, provider, input and output prices, cache prices, and **Last Updated**. | | **Archive** | Rules you've archived. Their full history is kept, and they can be restored. | | **Barndoor defaults** | Every price in Barndoor's catalog, each marked **Imported** or **Not imported**. | Search matches the model pattern. You can also paste a pricing rule ID (for example from a request log) to find the rule, or an older version of it, on whichever tab it lives. Filter by **scope** and **catalog**, and sort by the column headers. ## How Cost Is Computed Cost is calculated after a successful upstream response, from the token counts the provider reports. Failed requests record no cost. All prices are USD per million tokens. ```text theme={null} cost = input tokens × input price + output tokens × output price + cache-read tokens × cache read price + cache-write tokens × cache write price ``` * **Input tokens** exclude tokens served from the prompt cache, which are billed separately at the **cache read** price. * **Output tokens** include any reasoning tokens the provider reports; reasoning isn't billed separately. * A rule with no **cache read** or **cache write** price bills those tokens at the rule's **input** price. * If the rule has a **long-context surcharge** and the request's total prompt (input plus cache reads and writes) is at or above its threshold, the *whole* request — output included — is billed at the surcharge rates. * Rules match the **underlying model name** the provider is called with (for example `anthropic.claude-opus-5-5` on a Bedrock provider), not the route name the caller sent. > [!NOTE] > > A provider whose **Calculate token cost** setting is turned off (a flat-rate subscription, self-hosted inference, or usage billed elsewhere) records **\$0** for every request, even where a pricing rule matches. Those requests are labelled **Not metered**, not **Unpriced**: the rate is known to be zero rather than unknown. Change this in the provider's settings. ## How Pricing Resolves For each request, Barndoor looks for a matching rule in this order. The first tier with a match wins. Request to cost ?**Provider calculates token cost?**Set in the provider's settingsNo: \$0 · Not meteredYes: most specific tier first1**Provider Instance rule**This provider connectionMatch: use rate 2**Catalog rule**This vendor line, such as OpenAI or AWS BedrockMatch: use rate 3**Generic rule**Any providerMatch: use rate 4**Barndoor default**Barndoor's catalog priceMatch: use rate No match**\$0, labelled Unpriced**Add a pricing rule to cost this model | Tier | Scope badge | Use when | | - | - | - | | **1. Provider instance** | **Provider Instance** | You have a custom rate on one specific provider connection (for example one Azure deployment). | | **2. Catalog** | **Catalog** | The price applies to a whole vendor line — every OpenAI provider, every Bedrock provider — but not across vendors. | | **3. Generic** | **Generic** | The price applies wherever the model name matches, regardless of provider. The simplest and most common choice. | | **4. Barndoor default** | — | Barndoor's catalog. Applies automatically when none of your rules match. | **Within a tier, the most specific pattern wins**: an exact name beats a wildcard, and a longer wildcard beats a shorter one — so `claude-sonnet-5-5*` beats `claude-*`, and a catch-all `*` loses to everything. A higher tier always wins, however specific a lower-tier pattern is. In the portal, each model shows the price it resolves to and where it came from: **Org rule (this provider)**, **Org rule (provider type)**, **Org rule**, **Barndoor default**, **Not metered**, or **Unpriced**. > [!TIP] > > Stick to **Generic** rules for everyday pricing. Use **Catalog** or **Provider Instance** rules only when the same model genuinely has a different price on different vendors or connections. ## Importing Barndoor Defaults Importing copies a Barndoor default into your org rules so you can edit it, pin it, or keep it in sync. You don't need to import a default for it to apply. **1. Open LLM Management → Model Pricing → Barndoor defaults** Or click **Add Pricing Rule → A Barndoor default**. **2. Import one row** Click **Import** on a row and choose how it should track Barndoor: **Tracking**, **Pinned**, or **Auto-sync** (see [Keeping Prices in Sync](#keeping-prices-in-sync-with-barndoors-catalog)). **3. Or import several** Click **Select to import**, tick rows (filter by catalog and use the header checkbox to select a whole vendor), pick a **Sync behavior**, and click **Import N**. An imported row shows **View rule**, which jumps to your org rule. ## Creating a Pricing Rule **1. Click Add Pricing Rule → A custom rule** The **Add Pricing Rule** dialog opens. **2. Model Pattern** Pick a model you've enabled from the dropdown, or type a pattern. Use `*` as a wildcard at the start, the end, or both: * `gpt-5.4-mini` — exactly that model. * `gpt-5.4*` — any model starting with `gpt-5.4`. * `*-mini` — any model ending in `-mini`. * `*claude-sonnet-5-5*` — any model containing `claude-sonnet-5-5` (useful for Bedrock IDs with regional prefixes). A `*` in the middle of a pattern (`gpt-*-mini`) and regular expressions aren't supported. **3. Catalog and Provider (optional)** * **Catalog** — restrict the rule to one vendor line. Leave on **Any catalog** for a Generic rule. * **Provider** — restrict it to one configured provider connection. Available once a catalog is picked; leave on **Any provider in catalog** for a Catalog rule. **4. Prices** * **Input Cost ($/1M tokens)** and **Output Cost ($/1M tokens)** — required. * **Prompt caching** — **Cache Read** and **Cache Write** prices (\$/1M tokens). Leave cache read blank and cached tokens are billed at the full input price, which overstates cost against the provider's cache discount. Cache write applies to Anthropic models. * **Long-context surcharge** (optional) — tick it for models whose price rises once a prompt is large. Set **Applies at or above (prompt tokens)** (pre-filled with `200000`) and the input and output prices above the threshold; blank cache prices above the threshold bill at the surcharge input price. **5. When this takes effect** Choose **Take effect immediately** or **Schedule for later** and pick a date and time (in your local time zone, accurate to about ±5 minutes). **6. Sync behavior and reason** * **Sync behavior** — only **I'll manage it** is available unless the pattern and catalog match a Barndoor default. * **Change reason (optional)** — recorded in the rule's [Pricing History](#pricing-history). **7. Save** An immediate rule applies to requests within a few minutes. A scheduled rule shows a **Scheduled** badge until it activates. ![Add Pricing Rule dialog with model pattern, catalog, provider, prices, scheduling, and sync behavior](https://mintcdn.com/barndoor/la1TQbfBQ5KqGqlz/images/model-pricing/03-create-pricing.png?fit=max\&auto=format\&n=la1TQbfBQ5KqGqlz\&q=85\&s=1e77ace0746ee941a3638cde78f0ba6e) > [!TIP] > > If enabling a model is blocked because it has no price, the portal can bring you here with the model pre-filled. Save with **… & return to** to go straight back to where you were. ## Editing and Scheduling Price Changes Click the pencil icon on a row to open **Edit Pricing**. Every save creates a **new version** of the rule; an existing price is never overwritten in place. That means: * **Past and current versions are an audit trail** and can't be changed or removed. * **Scheduled future versions can be edited or cancelled** from the rule's [Pricing History](#pricing-history). * **Changes are forward-looking.** They apply only to requests after the new version becomes active; they don't re-cost past requests or adjust spending already counted against a budget. In **Edit Pricing** you can change the prices, cache prices, long-context surcharge, timing, sync behavior, and change reason. The **model pattern, catalog, and provider can't be changed** — create a new rule for a different scope, and archive the old one if you no longer need it. Rows with pending future versions show **Scheduled** (or **N scheduled**). To change or cancel one before it activates, open the row's history and use the pencil (**Edit Scheduled Change**) or trash icon next to the scheduled entry. ### Reset to default When your price for a pattern differs from Barndoor's, the row's badge shows **Custom** and a **Reset to default** action appears on the row and in **Edit Pricing**. It creates a new version with the current default input and output prices, recorded with the reason `Reset to default`. > [!TIP] > > **Reset to default uses the *current* default**, not the one you originally imported. If Barndoor has changed its price since, Reset moves you to the new value. ## Archiving and Restoring Rules To stop using a rule, click the archive icon on its row (or **Select rules**, tick several, and click **Archive N**). Archiving: * removes the rule from **Org rules**, so cost falls back to the next matching tier — typically the Barndoor default, or \$0 if nothing else matches; * cancels any scheduled changes on the rule; * keeps the rule's full history, visible on the **Archive** tab. To bring a rule back, open **Archive** and click restore (or select several and click **Restore N**). The rule returns to **Org rules** at its last live price, and costing resumes within a few minutes. Edit it afterwards if the provider's rate has moved on. ## Pricing History The clock icon on a row opens **Pricing History** — every version of that rule, newest first. Each entry shows: * the input, output, and cache prices at that version, with the change from the previous version; * when it took effect (or will take effect); * who made the change; * how it was made: **Created**, **Edited**, **Scheduled**, **Imported**, **Synced (manual)**, **Auto-sync**, **Archived**, or **Restored**; * the **Change reason**, if one was given. Future-dated entries carry edit and cancel icons. Past entries are part of the audit trail and can't be removed — they're what Barndoor uses to know what a past request cost at the time. ## Keeping Prices in Sync with Barndoor's Catalog Barndoor updates its defaults as provider prices change. Each imported rule has a **Sync behavior** that decides what happens when a default it was imported from changes. Pick it when importing, and change it later in **Edit Pricing**. | Sync behavior | Import option | What it does | | - | - | - | | **Prompt me on updates** | **Tracking** | Keeps your imported price. When the default changes, the row shows **Update available** and a **Review updates** banner appears. | | **I'll manage it** | **Pinned** | A fixed price you maintain. Barndoor never changes it and never prompts you. The row shows **Custom** with a lock icon. | | **Auto-sync to Barndoor** | **Auto-sync** | Barndoor applies default changes automatically, within about a minute. Each change is recorded in the rule's history. The row shows **Auto-sync**. | ### Reviewing updates When tracked rules are behind Barndoor's defaults, a banner reads *N imported prices have a new Barndoor default*. Click **Review updates** to open **Review pricing updates**, which lists each affected rule with its current and new prices. Tick the rules to adopt and click **Sync N Prices**; unticked rules keep their current price and stay flagged. To stop being prompted about a rule, set its sync behavior to **I'll manage it** in **Edit Pricing**. > [!TIP] > > **Auto-sync** keeps you on Barndoor's prices with no interaction, at the cost of prices changing underneath you. **Prompt me on updates** surfaces each change for review first — a good fit when prices feed spending budgets you don't want to shift quietly. ## Badges on Org Rules | Badge | Meaning | | - | - | | **Default** | Tracking a Barndoor default, and your price matches it. | | **Custom** | Your price differs from the Barndoor default. With a lock icon: the rule is set to **I'll manage it**. | | **Manual** | Barndoor has no default for this pattern; you created it from scratch. | | **Update available** | A tracked rule whose Barndoor default has changed. Use **Review updates**. | | **Auto-sync** | The rule follows Barndoor's default automatically. | | **Scheduled** / **N scheduled** | The rule has future-dated versions waiting to activate. | | **Provider Instance** / **Catalog** / **Generic** | The rule's [resolution tier](#how-pricing-resolves). | ## Require Pricing for Model Routes The **Require pricing for Model Routes** toggle at the top of Model Pricing stops models that would be recorded at \$0 without anyone deciding so. !['Require pricing for Model Routes' toggle at the top of the Model Pricing section](https://mintcdn.com/barndoor/la1TQbfBQ5KqGqlz/images/model-pricing/04-require-pricing-toggle.png?fit=max\&auto=format\&n=la1TQbfBQ5KqGqlz\&q=85\&s=e3c6c9e1d6108f954e606310a6d84e41) When **on**: * A model can't be enabled, and a route can't be added or re-enabled, unless the model is covered by **an org rule or a Barndoor default**. The save is refused with a message saying the model has no pricing. * Models on a provider whose **Calculate token cost** setting is off pass automatically — they're \$0 by design. * Already-enabled models with no coverage keep serving traffic at \$0 and are flagged **Unpriced** in the model list, with a **Disable N unpriced** action to switch them off in bulk. When **off** (default), any model can be enabled; uncovered models are recorded at \$0. *** ## Troubleshooting > [accordion] A spending budget or report shows \$0 for a model > > Check the model's pricing label in the portal: > > * **Unpriced** — no rule matches. The model may be missing from Barndoor's catalog (a fine-tune, a private model, a very new model), or your pattern doesn't cover the underlying model name — remember rules match the name the provider is called with, not the route name. Add a rule. > * **Not metered** — the provider's **Calculate token cost** setting is off. This is intentional; change the provider setting if it shouldn't be. > * A price is shown but it's `$0.00` — one of your rules sets zero prices and outranks the default. Edit or archive it. > [accordion] I changed a price but past costs didn't move > > Price changes are forward-looking. They affect requests after the new version is active; they don't re-cost past requests or change what's already counted against a budget. To correct a budget after a price fix, contact [support@barndoor.ai](mailto:support@barndoor.ai). > [accordion] A new price isn't being used yet > > The gateway picks up pricing changes within a few minutes. If you used **Schedule for later**, the price won't apply until the scheduled time — open the rule's history to confirm the **Scheduled** entry. > [accordion] I scheduled a price change but want to cancel it > > Open the rule's **Pricing History** (clock icon) and click the trash icon next to the scheduled entry. Only future versions can be cancelled. > [accordion] Two rules match the same model — which one wins? > > The higher [tier](#how-pricing-resolves) wins (Provider Instance, then Catalog, then Generic, then Barndoor default). Within a tier, the most specific pattern wins. Avoid two different patterns that are equally specific and both match the same model — there's no principled winner between them. > [accordion] Cached requests look more expensive than the provider's invoice > > The rule probably has no **Cache Read** price, so cached tokens are billed at the full input price. Set the cache read price in **Edit Pricing**. ## Frequently Asked Questions > [accordion] Do imported defaults follow provider price changes? > > That's your choice per rule: **Prompt me on updates** flags changes for review, **I'll manage it** never changes, and **Auto-sync to Barndoor** follows the default automatically. See [Keeping Prices in Sync](#keeping-prices-in-sync-with-barndoors-catalog). > [accordion] What currency is supported? > > **USD** only. All prices are entered, recorded, and reported in US dollars. > [accordion] Can I price the same model differently on different deployments? > > Yes — use a **Provider Instance** rule for each provider connection that needs its own price. Rules match the underlying model name, so two route names that reach the same model on the same provider share one price. > [accordion] What if my provider lists prices per 1,000 tokens? > > Multiply by 1,000. If your provider quotes `$0.0025 per 1K input tokens`, enter `2.50` as the input cost per million. > [accordion] Do I need a rule for embedding models? > > Only if Barndoor's catalog doesn't cover the model. For a custom or self-hosted embedding model, add a rule with the input price and leave output at `0` — embeddings consume input tokens only. > [accordion] Can I delete a pricing rule? > > Archive it instead. Archiving takes it out of use and keeps its history; you can restore it from the **Archive** tab. ## Need Help? Reach out to [support@barndoor.ai](mailto:support@barndoor.ai) with: * The model name (and provider) you're trying to price. * The pattern and prices you've configured (a screenshot of the row helps). * What you're seeing — `$0` cost, a budget not moving, an **Unpriced** label, and so on. # Managing Policies Source: https://docs.barndoor.ai/how-tos/manage-policies Step-by-step guide to validate, create, activate, update, clone, and audit policies with the v2 API. Barndoor policies define which MCP tools an agent can use and under what conditions. This guide walks through the full policy lifecycle with the v2 API, from drafting a policy to activating it, revising it, and reviewing its history. > [!NOTE] > > **Estimated Time**: 15-20 minutes ## Before You Begin Before getting started with policy management, you’ll need: * A Barndoor account with **admin privileges** * A valid bearer token for the Barndoor API * At least one registered MCP server * At least one registered agent or application Example shell setup: ```bash theme={null} export BASE_URL="https://your-org.platform.barndoor.ai" export TOKEN="your-jwt" export MCP_SERVER_ID="server_123" export APP_ID="agent_456" ``` > [!NOTE] > > The v2 policy API replaces the older policy-style wrapper. In v2, you send a single policy object directly to `/api/v2/policies`, use `application_ids` to scope the policy, and define each rule with `authorized`, `actions`, `roles_groups`, and optional `condition`. ## What You’ll Learn In this guide, you will: * Validate policy scope before creation * Create a policy in `DRAFT` * Grant a tool outright or subject to user approval * Review and activate the policy * Update rules and metadata safely * List, search, and summarize policies * Audit policy changes through revisions * Clone and retire policies as part of normal lifecycle management ## Step-by-Step Guide ### Step 1: Validate your policy before creating it Validate checks whether the policy name is unique and whether an active policy would overlap with the same MCP server and application scope. **Validation request example** ```bash theme={null} curl -X POST "$BASE_URL/api/v2/policies/validate" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Slack outbound policy", "mcp_server_id": "'"$MCP_SERVER_ID"'", "application_ids": ["'"$APP_ID"'"] }' ``` Typical response: ```json theme={null} { "name_is_unique": true, "no_overlap_if_active": true, "overlapping_policy_names": [] } ``` > [!TIP] > > Use `exclude_policy_id` when validating an update to an existing policy so the current record is ignored during overlap checks. Reference: [`POST /api/v2/policies/validate`](/api-reference/policies/validatePolicy) ### Step 2: Create the policy as a draft In v2, the request body is a single policy object. There is no `resourcePolicy` wrapper. **Draft policy payload example** ```bash theme={null} curl -X POST "$BASE_URL/api/v2/policies" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Slack outbound policy", "description": "Default outbound Slack controls for the support agent.", "support_contact": "platform@company.com", "tags": ["slack", "support"], "status": "DRAFT", "mcp_server_id": "'"$MCP_SERVER_ID"'", "application_ids": ["'"$APP_ID"'"], "rules": [ { "name": "allow_all", "authorized": true, "actions": ["*"], "roles_groups": ["*"] }, { "name": "block_general_channel", "authorized": false, "actions": ["tools/call:chat_postMessage"], "roles_groups": ["*"], "condition": { "match": { "all": { "of": [ { "expr": "request.resource.attr.channel == \"general\"" } ] } } } } ] }' ``` Important v2 fields: * `name`: Unique policy name within the organization * `mcp_server_id`: MCP server this policy controls * `application_ids`: Agents or applications this policy applies to * `status`: `DRAFT`, `ACTIVE`, `INACTIVE`, or `ARCHIVED` * `rules`: Array of policy rules Reference: [`POST /api/v2/policies`](/api-reference/policies/createPolicy) ### Step 3: Understand the v2 rule model Each rule in v2 uses a simpler structure than the older effect-based format. **Rule model details** * `authorized: true` means allow * `authorized: false` means deny * `actions` defines which MCP actions the rule applies to * `roles_groups` controls which role or group matchers apply * `condition` adds optional fine-grained logic Use `roles_groups: ["*"]` when a rule should apply to every user. To target a specific IdP group, use the exact group name that Barndoor receives from your IdP, for example `roles_groups: ["Finance"]`. > [!WARNING] > > Group-based policy rules only work after your IdP sends group membership to Barndoor during login. For OIDC IdPs, configure a `groups` claim in the ID token or UserInfo response and verify users have signed in again after the claim was added. Single-expression condition: ```json theme={null} { "condition": { "match": { "expr": "request.resource.attr.channel == \"general\"" } } } ``` Nested condition with `all`: ```json theme={null} { "condition": { "match": { "all": { "of": [ { "expr": "request.resource.attr.channel == \"general\"" }, { "expr": "request.principal.id == \"agent_456\"" } ] } } } } ``` ### Step 4: Require approval for a tool A rule can grant a tool outright or grant it **subject to user approval**. The difference is carried in the action string: append `:approve` to the tool call. This is the API-level view of the same three states the portal exposes per tool — see [Granular Tool Use Confirmations](/how-tos/tool-confirmations) for the UI walkthrough and the enforcement caveats. | Intent | Action string | | - | - | | Always Allow — runs without confirmation | `tools/call:create_issue` | | Needs Approval — user confirms before it runs | `tools/call:create_issue:approve` | | Off — not granted | omit the tool from the rule | > [!WARNING] > > Use **one** form per tool per rule, never both. `:approve` is the whole grant — a tool listed as `tools/call:create_issue:approve` is granted, with an approval gate attached. Listing the plain action alongside it makes the approval gate moot, because the plain grant already permits the call unconfirmed. The tri-state has no explicit deny form. "Off" is *absence* — a tool that no applicable rule grants is denied because nothing granted it, so turning a tool off means removing it from the rule rather than adding a rule against it. That is different from an `authorized: false` rule (Step 3), which serializes to a real deny and **overrides** any allow that would otherwise apply. Use `authorized: false` with a `condition` to carve a specific exception out of a grant; use omission to express "this group does not get this tool". **Rule with mixed always-allow and needs-approval tools** ```bash theme={null} curl -X POST "$BASE_URL/api/v2/policies" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Jira support policy", "description": "Reads run freely; writes need a human.", "status": "DRAFT", "mcp_server_id": "'"$MCP_SERVER_ID"'", "application_ids": ["'"$APP_ID"'"], "rules": [ { "name": "support_engineers", "authorized": true, "actions": [ "tools/call:search_issues", "tools/call:get_issue", "tools/call:create_issue:approve", "tools/call:update_issue:approve" ], "roles_groups": ["Support"] } ] }' ``` `search_issues` and `get_issue` run immediately. `create_issue` and `update_issue` return an approval request to the user first. `delete_issue` is absent, so the Support group cannot call it at all. > [!NOTE] > > The `:approve` suffix is reserved. It may appear at most once, at the end of a tool-call action — the API rejects a doubled `tools/call:X:approve:approve`. #### How overlapping grants resolve A user is usually in more than one group, and rules are evaluated together rather than in order. **The most permissive grant wins**, regardless of the order rules appear in: ``` Always Allow > Needs Approval > Off ``` > [!WARNING] > > This makes a broad grant capable of silencing a narrow one. If an unscoped rule (`roles_groups: ["*"]`) grants `tools/call:create_issue` plainly, then a group-scoped rule granting `tools/call:create_issue:approve` is **dormant** — those users are already allowed unconfirmed, so no approval fires. The narrower rule is not broken and does not need rewriting: remove or downgrade the broad grant and the approval requirement takes effect. Read the whole rule set, not just the rule you are editing, before concluding a tool is gated. The same resolution is what the app's policy detail view renders, so the UI and the API agree about a given tool's effective state. > [!WARNING] > > **Approval prompting happens through Barndoor's tool router only.** On the direct MCP path, a tool granted `tools/call:X:approve` is permitted and executes with no prompt — the approval ceremony lives in the tool router, not in the proxy. Treat `:approve` as a control for tool-router traffic; for a hard stop on every path, omit the tool instead. ### Step 5: Review the created policy Capture the returned `policy.id` from the create response, then fetch the full policy document. **Fetch a policy by ID** ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies/POLICY_ID" ``` Confirm the following before rollout: * The `status` is still `DRAFT` * The correct `application_ids` are attached * The `mcp_server_id` is correct * The returned `rules` match your intended behavior Reference: [`GET /api/v2/policies/{policy_id}`](/api-reference/policies/getPolicy) ### Step 6: Activate or update the policy Once reviewed, move the policy into `ACTIVE`. **Activation and update examples** ```bash theme={null} curl -X PATCH "$BASE_URL/api/v2/policies/POLICY_ID" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "status": "ACTIVE" }' ``` You can also update metadata and rules through the same endpoint: ```bash theme={null} curl -X PATCH "$BASE_URL/api/v2/policies/POLICY_ID" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "description": "Blocks posting to #general while allowing all other Slack tools.", "tags": ["slack", "support", "production"], "rules": [ { "name": "allow_all", "authorized": true, "actions": ["*"], "roles_groups": ["*"] }, { "name": "block_general_channel", "authorized": false, "actions": ["tools/call:chat_postMessage"], "roles_groups": ["*"], "condition": { "match": { "all": { "of": [ { "expr": "request.resource.attr.channel == \"general\"" } ] } } } } ] }' ``` Reference: [`PATCH /api/v2/policies/{policy_id}`](/api-reference/policies/updatePolicy) ### Step 7: List, search, and summarize policies List policies: **List and search examples** ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies?page=1&limit=20" ``` Search and filter: ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies?search=slack&status=ACTIVE&mcp_server_id=$MCP_SERVER_ID&agent_id=$APP_ID" ``` Get status counts: ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies/summary" ``` Get filter definitions for a UI: ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies/filter-definitions" ``` References: * [`GET /api/v2/policies`](/api-reference/policies/listPolicies) * [`GET /api/v2/policies/summary`](/api-reference/policies/getPoliciesSummary) * [`GET /api/v2/policies/filter-definitions`](/api-reference/policies/getFilterDefinitions) ### Step 8: Review revision history Every meaningful change is available through the revisions endpoint. **Revision history example** ```bash theme={null} curl -H "Authorization: Bearer $TOKEN" \ "$BASE_URL/api/v2/policies/POLICY_ID/revisions?changes_summary=true&page=1&limit=10" ``` Use revisions to: * Review what changed * See who changed it * Understand when the policy moved between lifecycle states Reference: [`GET /api/v2/policies/{policy_id}/revisions`](/api-reference/policies/listPolicyRevisions) ### Step 9: Clone, deactivate, or archive a policy Clone a policy to create a safe variation without rebuilding the rule set: **Clone and retirement examples** ```bash theme={null} curl -X POST "$BASE_URL/api/v2/policies/POLICY_ID/clone" \ -H "Authorization: Bearer $TOKEN" ``` The cloned policy should be reviewed and edited before activation. To retire a policy gradually, move it to `INACTIVE`: ```bash theme={null} curl -X PATCH "$BASE_URL/api/v2/policies/POLICY_ID" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "status": "INACTIVE" }' ``` To remove it from normal circulation, move it to `ARCHIVED`: ```bash theme={null} curl -X PATCH "$BASE_URL/api/v2/policies/POLICY_ID" \ -H "Authorization: Bearer $TOKEN" \ -H "Content-Type: application/json" \ -d '{ "status": "ARCHIVED" }' ``` References: * [`POST /api/v2/policies/{policy_id}/clone`](/api-reference/policies/clonePolicy) * [`PATCH /api/v2/policies/{policy_id}`](/api-reference/policies/updatePolicy) ## Legacy Endpoints The older engine-level toggles still exist: **Legacy endpoint references** * [`PUT /api/policy/enable`](/api-reference/policies/enablePolicy) * [`PUT /api/policy/disable`](/api-reference/policies/disablePolicy) * [`PUT /api/policies/restrictions/enable/{restriction_name}`](/api-reference/policies/enableRestriction) * [`PUT /api/policies/restrictions/disable/{restriction_name}`](/api-reference/policies/disableRestriction) > [!WARNING] > > For new policy lifecycle workflows, prefer the v2 endpoints and the `status` field. Use the legacy endpoints only when you explicitly need the older engine-level toggles. ## Best Practices * Create policies as `DRAFT` first, then promote to `ACTIVE` * Validate before both create and update operations * Keep `application_ids` narrow to avoid overlap with other active policies * Before relying on a `:approve` grant, check that no broader rule grants the same tool plainly — the plain grant wins and the approval never fires * Use descriptive tags and a `support_contact` so ownership is clear * Review revisions instead of maintaining a separate manual change log * Clone stable policies before making large behavior changes # MCP Change Management Source: https://docs.barndoor.ai/how-tos/mcp-change-management See every connected MCP server's tool inventory and version history, know which policies a change touches, and get alerted the moment a server's tools move. ## Overview MCP servers evolve — a tool's input schema gets a new required field, an output shape changes, a tool is renamed or removed. When that happens underneath a policy you've written, the policy can silently stop matching the tool it was meant to govern. MCP Change Management gives you visibility into exactly what changed on a connected server, which of your policies it touches, and an alert when it happens. ## How It Works Barndoor captures a **version** of each connected server's tool listing. A scheduled check runs once a day (02:00 UTC) against every connected server with a reachable upstream, and a new version is appended **only when something actually changed** — a check that finds nothing new records the check without creating a version. The same capture also happens outside the schedule. Each version records what triggered it: | Trigger | Meaning | | - | - | | **Scheduled check** | The daily sweep | | **Server connected** | A server was connected or reconnected | | **Manual refresh** | A refresh was forced | | **Config import** | Seeded from configuration rather than probed | | **Cache warm**, **Tool call miss**, **Lifecycle event**, **Backfill**, **Rollback** | Other system-initiated captures | > [!NOTE] > > Servers whose tools are **declared in configuration** rather than read from a running server — embedded and locally-deployed servers — have no upstream to probe, so the scheduled check skips them. Soft-deleted servers are skipped too. When a version is captured, Barndoor runs a **policy impact analysis** to identify which of your access policies reference an affected tool, so you can see not just what changed but what it touches. ## The Tool Data & History Page Open a server from **MCP Servers**, then choose **Tool data & history** from its settings menu. The page shows: * **Fetch status** — the server's **Source** (Barndoor, Official, or Custom) and the number of **Tools in latest version** * **Clocks** — **Last checked** (when a check last ran, whether or not anything changed), **Last changed** (when the current version was captured; never moves without a real content change), and **Last verified** (when upstream last confirmed the current content is still current — this moves on every successful check, including ones that found nothing new) * **Latest change · vN** — the newest version's change breakdown, with **View what changed** for the full delta * **Version history** — every captured version, newest first * **Current tools** — the tool listing stored at the newest version * **Impacts** — the access policies a detected change affects Use this page whenever you're about to write a new policy against a server, or when you get an alert that one changed, to see the current state before you act. > [!NOTE] > > There's no manual refresh control here on purpose. Reloading the page re-reads the stored versions; forcing a fresh upstream probe is a separate, heavier operation. History is retained 50 versions deep. ### What the status says The status on the fetch card distinguishes outcomes that are easy to conflate: | Status | Meaning | | - | - | | **Changes detected** | The last check succeeded and captured a new version | | **No changes detected** | The last check succeeded and found nothing new | | **Checked** | The last check succeeded; whether it captured a version wasn't recorded | | **Checking…** | A check is in progress | | **Awaiting approval** | A new version was captured and is waiting for approval before it's served | | **Checks paused** | Checks are paused for this server, so nothing was fetched | | **Never fetched** | No check has ever been attempted | | **Error** | The last check failed — see the error below | A failed check names what went wrong rather than just "error": **Credentials needed**, **Server unreachable**, **Timed out**, **Refused an empty listing**, or **Retries exhausted**. **Credentials needed** is the common one, and it distinguishes a server that has never had a usable credential (connect it) from one whose stored credential was rejected (reconnecting may be required). ### What "changed" means A change breakdown reports these categories: | Category | What moved | | - | - | | **Added** / **Removed** | Tools appearing or disappearing | | **Operation changed** | A tool's read/write classification | | **Input schema changed** | A tool's accepted arguments — your call sites | | **Output schema changed** | The shape of what a tool returns — your parsers | | **Annotations changed** | Safety hints such as read-only or destructive | | **Description changed** | A tool's documented purpose | | **Resources added** / **Resources removed** | Non-tool resources the server exposes | ## Reviewing Policy Impact An impact links one detected change to one policy that references the affected tool. Each carries a severity — **Breaking**, **Needs review**, or **Info** — and a status of **Open**, **Acknowledged**, or **Resolved**. Impacts appear in two places: as a severity badge beside each policy on the **Access Control Center** list, and as an **Impacts** section on a policy's detail view. Click **Acknowledge** on an impact once you've reviewed it. > [!WARNING] > > Acknowledging an impact records that you've seen it. It does **not** change the policy — updating rules to match the server's new tools is still yours to do. ## Getting Notified Subscribe to the **MCP server tooling changed** alert to hear about a change as it's detected, instead of finding out when you next open the portal. See [Notifications](/how-tos/notifications) to set up delivery to your in-app inbox, email, Slack, Microsoft Teams, or a webhook. > [!TIP] > > Pair this with a routine review of the Tool data & history page — the alert tells you *that* something changed; the page shows you exactly *what*, and which policies to check. ## FAQ > [accordion] Which MCP servers does the scheduled check cover? > > Connected servers with a reachable upstream — Barndoor-hosted, official, and custom remote servers. Servers whose tools are declared in configuration (embedded servers, and locally-deployed servers pushed via MDM) have nothing to probe and are skipped, as are servers with checks paused and servers that have been deleted. > [accordion] How often does the check run? > > Daily, at 02:00 UTC. Captures also happen when a server is connected, when a refresh is forced, and on a handful of other system events — so version history isn't strictly one row per day. Each version records which trigger produced it. > [accordion] Does a detected change automatically update or disable my policy? > > No. Policy impact analysis identifies which policies reference an affected tool so you can review and update them yourself — it doesn't change policy behavior automatically. > [accordion] Why does the version history have fewer entries than days of checks? > > Because a version is captured only when the tool listing actually moved. A check that finds nothing new advances **Last checked** and **Last verified** without appending a version — which is why those two clocks and **Last changed** are shown separately. > [accordion] Will I be notified even if I don't check the portal? > > Only if a channel is subscribed to the **MCP server tooling changed** alert under Notifications. Without a subscription, changes are visible on the Tool data & history page but won't be pushed to you. That alert is released progressively, so it may not be in your picker yet. ## In this section > [card] [Notifications](/how-tos/notifications) > > Subscribe to the MCP server tooling changed alert. > [card] [Managing Policies](/how-tos/manage-policies) > > Review and update the policies a tool change impacts. # Notifications Source: https://docs.barndoor.ai/how-tos/notifications Subscribe to the events you care about and get them delivered where you actually look — in-app, email, Slack, Microsoft Teams, or a webhook. ## Overview Barndoor's platform generates a steady stream of change events — a server's connection breaking, a policy changing, an LLM budget being exhausted, a connected MCP server's tools changing underneath your policies. Notifications lets you choose which of those alerts get delivered, and where: your in-app inbox, your email, or an organization-wide destination such as a Slack channel, a Microsoft Teams channel, a shared mailbox, or a webhook. > [!NOTE] > > **Estimated time**: 5–10 minutes per channel ## Before You Begin You'll need: * A Barndoor account with **admin privileges** to manage organization-wide channels. Any user can manage their own personal notification settings. * For Slack delivery: permission to authorize the Barndoor Slack app in your workspace * For Microsoft Teams delivery: permission to add a **Workflows** incoming webhook to the destination channel * For webhook delivery: a public HTTPS endpoint that can receive a POST request ## Two Places to Configure Notifications Barndoor separates *your* notifications from *your organization's* alert destinations, and they are managed on different pages. | Page | Scope | What lives there | | - | - | - | | **Settings → Notifications** | Just you | Your in-app inbox and your account email, plus the alert types each one delivers | | **Alert Channels** | The whole organization | Shared destinations — an email address, a webhook, a Slack channel, a Teams channel — each with its own alert types | > [!NOTE] > > There is no separate "subscription" object to create. A channel *is* the subscription: you add a destination, then turn on the alert types it should receive. ## Alert Types Alert types are grouped into categories, and each carries an intrinsic severity you can filter by when picking which ones a channel receives. | Category | Alert type | Severity | | - | - | - | | **MCP servers** | MCP server added | Info | | **MCP servers** | MCP server deleted | Info | | **MCP servers** | Connection broken | Warning | | **MCP servers** | MCP server tooling changed | Info | | **Access control** | Policy changed | Info | | **Access control** | Admin role change | Info | | **Access control** | Break-glass used | Critical | | **Usage & cost** | LLM threshold exceeded | Warning | | **Usage & cost** | LLM budget exhausted | Critical | | **LLM gateway** | LLM provider unavailable | Critical | | **LLM gateway** | LLM provider key rejected | Critical | | **LLM gateway** | LLM API key expiring | Warning | | **LLM gateway** | LLM API key expired | Critical | | **LLM gateway** | LLM API key revoked | Info | > [!NOTE] > > This list is enumerated by the platform, not hard-coded into the UI, so new alert types appear in the picker as they ship — no action needed to see them. Some alert types are released progressively and may not be visible to your organization yet; **MCP server tooling changed** (see [MCP Change Management](/how-tos/mcp-change-management)) is one of them. If a type isn't in your picker, it isn't available to your organization yet. > [!NOTE] > > **LLM API key expiring** fires when a key has 7 days left and again when it has 1 day left; **LLM API key expired** fires once after it lapses. See [Expiration Alerts](/how-tos/manage-llm-api-keys#expiration-alerts). > [!NOTE] > > **Connection broken** is scoped to the person whose connection failed. It's delivered to that user's own channels only — organization-wide channels never receive it, because a personal credential failure isn't an org-wide event. ## Delivery Channels Personal channels, on **Settings → Notifications**: * **In-app inbox** — the notification bell in the top bar * **Email** — sent to your account email address Organization-wide channels, on the **Alert Channels** page: * **Email** — an address you specify, such as a shared or on-call mailbox * **Slack** — posted to a channel by the Barndoor Slack app, which you authorize once per workspace * **Microsoft Teams** — posted into a channel as an Adaptive Card via a Teams **Workflows** incoming webhook * **Webhook** — a signed JSON payload POSTed to an HTTPS endpoint you control ## Add an Organization-Wide Channel 1. Sign in to your Barndoor portal and navigate to **Alert Channels**. 2. Click **Add channel**. 3. Choose the **Type** — Email, Slack, Microsoft Teams, or Webhook — and fill in its destination using the sections below. 4. Click **Create**. 5. Open the channel and, under **Subscriptions**, turn on the alert types it should receive. Filter by severity to focus the list. 6. Click **Test** to confirm delivery before you rely on it. > [!WARNING] > > A channel's destination is fixed once created. To point alerts somewhere else, delete the channel and add a new one. ## Setting Up Slack Delivery 1. In Barndoor, go to **Alert Channels → Add channel** and set **Type** to **Slack**. 2. Click **Connect Slack** and authorize the Barndoor Slack app for your workspace. You're returned to Barndoor with the Slack type preselected. 3. Pick the destination channel from the dropdown, then click **Create**. Slack delivery is a direct app integration, not an incoming webhook — there's no URL to copy or manage on the Slack side. > [!TIP] > > The dropdown only lists channels the Barndoor bot is in. If the channel you want is missing, invite the bot to it in Slack with `/invite @Barndoor`, then reopen the picker. ## Setting Up Microsoft Teams Delivery Teams delivery uses a **Workflows** incoming webhook — the same mechanism Microsoft now recommends in place of retired Office 365 connectors. The workflow URL is the credential, so treat it like a secret. 1. In Microsoft Teams, open the destination channel, click **•••**, and choose **Workflows**. 2. Select the **"Post to a channel when a webhook request is received"** template and complete it. Teams generates an `https://` URL. Copy it. (See Microsoft's [guide to incoming webhooks with Workflows](https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498).) 3. In Barndoor, go to **Alert Channels → Add channel**, set **Type** to **Microsoft Teams**, give the channel a **Label** you'll recognize, paste the URL into **Workflow URL**, and click **Create**. > [!NOTE] > > Alerts arrive as an Adaptive Card posted into the channel, so they persist in the conversation the way a Slack message does. Barndoor stores only the label and a fingerprint of the URL — the URL itself never comes back out of the API, which is why editing a Teams channel asks for it again. ## Setting Up Webhook Delivery 1. In Barndoor, go to **Alert Channels → Add channel** and set **Type** to **Webhook**. 2. Enter your endpoint as **Webhook URL**. It must be a public `https://` URL — localhost, private, and internal network addresses are rejected. 3. Click **Create**. Barndoor shows the **signing secret** once, at creation. Copy it then; it can't be retrieved later. > [!WARNING] > > Signing secrets are credentials — anyone holding one can forge a payload that looks like it came from Barndoor. Use **Regenerate secret** on the channel's page if you suspect a leak; the new secret is again shown only once, and the old one stops working immediately. ### Webhook Payload Barndoor follows the [Standard Webhooks](https://www.standardwebhooks.com/) specification. Each delivery POSTs a JSON body shaped like: ```json theme={null} { "type": "alert.mcp_server_tooling_changed", "timestamp": "2026-08-20T14:03:11.482913+00:00", "data": { "event_id": "01J9Z2QF7K8V3M4N5P6R7S8T9U", "severity": "info", "title": "Salesforce tools changed", "resource_name": "Salesforce", "occurred_at": "2026-08-20T14:03:11+00:00", "organization_id": "3f1c9e4b-7821-4a55-9d0e-6b2f8c1a7d34", "detail": {}, "link": "https://app.barndoor.ai/servers/…" } } ``` `type` is `alert.` followed by the alert type's identifier. `link` is present only when the alert has a destination in the portal. ### Verifying a Delivery Every request carries three headers: | Header | Contents | | - | - | | `webhook-id` | A unique id for this delivery, also used for idempotency | | `webhook-timestamp` | Unix seconds at send time | | `webhook-signature` | `v1,` followed by base64(HMAC-SHA256) over `{id}.{timestamp}.{body}`, keyed with your signing secret | > [!NOTE] > > The `detail` object's shape is specific to each alert type, and is the structured payload behind the alert — for **MCP server tooling changed**, it's the summary of what changed on the server. It never carries secrets, but it can carry your own tenant's resource names, so treat the endpoint as an egress point for your organization's data. ## Managing an Existing Channel Open a channel from the **Alert Channels** list to: * Toggle **Enabled** to stop and resume delivery without losing the channel's configuration * Change which alert types it receives, under **Subscriptions** * Send a **Test** message * **Regenerate secret** (webhook channels only) * **Delete channel** — the destination stops receiving alerts, and this can't be undone ## Your Own Notifications Go to **Settings → Notifications** to control what reaches you personally. Turn on **In-app inbox** or **Email**, then turn on the alert types each should deliver. Filtering by severity narrows the list you're looking at; it doesn't change what's already turned on. ## Managing Channels as Code > [!NOTE] > > **Coming soon**: a `barndoor_notification_channel` Terraform resource is planned, so webhook, Slack, Teams, and email channels can be declared and version-controlled the same way you already manage MCP servers and policies. Channels are configured in the portal for now — this page will be updated with a Terraform example once that resource ships. ## FAQ > [accordion] Can different people get different alerts? > > Yes, two ways. Each user controls their own in-app and email delivery under **Settings → Notifications**. For teams, add an organization-wide channel per destination — an on-call mailbox, a Slack channel per squad — and give each its own set of alert types. > [accordion] Is there a delay between an event happening and the notification arriving? > > In-app and webhook deliveries are near-real-time. Email, Slack, and Teams delivery depend on the destination service but are typically seconds behind the event. > [accordion] Can I pause a channel temporarily instead of deleting it? > > Yes — toggle **Enabled** off on the channel's page. Its alert-type selections are preserved, and turning it back on resumes delivery. > [accordion] Why don't I see the Notifications or Alert Channels pages? > > Both are released progressively. If they aren't in your sidebar yet, they haven't been enabled for your organization — contact support to ask about availability. **Alert Channels** additionally requires an admin role. > [accordion] A test message worked, but real alerts never arrive. > > Check three things: the channel is **Enabled**, the alert type you expect is turned on under **Subscriptions**, and the alert type is one your organization actually receives. **Test** exercises the transport, not your subscriptions, so it succeeds even when no alert type is selected. ## In this section > [card] [MCP Change Management](/how-tos/mcp-change-management) > > See what's driving the MCP server tooling changed alert. > [card] [Granular Tool Use Confirmations](/how-tos/tool-confirmations) > > Require human approval before an agent's tool call runs. # Connect Okta as your IdP Source: https://docs.barndoor.ai/how-tos/okta-oin-setup Configure Barndoor SSO using the official OIN app with SCIM provisioning ## Overview The Barndoor OIN app provides the easiest setup experience with built-in SCIM provisioning for automated user lifecycle management. This method offers: * Pre-configured OIDC settings * Automated user provisioning and deprovisioning * Automated group provisioning and group membership synchronization * Official Okta Verified integration path *** ## Supported features The Barndoor OIN integration supports the following Okta features. ### OIDC * **SP-initiated SSO** — Single Sign-On initiated from Barndoor * **IdP-initiated SSO** — Single Sign-On initiated from the Okta dashboard (through Third-Party Initiated Login) * **Just-In-Time provisioning** — Accounts are created and updated in Barndoor at first sign-in ### SCIM provisioning * **Create users** — Provision new users to Barndoor * **Update user attributes** — Sync user attribute changes from Okta to Barndoor * **Deactivate users** — Deprovision users in Barndoor when they are unassigned or deactivated in Okta * **Group Push** — Push Okta groups and their memberships to Barndoor *** > [!NOTE] > > **Prerequisites**: > > * Admin access to your Barndoor account > * Admin access to your Okta org > * SCIM token from Barndoor (generated during setup) *** ## Step 1: Add Barndoor from OIN **1. Navigate to Okta Applications** In the Okta Admin Console, go to **Applications** → **Applications**. **2. Browse App Catalog** Click **Browse App Catalog** and search for **"Barndoor.ai"**. **3. Add Integration** Click on the Barndoor app and then click **Add Integration**. **4. Configure Application Settings** Add your Application Label and Organization alias. This can be found in the platform on your user profile information. In the example below, `oin-app-testing` is the organization alias. ![OIN App Configuration](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-app-config.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=1be6b865afa0fd12a97791efded40ce6) ![Organization Alias Location](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/organization-alias-location.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=9486c0217637317526789aa5b302a3e3) *** ## Step 2: Configure SSO Settings **1. Open SSO Configuration** In your newly added Barndoor app, go to the **Sign On** tab. **2. Note OIDC Settings** The OIN app comes pre-configured with: * Client ID (auto-generated) * Client Secret (auto-generated) * Issuer URL (your Okta domain) You'll need these values to configure the IDP connection within Barndoor. Copy the Issuer URL along with the Client ID and Client Secret to the Identity Provider section within Barndoor and then save the connection details. > [!NOTE] > > Your OIDC metadata can be found at `https://.okta.com/.well-known/openid-configuration` ![OIN Sign-On Configuration](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-signon-config.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=8c662491e8affdbc446cb874bfc76877) ![Barndoor OIDC Config](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/barndoor-oidc-config.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=3365471a610c6c66cd3f0debb0220bcf) *** ## Step 3: Configure SCIM Provisioning **1. Enable SCIM Provisioning** Go to the **Provisioning** tab and click **Integration** in the sidebar. **2. Enable API Integration** Check **Enable API integration** and enter: * **API Token**: Generate this from Barndoor Settings → SCIM Provisioning -> API Token ![Barndoor SCIM API Token](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/barndoor-scim-api-token.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=ce9726c0fa312763d091d3f95afc017a) **3. Test Connection** Click **Test API Credentials** to verify the connection. ✅ **Expected result**: "API credentials verified successfully" ![OIN SCIM API Token Success](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-scim-api-token-success.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=574c4279af29576dd069641995f9eb47) **4. Enable User Provisioning to App** Go to the **Provisioning** tab and click **To App** in the sidebar. * Enable the lifecycle settings you would wish to synchronize to Barndoor. It is recommended to enable all operations. ![OIN SCIM To App](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-scim-to-app.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=3460c54f88e19d3a37609b799904a9e7) *** ## Step 4: Assign Users and Groups **1. Go to Assignments** Navigate to the **Assignments** tab in your Barndoor app. **2. Assign Users** Click **Assign** and choose either: * **Assign to People**: Select individual users * **Assign to Groups**: Select entire Okta groups (recommended) **3. Configure User Attributes** Review and confirm the attribute mappings for each assigned user. **4. Save Assignments** Click **Save and Go Back** to complete assignments. > [!NOTE] > > Users will be automatically provisioned in Barndoor within a few minutes. ![OIN SCIM User Assignment](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-scim-user-assignment.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=bedc92b3dc03b4b8b417032d0fa5f9eb) **5. Assign Groups** Navigate to the **Push Groups** tab in your Barndoor app. * Click **Push Groups** and search for groups by name or rule. * Search for the group you would like to sync and click 'Save' or 'Save and Add Another'. * Continue adding all groups you would like to synchronize with Barndoor. > [!NOTE] > > All groups added to 'Push Groups' will synchronize with Barndoor but group membership will only synchronize to > users that have been assigned to the application. ![OIN SCIM Group Assignment](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/oin-scim-group-assignment.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=a3f015ef5adf4c212d33dc4b0d4dfd70) *** ## Map admin access (optional) SCIM group push keeps users and group membership in sync in Barndoor. To auto-assign the **Admin** role from an Okta group at login, use the **Map groups to roles** card on the [Identity Provider](https://app.barndoor.ai/idp) page—the **Admin Role Group Name** must match the group you push in Step 4 exactly. See [Connect your IdP — Step 3: Configure Role Mapping](/how-tos/idp-setup#step-3-configure-role-mapping-auto-provision-admins) for the full flow, including the OIDC `groups` claim if your OIN app does not already emit group names at sign-in. *** ## Testing the Integration ### Verify SSO Connection **1. Confirm SSO sign-in works** Sign out of Barndoor and sign in with an Okta-assigned test user. You should reach Barndoor after Okta authentication. ![Barndoor SSO Success](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/barndoor-sso-success.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=1f6f1f75ae5a4ea58edf8ab563d047a0) **2. Run the enforcement preflight (recommended)** Before enforcing organization-wide SSO, run **Test SSO sign-in** from [Roll out SSO enforcement](#roll-out-sso-enforcement) below. Barndoor requires that pop-up test—not just a manual login—before **Enforce SSO** is enabled. ### Verify SCIM Provisioning **1. Assign Users** In Okta, assign user(s) to the Barndoor application by either individual users or groups. **2. Verify user provisioned in Barndoor** In Barndoor, go to [**Users**](https://app.barndoor.ai/users) and verify the user appears. **3. Push Groups** In Okta, assign group(s) to the Barndoor application by pushing groups by name or rule. * Push groups for users that are already assigned to the application. * In Okta, verify groups pushed have transitioned from 'Pushing' to 'Activated' **4. Verify user groups provisioned in Barndoor** In Barndoor, go to [**Users**](https://app.barndoor.ai/users) and verify the users previously provisioned now show their pushed group memberships. ![Barndoor SSO Success](https://mintcdn.com/barndoor/K5EAwxC6tMHpdKua/images/okta/barndoor-scim-provisioning-success.png?fit=max\&auto=format\&n=K5EAwxC6tMHpdKua\&q=85\&s=49291f069af010dcba60b18468297cab) *** ## Roll out SSO enforcement After your IdP connection is saved and SSO sign-in works, the **Roll out SSO enforcement** section on the [Identity Provider](https://app.barndoor.ai/idp) page lets you require SSO for every member of your organization. Until you enforce SSO, users can still sign in with Barndoor passwords in addition to your IdP. > [!NOTE] > > If you don't see **Roll out SSO enforcement** controls on the Identity Provider page, organization-wide SSO enforcement may not be enabled for your workspace yet. Contact your Barndoor account team. > [!WARNING] > > **Enforcing SSO is irreversible in production.** It permanently clears Barndoor passwords for all members, terminates every active session (including yours), and requires all future logins through your IdP—except the dedicated break-glass account described below. ### What changes when you enforce SSO When you confirm enforcement, Barndoor: * Requires all organization members to sign in through your IdP * Permanently clears saved Barndoor passwords for every member * Leaves password sign-in enabled **only** for the break-glass admin email you configure * Terminates all active sessions, including the administrator who enabled enforcement After enforcement succeeds, sign out and sign back in through your IdP to continue working as an administrator. ### Prerequisites Both items in **Before you can enforce SSO** must be complete before **Enforce SSO** is enabled: **1. Test SSO sign-in** Click **Test SSO sign-in**. Barndoor opens a pop-up window and runs the full IdP login path—not just a connection preflight. Complete authentication in the pop-up. When the test succeeds, the row is marked complete. You can run the test again anytime to confirm sign-in still works. > [!TIP] > > If the pop-up is blocked, allow pop-ups for the Barndoor site and run the test again. **2. Configure break-glass admin email** Click **Manage** on the **Break-glass admin email** row and set an emergency mailbox your security or platform team can use if your IdP is unavailable. * The address must use your organization's IdP email domain (shown as `@your-domain` in the dialog) * It must **not** already belong to an existing Barndoor user * You **cannot** use your own administrator email as the break-glass account Click **Save**. Barndoor stores the address as the configured break-glass email. The dedicated break-glass user account is created when you enforce SSO. ### Enable organization-wide SSO **1. Review the rollout card** When both prerequisites are complete, click **Enforce SSO** at the bottom of the rollout card. **2. Acknowledge each consequence** In the confirmation dialog, check every acknowledgement: * Future logins will be exclusively via IdP SSO * All Barndoor passwords will be permanently cleared * Only your break-glass email will be able to sign in via password going forward * All active sessions—including your current one—will be terminated The dialog also shows your IdP connection name and redirect URI for a final sanity check. **3. Confirm enforcement** Click **Confirm Enforcement**. On success, Barndoor shows **SSO enforcement is active** and prompts you to **Sign out and sign in with SSO**. > [!NOTE] > > If enforcement succeeds but Barndoor shows a warning that not all member passwords were cleared or sessions could not be terminated, SSO enforcement is still active. Sign out and sign in again with SSO, verify member access, and contact support if the warning persists. > [!TIP] > > SSO enforcement is active. All organization members must sign in through your Identity Provider. Password login is disabled for everyone except the break-glass account. ### Set up the break-glass account When enforcement completes, Barndoor provisions a dedicated **Barndoor Break Glass** administrator account at the email you configured and sends a setup email to that mailbox. The recipient must: 1. Open the setup email and follow the link to set a password 2. At first sign-in, complete the email one-time passcode (OTP) sent to that mailbox—the same second factor used during an IdP outage Store break-glass credentials in your organization's secure emergency-access process (for example, a sealed envelope or privileged-access vault)—not in shared chat or email threads. ### Manage break-glass access after enforcement After SSO is enforced, the rollout card shows **SSO enforcement** as active and lets you manage the break-glass email: * **Resend invite** — If the break-glass account has not finished password setup, resend the setup email from the break-glass dialog * **Change break-glass email** — Opens a destructive change flow. Enter the new address, check the acknowledgement that the current account will lose password sign-in, then click **Save**. The new mailbox must complete password and OTP setup before it can be used > [!WARNING] > > Changing the break-glass email while SSO is enforced removes the previous break-glass account's password credentials and requires the new mailbox to complete setup from scratch. ### Sign in with break-glass during an IdP outage If your IdP is unavailable and you need emergency administrator access: 1. On the Barndoor sign-in page, choose password sign-in (not SSO) 2. Enter the break-glass email address and password 3. Complete the email one-time passcode sent to that mailbox Password sign-in and email OTP at login are available **only** for the break-glass account once SSO is enforced. All other members must use IdP SSO. ### Remove the SSO connection (optional) To disconnect IdP integration before or after enforcement, open the **actions menu** (⋯) on the rollout card and choose **Remove SSO**. Confirm when prompted. > [!WARNING] > > Removing the SSO connection immediately revokes IdP-based access for your organization. Only users who can still authenticate with a Barndoor password—including the break-glass account, if configured—can sign in. SSO enforcement remains on for the organization; re-connecting an IdP does not restore member password login. ### SSO enforcement troubleshooting > [accordion] Test SSO sign-in pop-up blocked or closes early > > **Common causes:** > > * Browser blocked pop-ups for the Barndoor site > * The sign-in window was closed before authentication finished > > **Solution:** Allow pop-ups for your Barndoor portal origin, then click **Test SSO sign-in** again. If the test times out, cancel and retry. > [accordion] Break-glass email rejected on Save > > **Common causes:** > > * Address is outside your organization's IdP email domain > * Address already belongs to an existing Barndoor user > * You entered your own administrator email > > **Solution:** Use a dedicated emergency mailbox on your IdP domain that is not yet a Barndoor user. Enter only the part before `@`—the domain is shown in the dialog. > [accordion] Break-glass setup email not received > > **Solution:** From the break-glass **Manage** dialog after enforcement, click **Resend invite**. Check spam filters and confirm the mailbox is monitored. The recipient must complete password setup from the link before the account can sign in. > [accordion] Enforcement succeeded with a warning > > **Cause:** SSO enforcement is active, but Barndoor could not clear every member password or terminate every session. > > **Solution:** Sign out and sign back in with SSO. Verify affected members can still reach the app through your IdP. Contact Barndoor support if the warning remains or members report unexpected password login. *** ## Troubleshooting > [accordion] SSO Login Fails > > **Common causes:** > > * Incorrect Client ID or Secret > * Incorrect organization alias > * User is not assigned to application > > **Solution**: > > * Verify OIDC credentials in both systems > * Confirm organization alias is correct > * Check user logging in is assigned to the Barndoor application > [accordion] SCIM Connection Fails > > **Common causes:** > > * Invalid or expired SCIM token > > **Solution**: > > * Generate a new SCIM token in Barndoor > [accordion] Users Not Provisioning > > **Common causes:** > > * Provisioning not enabled in Okta > * Users not assigned to the application > * Attribute mapping conflicts > > **Solution**: > > * Verify "Create Users" is enabled in Provisioning settings > * Check user assignments in the Assignments tab > * Review attribute mappings for required fields > [accordion] Groups Not Syncing > > **Common causes:** > > * Group push not configured > * Group already exists with different ID > > **Solution**: > > * Enable "Push Groups" in Provisioning settings > * Deactivate the group and re-add it to trigger reprovisioning *** ## Best Practices > [card] Use Groups for Assignment > > Assign Okta groups rather than individual users for easier management. > [card] Test Before Production > > Always test with a small group before rolling out to all users. > [card] Monitor Provisioning Logs > > Regularly check Okta's provisioning logs for any sync issues. > [card] Secure SCIM Tokens > > Rotate SCIM tokens periodically and store them securely. *** ## Summary You've successfully configured the Okta integration with Barndoor using the Okta Integration Network! This enables SSO and SCIM provisioning for your organization. > [!TIP] > > **Centralized authentication** - Users sign in with their Okta credentials > [!TIP] > > **Automated user lifecycle management** - Users are managed automatically > [!TIP] > > **Real-time group synchronization** - Membership changes take effect immediately > [!TIP] > > **Reduced manual work** - No need to manually provision users in Barndoor > [!TIP] > > **(Optional) Admin role mapping and organization-wide SSO enforcement** - See sections above *** # Reading the Dashboard Source: https://docs.barndoor.ai/how-tos/read-dashboard What the counts, policy decision totals and top-activity tables on the Barndoor home Dashboard measure, and where they differ from the usage dashboards. The **Dashboard** (first item in the sidebar) is the admin home page: headline counts for your organization, policy decisions over time, and the most active users, AI agents, MCP servers and tools. This page defines what each figure counts. The Dashboard reports MCP activity and policy decisions. It has no token or cost figures — for LLM Gateway traffic, use the [LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard), and for MCP call volume, duration and errors, the [MCP Usage Dashboard](/how-tos/read-mcp-usage-dashboard). ## The time period The selector in the top right — **Last 24 Hours**, **Last 7 Days**, **Last 30 Days** (the default), **Last 90 Days**, **Last 6 Months** or **Last 12 Months** — sets the window for everything below the three count cards. Each window is rolling and ends at the current time. Unlike the usage dashboards, the Dashboard groups activity into hours, days and months in **your browser's timezone**, so two admins in different timezones can see different per-day figures for the same window. ## The count cards | Card | What it counts | | - | - | | **AI Agents** | AI agents registered in your organization | | **MCP Servers** | Active MCP servers that you can manage policies for | | **Users** | Users in your organization | > [!NOTE] > > These are current totals, not activity. They don't change with the time period, and a server or agent with no traffic still counts. Each card links to its list page. ## Monitored Actions Policy decisions over the window, with three cards above a line chart: | Card | What it counts | | - | - | | **Total Policy Decisions** | Every policy decision recorded in the window | | **Allowed Requests** | Decisions that allowed the call, including calls that needed approval | | **Denied Requests** | Decisions that denied the call | These count **policy decisions, not completed tool calls**. A call that was allowed and then failed on the MCP server still counts as allowed, and a call that needed approval counts as allowed whether or not anyone approved it. Beneath each count is a rate and a comparison, for example `2 / day • 40 in previous 30 days (↑ 50%)`: * **The rate divides by the number of periods that had activity**, not by the length of the window. A 30-day window with activity on only 10 days divides by 10, so the rate reads as "per active day". The unit is hours for **Last 24 Hours**, months for **Last 6 Months** and **Last 12 Months**, and days otherwise. * **The comparison** is against the window of the same length immediately before this one. Selecting a card opens **Audit History** filtered to those decisions over the same window. ## Top Users The ten most active users in the window, with two columns: | Column | What it counts | | - | - | | **Actions** | Audit events recorded for the user on currently active MCP servers | | **MCP Servers Used** | How many of those servers the user was active on, shown as "*n* of *total*" against the **MCP Servers** card | **Actions counts audit events, not tool calls.** A single tool call records more than one event — the policy decision and the call itself, for example — so a user's Actions is typically higher than their number of tool calls. Only servers that are currently active count. Activity on a server that has since been deleted or deactivated is left out of both columns, which keeps **MCP Servers Used** from exceeding the total. Selecting a row opens **Audit History** for that user over the same window. ## Top Usage The five most active **AI Agents** and the five most active **MCP Servers** in the window, each ranked by **Actions** — audit events, as in Top Users. Activity with no recorded agent or server name is left out. Unlike Top Users, this card isn't limited to currently active servers, so a server removed during the window can still appear. ## Tool Calls The ten busiest tools in the window, one row per MCP server and tool: | Column | What it shows | | - | - | | **Type** | **Read**, **Write** or **Unknown** | | **Total Calls** | Policy decisions for the tool | | **Allowed** | Decisions that allowed the call, including calls that needed approval | | **Blocked** | Decisions that denied the call | Like Monitored Actions, the counts are policy decisions. Decisions made by Data Control Center runtime policies are left out. **Type** comes from the tool's own metadata when Barndoor has it. Otherwise it's inferred from the tool's name — names starting with verbs like *create*, *update*, *delete* or *send* read as **Write**, and *get*, *list*, *search* or *fetch* as **Read**. Anything else shows **Unknown** rather than guessing. ## Frequently asked > [accordion] Why is a user's Actions count much higher than the calls they made? > > Actions counts audit events, and a tool call usually records more than one. Use **Top Users** to compare users against each other, and the [MCP Usage Dashboard](/how-tos/read-mcp-usage-dashboard) — grouped by **User** — for call counts. > [accordion] Why does the '/ day' rate look too high? > > It divides by days that had activity, not by every day in the window. A burst of activity on a few days produces a high per-day rate even over a long window. > [accordion] Why don't these numbers match the MCP Usage Dashboard? > > The two count different things. The MCP Usage Dashboard counts MCP messages proxied through the gateway; the Dashboard counts policy decisions (Monitored Actions, Tool Calls) and audit events (Top Users, Top Usage). The Dashboard also groups by your browser's timezone, while the MCP Usage Dashboard defaults to UTC. # Reading the LLM Usage Dashboard Source: https://docs.barndoor.ai/how-tos/read-llm-usage-dashboard What each metric on the LLM Usage Dashboard measures — requests, tokens, estimated cost, duration, errors and failovers — and how to read the trends, errors, resilience, caching, by-period and breakdown tabs. The LLM Usage Dashboard (**Reporting → LLM Usage Dashboard**) reports requests, tokens, estimated cost, duration, errors and failovers for traffic through your LLM Gateway. This page defines what each figure counts, so the numbers can be read — and reconciled against a provider invoice — without guessing. The dashboard is available to organization admins. It opens on the **Last 7 days**, covering all organization traffic, on the **Trends** tab. ## Choosing the window and scope Everything on the page — the summary cards, every chart and every table — follows the same time window and the same scope filters. ### Time window The date button in the header shows the active window and the timezone it's expressed in. Open it to pick a preset (**Last 1 hour** through **Last 30 days**, or **Today**, **Yesterday**, **Week to date**, **Month to date**, **Last month**) or drag a custom range on the calendar. The arrows either side step the window back or forward by its own width. * **Rolling presets end at "now"** and move forward each time the page refreshes. Stepping the window, or picking dates on the calendar, pins it to fixed start and end times instead. * **Picking days on the calendar selects whole days**, in the active timezone. Future days can't be selected. * **The window is part of the URL**, so copying the address shares the exact view. A rolling preset stays rolling for whoever opens the link. **Refresh** re-fetches the data; **Auto** repeats that every 10 seconds until switched off. ### Timezone **The dashboard uses UTC by default.** Switch between **UTC** and **Local** (your browser's timezone) at the bottom of the date picker. The choice decides where each day, week and month starts, so it changes which period a request lands in — and therefore the per-period figures — but never the window's totals for the same start and end times. > [!NOTE] > > Keep UTC when comparing against provider invoices, which are almost always denominated in UTC days and months. **Reset** in the date picker restores the default window, granularity and timezone. ### Granularity The **Hourly / Daily / Weekly** selector sets the length of each period on the charts and in the By period table. It follows the window unless you change it: hourly up to two days, daily up to 90 days, weekly beyond that. Options that would be unreadable for the window are greyed out — hourly over more than eight days, daily under six hours, weekly under 14 days. Weeks start on Monday. ### Scope filters Two independent filters narrow the whole dashboard. Each is optional, and when both are set they combine — **By Group** "Platform" together with **By Provider** "anthropic" shows only that group's Anthropic traffic. | Filter | Options | Notes | | - | - | - | | **Who** | **All Organization**, **By User**, **By Group**, **By Role**, **By AI Agent**, **By API Key** | **By Group** covers the group's members plus API keys assigned to the group rather than a user. **By Role** covers users only. | | **What** | **All Models**, **By Provider**, **By Model**, **By Upstream Model**, **By Credential** | The value list offers only values that appear in the current window (and in the **Who** scope, if set). | Picking a dimension without a value leaves that filter off, so the dashboard never goes blank mid-selection. > [!NOTE] > > **By AI Agent** matches the agent recorded on each request at the time it was made — not the agent's currently bound keys — so an agent's history doesn't change when keys are unbound or rebound. It only appears once API keys can be bound to AI agents in your organization; this may not be enabled for your organization yet — contact Barndoor. ## The summary cards Seven cards sit at the top, reflecting the selected window and scope. ![The seven LLM Usage Dashboard summary cards: Requests, Tokens Used, Est. Cost, Avg Duration, Active Users, Error Rate, and Failovers](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-usage/01-summary-cards.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=a1f965e50ac6978e30959a2f7473dac8) | Card | What it counts | | - | - | | **Requests** | Every completed request — successful, failed, or blocked by the gateway | | **Tokens Used** | Input + output + cache read + cache write tokens | | **Est. Cost** | Cost recorded on each request, from your model pricing at the time | | **Avg Duration** | Average time per request, as measured at the gateway | | **Active Users** | Users active in the busiest single period | | **Error Rate** | Share of requests that failed or were blocked, with the raw count beneath | | **Failovers** | Failed provider attempts that the gateway retried on another route, with the requests that were recovered beneath | > [!NOTE] > > **Active Users** is a peak, not a total. It reports the highest distinct-user count seen in any one period, so a window where ten users were each active on a different day shows the busiest day's count rather than ten. Changing the granularity changes it. ### Requests One row per request that reached an outcome: **success**, **error**, or **denied** (blocked by a budget or rate limit, for example). Blocked requests count here even though they never reached a provider. Two kinds of traffic count as requests that you might not expect: * **Routing policy decisions.** When a routing policy uses a model call to pick the route, that call is recorded as a separate request under the same user and key, so one routed user request can add two to **Requests**. Group the Breakdown tab by **Routing Role** to separate them. * **Routing policy previews.** Each preview an admin runs from the routing policy editor is recorded as a request under that admin, with no API key. A failover is **not** counted twice: a request that failed on one route and succeeded on the next is one request. The failed attempt is counted in **Failovers** instead. ### Tokens Used **Fresh input tokens + output tokens + cache read tokens + cache write tokens.** This is the same basis the cost is computed from, so dividing **Est. Cost** by **Tokens Used** gives a sensible blended rate. * **Input tokens never include cached tokens**, for any provider. Cache reads and cache writes are counted separately and added on top. * **Reasoning tokens are already inside output tokens.** Models that "think" before answering bill that thinking as output, and the gateway counts it there. There is no separate reasoning figure on the dashboard, and nothing to add. * **Blocked and most failed requests contribute no tokens**, since no model produced a response. ### Est. Cost **The sum of the cost recorded on each request when it was served**, using the pricing rule that applied at that moment. It covers input, output, cache read and cache write cost — including any long-context surcharge on the matching rule. The figure is *estimated* because it comes from your pricing rules in Barndoor, not from the provider's bill. If your rules match your contract, it should track the invoice closely. Some requests record **\$0.00**: * **Unpriced models** — no pricing rule and no Barndoor default covers the model. The request succeeds, but no cost is recorded. * **Providers with Calculate token cost turned off** — for example a provider billed on a flat subscription. Their tokens are still counted, but cost is recorded as \$0 by design. * **Blocked requests**, which never reach a provider. > [!WARNING] > > Cost is fixed when the request is served. Changing a price, or a provider's **Calculate token cost** setting, affects only later requests — the dashboard never re-costs history. See [Managing Model Pricing](/how-tos/manage-model-pricing). If a pricing rule sets no cache rate, cache tokens are costed at the model's normal input rate. ### Avg Duration **The time the gateway spent on each request**, most of which is time waiting on the upstream provider. It is the whole call's wall-clock — not the overhead Barndoor adds, and not a number to subtract from anything. Blocked requests, and requests rejected before reaching a provider (for example, an unknown model name), have no duration and are left out. The card averages every request in the window that has a duration, so a busy hour carries more weight than a quiet one and the figure stays the same when you change the granularity. The **Avg Duration Over Time** chart shows each period's own average, which helps you see when it changed. It's a mean, not a percentile. Long generations and large prompts take longer by nature, so a shift in the models or workloads behind the traffic moves it too — scope the dashboard to one model to compare like with like. ### Error Rate Requests with an error **plus** requests blocked by the gateway, as a share of **Requests**. The count beneath the percentage covers both. A spike is not necessarily a broken provider — it may be a budget or rate limit correctly denying traffic. The **Errors** tab separates the two: each error is attributed either to the **Gateway** (Barndoor's own limits and rejections) or to the **Provider**. ### Failovers **Failed provider attempts that the gateway retried on another route**, plus, beneath, the number of **requests recovered** that way. This is separate from **Requests** and **Error Rate**. A provider can be failing badly here while users see no errors, because failover absorbed the failures. The **Resilience** tab shows the detail. See [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns). ## The tabs ### Trends Six charts, one value per period: * **Requests Over Time** * **Tokens Used Over Time** — stacked into input and output, plus cache read and cache write when the window used prompt caching * **Estimated Cost Over Time** — split the same way * **Avg Duration Over Time** * **Active Users Over Time** — distinct users in each period * **Avg Requests per User** — requests ÷ active users in each period ### Throughput **Peak Requests / min** and **Peak Tokens / min**: the busiest single minute inside each period. Use them to size requests-per-minute and tokens-per-minute [rate limits](/how-tos/use-llm-controls) against real bursts, which an hourly or daily average hides. > [!NOTE] > > Peak Tokens / min counts each request's total as the provider reported it. For some providers that total leaves out cached input tokens, so it isn't on exactly the same basis as **Tokens Used**. ### Errors Three charts: * **Error Count by Status Code** — failed requests stacked by HTTP status and who issued it, for example `429 Rate limited · Gateway` versus `429 Rate limited · Provider`. A 429 from the gateway means one of your rate limits fired; a 429 from the provider means the provider throttled you. * **Error Count by Model** — failed requests stacked by the model the caller asked for. * **Error Rate (%)** — errors as a share of requests in each period. The stacked charts show the ten largest series in the window. On low traffic the count and the rate can disagree — a handful of errors is a low count but a high rate. That is expected, and the rate is usually the one to act on. ### Resilience Retry and failover activity, kept apart from the request figures on every other tab: * **Provider Failures That Triggered Failover** — failed attempts, stacked by the provider that failed. * **Requests Recovered by Failover vs Failed on All Routes** — of the requests that hit a failure, how many succeeded on a later route and how many ran out of routes and returned an error. * **429 Retries Absorbed Within a Route** — rate-limit (429) responses the gateway retried on the same route instead of failing over or returning the error to the caller. ### Caching This tab only appears when some request in the window used prompt caching. Cache reads (billed at a discount) and cache writes (billed at a premium) are always kept separate, because they move cost in opposite directions. | Card | What it counts | | - | - | | **Cache Hit Rate** | Cache reads ÷ (cache reads + fresh input tokens). Cache writes are not counted. | | **Cache Savings** | What the cached tokens would have cost as fresh input, at the window's average input rate, minus what they actually cost | | **Cache Reads** | Tokens served from the cache, with their cost | | **Cache Writes** | Tokens written into the cache, with their cost | **Cache Savings can be negative.** Writing to the cache costs more than fresh input, so a workload that writes a lot and reads little back pays more with caching than without it. The card shows "—" when the window has no fresh input cost to compare against. Beneath the cards, **Cache Hit Rate Over Time**, **Cache Tokens Over Time** and **Cache Cost Over Time** show whether reuse is improving or decaying. ### By period One row per period — hourly, daily or weekly, chosen from the **Usage by** dropdown — newest first, with requests, input tokens, output tokens, cache read and cache write (when used), **Total tokens**, **Est. cost**, errors and error rate. Totals for the window match the summary cards. * **Quiet periods are hidden by default.** The line above the table says how many are held back ("5 of 7 days with activity"); clear **Hide quiet days** to show them as zero rows. * **Expanding a row** breaks that single period down along the dimension set in **Expand to**, so you can go from "Tuesday was expensive" to "Tuesday was expensive on this model" without changing the window. * **The first and last periods of a window are usually partial.** A **Last 7 days** window starts at the current time of day seven days ago, so its first daily row covers only part of that day. **Export CSV** downloads exactly the rows and columns on screen, with plain numbers a spreadsheet can sum. The first line records the window and timezone, and the filename carries both, for example `llm-usage-by-period-2026-09-01_2026-09-07-UTC.csv`. Hidden quiet periods are left out of the file too. ### Breakdown The same traffic grouped along one dimension at a time, chosen from **Group by**, with requests, input, output and total tokens, errors, and estimated cost per row. Cache columns appear when any row used caching; a **Failovers** column appears for Model, Upstream Model and Provider. Switch between table, bar and pie with the toggle above it — the charts show the 15 largest rows by requests. | Group by | Groups requests by | | - | - | | **Model** | The model name the caller sent | | **Upstream Model** | The provider's own model ID that served the request, with the provider alongside | | **User** | The user the request was made for | | **Group** / **Role** | The groups or roles of those users (see below) | | **Provider** | The provider configuration that served the request | | **Credential** | The stored provider key that served the request — the unit a provider invoice is billed to | | **Routing Role** | **User requests**, **Routing overhead** (a routing policy's own route decisions) and **Routing preview (admin)** | | **API Key** | The gateway API key used, shown as ` ()` | | **Client settings** | The client settings a Barndoor Bridge or `barndoor run` session launched with, shown as ` v`. Sessions from before client settings show the launch profile they ran under. | | **AI Agent** | The agent recorded on the request | | **Status Code** | HTTP status, split by whether the gateway or the provider issued it | | **Error Source** | Failed requests only: **Gateway (Barndoor limits)** versus **Model provider** | The metric definitions above apply unchanged. A few groupings need more care: * **Requests with no value for the dimension are left out**, so the rows may not add up to the summary cards. Grouping by **User**, for example, omits traffic from keys not tied to a user. * **Group and Role can double count.** A user in three groups contributes their full usage to each of the three rows, so group rows can add up to more than the organization total. Users with no group don't appear at all. * **Routing Role reports all traffic.** **User requests** is everything that isn't a routing decision, so the rows always add up to the total. **Routing overhead** is what routing cost you on top of the requests it routed; **Routing preview (admin)** is spend from admins testing policies, which is not charged to anyone's budget or rate limits. See [Routing policies](/how-tos/llm-routing-policies); they may not be enabled for your organization yet — contact Barndoor. * **Client settings** only has rows if your organization launches Claude or Codex through Barndoor Bridge, which may not be enabled for your organization yet — contact Barndoor. * **Credential** is the grouping to use when reconciling against a provider invoice. Several providers can share one credential, so a **Provider** breakdown can split one invoice line across several rows. * **Status Code** puts a gateway 429 and a provider 429 on separate rows. The Errors column is hidden for **Status Code** and **Error Source**, where it would say nothing new. #### Traffic excluded from the rows Three groupings report requests that have no value for the dimension beneath the table rather than as a row, because that bucket is usually the largest and would crowd out the rows that matter. The note beneath the table gives its request and token count, so the rows plus the note reconcile with the summary cards. | Grouping | The note covers | | - | - | | **AI Agent** | Requests with no AI agent assigned: keys not bound to an agent, direct user traffic, and requests from before agent attribution | | **Credential** | Requests with no credential recorded: requests from before credential attribution, and providers that hold their own key rather than a stored credential | | **Client settings** | Requests not run under a governed agent session: ordinary API-key traffic, and requests from before client settings attribution | > [!NOTE] > > **Model**, **Upstream Model** and **Provider** rows are grouped by the name recorded when the request was made, so a provider renamed mid-window appears as two rows. **AI Agent**, **Credential**, **API Key** and **Client settings** rows are grouped by ID, so a rename keeps one row. The table returns at most 500 groups, the largest by tokens. Only very broad selections reach that, and grouping by **User** or **API Key** over a long window is the likeliest way to hit it — narrow the window or scope if you need the tail. **Group** and **Role** are built from the user and API key groupings, so they're subject to the same limit. ## Per-agent LLM usage Each AI agent's detail page (**AI Agents** → select an agent) has an **LLM Usage** card covering the agent's traffic over the page's selected period, with **Cost**, **Requests**, **Tokens Used** and **Error rate**, a cost sparkline, and a **By model** table showing each model's share of the agent's cost. These use the same definitions as the dashboard: **Tokens Used** includes cache tokens, and usage is matched on the agent recorded on each request, so it doesn't change when keys are unbound or rebound. The "/ day" figures divide by the length of the whole period, including days with no traffic. When the agent has errors, the **Error rate** figure links to this dashboard's **Errors** tab, already scoped to the agent over the same window (up to 30 days). The card only appears once API keys can be bound to AI agents in your organization; this may not be enabled for your organization yet — contact Barndoor. ## Frequently asked > [accordion] Why doesn't Est. Cost match my provider invoice? > > Est. Cost is computed from your pricing rules at the time each request was served, not read from the provider. It drifts from the invoice when a rule's rates don't match your contract, when models are unpriced or a provider has **Calculate token cost** turned off, or when prices changed partway through the period (history is never re-costed). Check the timezone too: invoices are usually in UTC. To compare like for like, set the window to the invoice period, keep UTC, and group the Breakdown tab by **Credential**. See [Managing Model Pricing](/how-tos/manage-model-pricing). > [accordion] Why is Tokens Used much larger than input plus output? > > It includes cache read and cache write tokens, which the input figure never does. Agents that reuse long prompts — coding assistants in particular — can read far more tokens from the cache than they send fresh. The **Caching** tab shows the split. > [accordion] Why are there more requests than my users sent? > > Requests routed through a routing policy record a second request for the policy's own route decision, and routing policy previews are recorded too. Group the Breakdown tab by **Routing Role** to see how much of the total each accounts for. Blocked requests also count as requests. > [accordion] My error rate spiked but the provider looks healthy. > > Requests blocked by budgets and rate limits count as errors. On the **Errors** tab, check whether the spike is labelled **Gateway** (your own limits) or **Provider**. If failover is configured, the **Resilience** tab shows provider failures that never became user-facing errors. > [accordion] Why don't the per-group rows add up to the organization total? > > A user who belongs to several groups is counted in each of them, and users in no group aren't shown. Use **By Group** in the scope filter when you need one group's exact totals. > [accordion] Why does an expanded row show more than the row itself? > > On a rolling window the first period is partial — the row counts traffic from the start of the window, but expanding it breaks down the whole period, including the part before the window began. Pick whole days on the calendar to avoid this. > [accordion] Where is MCP traffic? > > On the [MCP Usage Dashboard](/how-tos/read-mcp-usage-dashboard) (**Reporting → MCP Usage Dashboard**). This dashboard covers LLM Gateway traffic only. # Reading the MCP Usage Dashboard Source: https://docs.barndoor.ai/how-tos/read-mcp-usage-dashboard What each metric on the MCP Usage Dashboard measures, and how to read the trends, errors, by-period and breakdown tabs. The MCP Usage Dashboard (**Reporting → MCP Usage Dashboard**) reports tool invocations, request duration, and errors across your MCP servers. This page defines what each figure counts, so the numbers can be read without guessing. The dashboard is available to organization admins and opens on the **Last 7 days**, covering all organization traffic. ## Choosing the window The time controls in the header work the same way as on the [LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard#choosing-the-window-and-scope): * **The date button** opens rolling presets (**Last 1 hour** through **Last 30 days**), calendar presets (**Today**, **Yesterday**, **Week to date**, **Month to date**, **Last month**) and a calendar for a custom range. The arrows either side step the window back or forward by its own width. * **UTC is the default timezone.** Switch to **Local** at the bottom of the date picker to use your browser's timezone instead. The choice decides where each day and week starts. * **The Hourly / Daily / Weekly selector** sets the period length for the charts and the By period table. It follows the window unless you change it, and options that would be unreadable for the window are greyed out. * **Refresh** re-fetches the data, and **Auto** repeats that every 10 seconds. The window is part of the URL, so copying the address shares the view. ## The summary cards Six cards sit at the top, reflecting the selected time range. | Card | What it counts | | - | - | | **Tool Calls** | All MCP messages proxied in the period | | **Avg Duration** | Mean time per call spent on the MCP server | | **MCP Servers** | Servers active in the busiest single period | | **AI Agents** | Agents active in the busiest single period | | **Active Users** | Users active in the busiest single period | | **Error Rate** | Share of traffic that failed or was blocked, with the raw count beneath | > [!NOTE] > > The three middle cards are peaks, not totals. Each reports the highest count seen in any one period, so a window where ten servers were each busy at different hours shows the busiest hour's count rather than ten. Two of the remaining cards count something broader than their label suggests. ### Tool Calls Every MCP message proxied in the period — **not only tool invocations.** The underlying query counts tool calls *plus* MCP protocol traffic (`tools/list`, `initialize`, and similar). A client that reconnects frequently, or an agent that enumerates tools before every run, inflates this relative to "things the agent actually did." > [!NOTE] > > For a count of genuine tool invocations, switch the **Breakdown** tab to group by Tool. Protocol traffic carries no tool name, so it is excluded there. ### Error Rate Requests that failed upstream **plus** requests blocked by policy or governance. Both land in this one figure, and the count beneath the percentage covers both. A spike is not necessarily a broken server — it may be a policy correctly denying traffic. The **Errors** tab breaks this down over time, both by server and as a rate. ## Avg Duration **The mean time per call spent on the MCP server, as measured at the gateway.** The timer starts when the gateway sends your request upstream and stops when the server's response comes back, so the figure is time attributable to the server and the network between it and the gateway. > [!NOTE] > > The card is named *duration*, not *latency*, because it is the whole call's wall-clock — not the overhead Barndoor adds on top. It is not a number to subtract from anything. Denied requests are excluded — a request blocked by policy is never sent upstream, so it has no duration to record. It still counts toward Tool Calls and Error Rate. > [!NOTE] > > It's a mean, not a percentile, so one slow call skews a quiet server. A server with four calls — three at 100ms and one at 30s — reports 7.6s, which describes none of them. Servers differ a lot on this: an in-cluster server has a far shorter network path than an external SaaS API, and the work behind each call differs. **Treat Avg Duration as a trend within a single server, rather than a league table across servers.** ## The tabs ### Trends **Tool Calls Over Time**, **Avg Duration Over Time**, and **Active Users Over Time**, one value per period. The period length is set by the granularity selector. ### Errors Two views side by side: error count over time stacked by MCP server (the ten largest in the window), and error rate as a percentage. The stack answers "is one server responsible?"; the rate answers "how bad is it relative to volume?" On low traffic these can disagree — a handful of errors is a low count but a high rate. That is expected, and the rate is usually the one to act on. ### By period One row per period — hourly, daily or weekly, chosen from the **Usage by** dropdown — newest first, with tool calls, average duration, errors, error rate, and the users, MCP servers and AI agents active in that period. Options that would be unreadable for the selected range (hourly over a month, weekly over a day) are greyed out. Expanding a row breaks that single period down along the dimension set in **Expand to**, so you can go from "Tuesday was bad" to "Tuesday was bad on this server" without changing the date range. Quiet periods are hidden by default; the line above the table says how many are held back, and clearing **Hide quiet days** shows them as zero rows. The first and last periods of a rolling window are usually partial. **Export CSV** downloads exactly the rows and columns on screen as plain numbers, with the window and timezone recorded in the first line and in the filename (for example `mcp-usage-by-period-2026-09-01_2026-09-07-UTC.csv`). ### Breakdown The same traffic grouped along one dimension at a time, chosen from **Group by** — **MCP Server**, **Tool**, **User**, or **AI Agent** — with tool calls, average duration, and errors per row. Switch between table, bar and pie with the toggle above it; the charts show the 15 largest rows. The metric definitions above apply unchanged. MCP Server and AI Agent rows are grouped by name, so a server or agent renamed mid-period appears as two rows. Traffic with no value for the chosen dimension — protocol messages when grouping by Tool, for example — is left out, so the rows may not add up to the summary cards. The table returns at most 500 groups, ordered by tool call volume. Only very large or very broad selections reach that, and grouping by Tool over a wide window is the likeliest way to hit it — narrow the date range if you need the tail. ## Frequently asked > [accordion] Why is one server's duration in milliseconds and another's in seconds? > > Usually because the calls genuinely differ. An in-cluster server has a far shorter network path than an external SaaS API, and cheap lookups finish faster than heavy queries. Compare each server against its own history rather than against other servers. > [accordion] Why does Tool Calls exceed the number of tool calls I expect? > > It includes MCP protocol traffic — `tools/list`, `initialize`, and similar — not only tool invocations. Agents that reconnect or re-enumerate tools frequently generate a lot of this. Grouping by Tool on the Breakdown tab excludes it. > [accordion] My error rate spiked but the server looks healthy. > > Policy denials count as errors. Check the Errors tab to see whether the spike concentrates on one server, and whether it coincides with a policy change rather than an upstream fault. > [accordion] Can I filter the dashboard to one team or agent? > > Not on this dashboard. The Breakdown and By period tabs group by user or AI agent, so per-user and per-agent figures are visible in a table, but the summary cards and charts always cover all organization traffic. The [LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard) does have scope filters, for LLM Gateway traffic only. > [accordion] Why do the daily totals change when I switch to Local time? > > The timezone decides where each day starts, so a call made late in the evening can move from one day's row to the next. For the same start and end times, the window's overall totals don't change. Keep UTC when comparing figures with colleagues in other timezones. # Redirect URI Allowlisting Source: https://docs.barndoor.ai/how-tos/redirect-uri-allowlisting Allowlist the Barndoor redirect URI in your OAuth application ## Overview Barndoor connects users to your MCP server using the OAuth 2.0 authorization code flow. When a user authorizes Barndoor, your platform redirects their browser to a Barndoor-hosted callback URL with the authorization code. For that redirect to succeed, the callback URL must be registered as an allowed redirect URI on the OAuth application (or MCP server registration) in your platform. If you operate a SaaS platform with an MCP server and want Barndoor customers to be able to connect to it, add the redirect URI below to your OAuth client allowlist. ## Redirect URI to Allowlist Add this one URI: * `https://app.barndoor.ai/callback` — Production > [!NOTE] > > This URI is stable. It is an exact-match URL — do not add trailing slashes, wildcards, or alternate paths. ### Common Platform Locations | Platform pattern | Typical setting path | | - | - | | OAuth 2.0 client config | App settings → OAuth → Redirect URIs | | Dynamic client registration | Set `redirect_uris` array in the client registration payload | | Per-tenant OAuth app | Admin console → Apps / Integrations → Edit app → Redirect URIs | ## Troubleshooting If users see redirect errors after allowlisting: 1. **Check for exact-match issues.** Confirm there are no trailing slashes, missing `https://`, or typos. 2. **Confirm the change has propagated.** Some platforms cache OAuth client config for several minutes. 3. **Contact support** if the issue persists: [support@barndoor.ai](mailto:support@barndoor.ai). ## Frequently Asked Questions > [accordion] Do I need to allowlist any other Barndoor URIs? > > No. `https://app.barndoor.ai/callback` is the only redirect URI customers connect from. Barndoor's non-production environments are for internal use and are not part of any customer integration. > [accordion] Does this URI change? > > No. It is a stable, long-lived URI. If it ever changes, Barndoor will notify integrated platforms in advance and update this page. > [accordion] Can I use a wildcard like https\://\*.barndoor.ai/callback? > > Most OAuth providers don't allow wildcards in redirect URIs, and we don't recommend it even where supported. Register the exact URI above. > [accordion] Is this the same as IP whitelisting? > > No. Redirect URI allowlisting governs the OAuth browser redirect to Barndoor. [IP whitelisting](/how-tos/ip-allowlisting) governs the server-to-server MCP traffic from Barndoor to your infrastructure. Most integrations need both. ## Need Help? If you have questions about redirect URI allowlisting or need assistance configuring your OAuth application, reach out to our support team at [support@barndoor.ai](mailto:support@barndoor.ai). # Granular Tool Use Confirmations Source: https://docs.barndoor.ai/how-tos/tool-confirmations Require human approval for any tool call — including reads — on a per-tool, per-group basis from the Access Control Center. ## Overview Granular Tool Use Confirmations lets you require human approval for any tool call an access policy governs — including reads, not just creates, updates, and deletes. An agent reading sensitive data (a customer record, a legal contract, a payroll file) can carry as much risk as one changing it, so approval requirements are configured per tool and per group, inside a policy in the **Access Control Center** — not as a single global setting on the agent. ## Before You Begin You'll need: * A Barndoor account with **admin privileges** * At least one access policy governing the agent and MCP server you want to configure If you haven't set one up yet, see [Managing Policies](/how-tos/manage-policies) first. ## How It Works Every tool a policy governs has one of three states: | State | Behavior | | - | - | | **Always Allow** | The tool runs immediately, no prompt. | | **Needs Approval** | The call pauses until a human approves or denies it, then proceeds or fails accordingly. | | **Off** | This group isn't granted the tool. There's no explicit "deny" state — a tool set to Off is simply omitted from the policy's rule. | > [!NOTE] > > **Off is not a block.** It declines to grant the tool for *this* group; it does not override a grant the same user gets from another group. To make sure nobody can reach a tool through this policy, leave it **Off** in every column, including **All Users**. Each state is set **per tool, per group** — not globally per agent. That means you can, for example, let a support agent freely read Salesforce records but require approval before it posts to a customer-facing Slack channel, or require approval on both reads and writes for a policy scoped to a more sensitive system. > [!TIP] > > Because the setting lives on the policy, not the agent, the same agent can have different confirmation rules depending on which policy — and therefore which group or role — is in effect for a given user or session. ### Precedence across groups When a principal belongs to more than one group with a rule for the same tool, the most permissive state wins: **Always Allow > Needs Approval > Off**. This is order-independent — it doesn't matter which rule was written first. **All Users** is the policy's baseline: whatever you grant there applies to every user the policy covers, including members of the specific groups beside it. Group columns can add to the baseline; they can't take it away. > [!WARNING] > > Because the baseline wins, an **All Users → Always Allow** grant makes a narrower group's **Needs Approval** grant *dormant*: the prompt never fires, because the user is already allowed unconfirmed. The group's setting is kept, not discarded — remove or lower the baseline grant and the approval requirement takes effect again. This is why a policy can show **Needs Approval** for a group while users in that group are never prompted. If you're scoping approval to a specific group, check that no wider rule already grants Always Allow on the same tool. ## Configure Tool Confirmations 1. Sign in to your Barndoor portal and navigate to the **Access Control Center**. 2. Open the access policy governing the MCP server and agent you want to configure, and go to its **Policy Rules** step. 3. The tool matrix lists the server's tools down the left and one column per audience — **All Users** first, then each group or role you add. Set each cell to **Always Allow**, **Needs Approval**, or **Off**. 4. To move many tools at once, use the **Set all** control in a column header. It applies one state to every tool currently *visible* in that column, so narrow the list with the operation filter or the search box first — the control tells you how many tools it will touch. 5. Save the policy. Changes take effect on the next tool call. > [!TIP] > > A quick way to lay down a baseline: filter to **Read** and **Set all → Always Allow**, then filter to **Update** and **Delete** and **Set all → Needs Approval**, then clear the filter and turn off anything the group shouldn't reach at all. > [!WARNING] > > Setting a frequently-used tool to **Needs Approval** introduces a pause in the agent's workflow until a human responds. Reserve it for tool calls where the risk of an unreviewed action or an unreviewed data exposure outweighs the friction of a prompt. ## What the User Sees When a tool set to **Needs Approval** is called, the approval request goes back to the person driving the session — the agent receives a request naming the specific server, tool, and arguments instead of a result, and the call runs only after that person approves it. There is no separate reviewer queue and no reviewer routing to configure. A tool that no group grants comes back as a policy block instead, worded distinctly from an approval request so an agent doesn't retry it as though it were pending. ## Scope of Enforcement > [!NOTE] > > **Known limitation**: approval prompting currently happens only through ToolIQ / the tool router. On the direct proxy path (non-ToolIQ clients), a tool set to Needs Approval executes without a prompt. If your agents connect through a non-ToolIQ client, treat Needs Approval as not yet enforced for that path — leave the tool **Off** instead where you need it stopped everywhere. ## API and Terraform Under the hood, each state serializes as an action on the policy rule: * **Always Allow** → `tools/call:` * **Needs Approval** → `tools/call::approve` (this action only — never both the plain and `:approve` form on the same tool) * **Off** → the tool is simply omitted from the rule's `actions` This is expressed entirely through the `actions` field on a policy rule — the same field [Managing Policies](/how-tos/manage-policies) and the `barndoor_policy` Terraform resource already use. If you manage policies as code, add `:approve` to a rule's `actions` list to require approval on that tool. The suffix is reserved and may appear at most once, at the end of a tool-call action. ## FAQ > [accordion] Can I require approval on a read-only tool call? > > Yes — this is the core change. Any tool a policy governs, regardless of whether it reads or writes data, can be set to Always Allow, Needs Approval, or Off. > [accordion] Who approves a 'Needs Approval' request? > > The user whose session made the call. The request surfaces to them in the client they're working in, and the call proceeds only once they approve it. > [accordion] What happens to a tool call while it's waiting on approval? > > The call blocks until it's approved or denied. Approved calls proceed normally; denied calls return an access-denied response to the agent. > [accordion] I set a tool to Needs Approval, but nothing ever prompts. > > Two likely causes. Check whether a broader rule — most often **All Users** — already grants that tool **Always Allow**, which outranks your Needs Approval grant and leaves it dormant. If the grants look right, check how the agent connects: approval prompting happens on the ToolIQ / tool-router path only. ## In this section > [card] [Managing Policies](/how-tos/manage-policies) > > Create and structure the access policies that tool confirmations attach to. > [card] [Notifications](/how-tos/notifications) > > Get alerted when a policy changes or a server's tools move underneath it. # Trial Guide Source: https://docs.barndoor.ai/how-tos/trial-guide Complete guide to set up and configure your Barndoor platform from start to finish ![Middle Layer Architecture](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/middleLayer.webp?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=58207d2fdf59c802bddaa7c1ff324f2f) Welcome to Barndoor, where your AI workflows can run safely with context-aware tool routing, action-level policies, and observability. **In the free trial, you can:** > [card] Centralize AI + MCP Connections > > Securely connect AI apps (Claude, ChatGPT, VSCode), agentic platforms (LangChain, LlamaIndex, CrewAI) and more with [MCP servers](https://modelcontextprotocol.io/docs/learn/server-concepts). > [card] Control AI Actions at Runtime > > Define exactly which servers and tools your AI apps and agents can access across create, read, update, or delete operations—enforced instantly in live workflows. > [card] Improve Execution with Context-Aware Tool Routing > > Eliminate tool selection friction. Barndoor analyzes live context enabling your AI to execute the right tool at the right time—securely and efficiently. > [card] Observe AI Activities from End-to-End > > Eliminate the guesswork from agentic workflows. Get complete end-to-end telemetry on every routing decision and tool execution, making it effortless to monitor performance and maintain security posture. *** > [!NOTE] > > **Estimated Time**: 15-20 minutes ## Prerequisites Before you begin, ensure you have: * Admin Access to your Barndoor account. Click [here](https://app.barndoor.ai/auth/signup/trial) if you have not signed up yet. * Admin credentials for the MCP server you want to connect * An AI client application or API key ready for testing *** ## Labs > [accordion] Step 1: Add and Connect an MCP Server > > ### Summary > > To realize full productivity potential, AI needs to take actions in real systems like Salesforce, Jira, GitHub, etc. Barndoor is the control plane for access control between AI and these systems. > Once set up, Barndoor enforces fine grained access controls to the MCP servers of your connected systems. > > ![Add MCP Server](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/addMCPServer.png?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=8fe6f32c3583dba8fadcb1a67961e9de) > > ### What You'll Learn > > In this lab, you'll discover how register and connect the Barndoor Gateway to an MCP server. Once connnected that server becomes available to your agents. > > ### Let's Get Started > > To evaluate how Barndoor works, first add and connect an MCP server. **Choose your path:** > > > [card] [Add an MCP Server](https://app.barndoor.ai/servers/add?appcue=311cf101-0f1e-4412-9ce6-4e111bc0632a) > > > > Configure MCP server now in the Barndoor Dashboard > > OR > > > [card] [Register MCP Server Docs](https://docs.barndoor.ai/how-tos/add-an-mcp-server) > > > > Learn how to add servers with our comprehensive guide > > > [!NOTE] > > > > You can connect multiple MCP servers. Start with one to understand the process, then add more as needed. > [accordion] Step 2: Define Your First Access Policy > > ### Summary > > The Access Control Center is where you **define policies** for how **AI agents and users can interact with connected systems**. > > * Create policies that apply to specific agents, user roles and groups, or across your environment. > * Choose which MCP tools are available or add sophisticated **fine-grained access controls**. > * Deeper role, group, or user attribute based policies are available once you've **integrated Barndoor with your identity provider system**. > > ![Configure Policy](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/configurePolicy.png?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=5921c97c013526aded0cf8f30b74dd0b) > > ### What You'll Learn > > In this lab, you'll create your first access policy that controls what AI agents can (and cannot) do with your MCP servers. You'll learn how to set up guardrails that keep AI secure while maintaining productivity. > > > [!NOTE] > > > > ⚠️ **Important**: You must first connect to an MCP server before you can set up policies. If you haven't completed Step 1, go back and add a server first. > > ### Let's Get Started > > Follow these steps to create your first access control policy: > > **1. Open Access Control Center** > > Click [Access Control Center](https://app.barndoor.ai/rules) to begin configuring policies. > > **2. Select Agent and Server** > > 1. Under the **'AI Agents'** column, choose **'Any Agent'** > 2. Under the **'Connected Servers'** middle column, select **Notion** or your preferred server to configure agent permissions > > **3. Enable MCP Tools** > > Notice all your MCP tools are loaded under the **'Actions'** tab. > > Turn on only the MCP tools you want Barndoor to allow through. This controls which tools are available for the agent to use. > > **4. Add Access Restrictions** > > Now that we've enabled certain tools, let's add RBAC/ABAC access control policies. > > Click the **'Restrictions'** tab to configure a policy. > > **5. Create A Policy** > > We have a bunch of pre-built policies in our [MCP Server marketplace](/mcp-servers) you can reuse. > > For now, click **'Add Restriction'** and set up a basic user policy: > > 1. **Name the restriction**: Give it a descriptive name like "disallow\_email" > > 2. **Choose Action**: Select **'All Actions'** (synonymous with all MCP tools) > > 3. **Set Match**: Choose **'Any'** > > 4. **Add Condition**: Select a **User restriction** type that checks if the **Email** is **not equal** to yours > > > [!NOTE] > > > > **Optional**: If you've set up a Notion MCP server, [check out this policy](/mcp-servers/notion#policies) that disallows page updates and comments to a specific Notion page. Please note: deeper role, group, or user attribute based policies are available once you’ve integrated Barndoor with your identity provider system. > > **6. Review JSON Configuration** > > Here's how the JSON should look: > > ```json theme={null} > { > "name":"disallow_other_emails", > "effect":"EFFECT_DENY", > "actions":[ > "*" > ], > "roles":[ > "*" > ], > "condition":{ > "match":{ > "all":{ > "of":[ > { > "expr":"P.attr.email != \"youremai@email.com\"" > } > ] > } > } > } > } > ``` > > 💡 **What this does**: Denies all actions (\*) for users whose email doesn't match yours—a basic example of user-level access control. Be sure to change the sample to match your email used during the Barndoor authorization process in step 3. > > > [!TIP] > > > > **Extra Credit**: Check out our [Policies API](/how-tos/manage-policies) and deeper details on how our policies are constructed. > [accordion] Step 3: Protect Sensitive Data with the Data Control Center > > ### Summary > > The **Data Control Center** goes a layer deeper: it inspects the actual **data** flowing through MCP tool calls and can **block, redact, tokenize, or alert** on sensitive content in real time. > > In this lab you'll stand up the three essentials: > > 1. A **Protection Profile** that detects PII (SSNs, credit cards, emails, and more). > 2. An **MCP Policy** that **redacts** that PII in tool responses. > 3. A **Field Control** rule that deterministically strips known-sensitive fields from a specific tool. > > ![Data Control Center](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/trial-dcc-overview.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=7fb8e51e043f5b3fb23bc27674c2f526) > > ### What You'll Learn > > How to protect sensitive data two complementary ways — by **content detection** (Protection Profiles + MCP Policies) and by **exact field path** (Field Controls) — and how redaction is enforced on live MCP traffic. > > > [!NOTE] > > > > ⚠️ **Important**: You need at least one MCP server connected (Step 1). A **Protection Profile must exist before you can create an MCP Policy**, so we build the profile first. > > ### Let's Get Started > > Open your [Barndoor dashboard](https://app.barndoor.ai) and go to the **[Data Control Center](/how-tos/data-control-center/overview)**. It has three tabs: **MCP Policies**, **Field Controls**, and **Protection Profiles**. > > #### Part A — Create a PII Protection Profile > > **1. Open Protection Profiles** > > Select the **Protection Profiles** tab and click **Add Protection Profile**. > > ![MCP Target and runtime boundary](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/trial-protection-profile.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=3314982e9c303a9482e6cafe32dfbbbc) > > **2. Choose Sensitive Identifiers** > > From the catalog, choose **Sensitive Identifiers** — built-in detection for structured personal identifiers (SSNs, cards, emails, phone numbers). No connection needed. > > **3. Name it and pick detection signals** > > Give it a name like **Sensitive Identifiers v1**. Under **Detection Signals**, click **Select Defaults** to enable Credit Card, SSN, Email, Phone Number, IP Address, Passport Number, Date of Birth, and Address. > > ![Add Sensitive Identifiers Profile](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/add-profile.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=0e5789a0a7aa947cba287c72908b6c13) > > **4. Save** > > Click **Add Profile**. It now appears in the Protection Profiles list, ready to attach to a policy. > > #### Part B — Create an MCP Policy that redacts PII > > **1. Start a new policy** > > Switch to the **MCP Policies** tab and click **New MCP Policy** to open the wizard. > > **2. Choose the MCP target** > > Select **All MCP servers** (or a specific one), then set the **Runtime Boundary** to **Tool Output Only** — inspect what a tool returns before it reaches the agent. > > ![MCP Target and runtime boundary](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/mcp-target.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=017e8bce683bb1069c5164187d368188) > > **3. Scope to users, groups, or roles** > > Choose **All Users (No Filter)** to protect everyone, or **Specific Groups or Roles** (for example, `dept-hr`) to target an audience. > > ![Groups and Roles scoping](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/idp-groups-target.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=804a6c36560f733fb385ba8abb28899c) > > **4. Attach the profile and set the action** > > Name the policy (e.g., **Block PII in and out**), select your **Sensitive Identifiers v1** profile, and set **Action** to **Redact**. Leave **Dry Run** off to enforce immediately — or toggle it on to log detections without changing traffic while you validate. > > ![Protection profiles and action](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/attach-profile.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=531f58c3d85dc8b9fabff9522440048b) > > **5. Create the policy** > > Click **Create Policy**. Detected PII in matching tool responses is now replaced with typed placeholders (e.g., `[EMAIL]`, `[SSN]`). > > > [!TIP] > > > > Want to confirm coverage before enforcing? Turn on **Dry Run**, send some traffic, and review **Detection Activity**. Full detail lives in the [MCP Policies guide](/how-tos/data-control-center/mcp-policies). > > #### Part C — Add a Field Control (deterministic response redaction) > > Field Controls strip **exact JSON fields** from a specific tool's response — use them when you know the precise field paths, independent of content detection. > > **1. Open Field Controls** > > Switch to the **Field Controls** tab and click **Add Field Control Rule**. > > **2. Target a server and tool** > > Name the rule (e.g., **Block Atlassian sensitive key value pairs**), choose the **Server** (e.g., Atlassian) and **Tool** (e.g., `getAllProjects`). Optionally scope it with a **Target Group / Role** — leave empty to apply to all users. > > **3. Pick a behavior and select fields** > > Choose how the rule treats the response: > > | Behavior | Effect | > | - | - | > | **Redact selected fields** | The fields you check are removed; any new fields the tool adds later still pass through | > | **Allow only selected fields** | Only the fields you check pass; anything else (including new fields) is automatically redacted | > > Then check the exact fields in the field tree. > > ![Add Field Control Rule](https://mintcdn.com/barndoor/LqgBE7ANQmmfqfs0/images/data-control-center/field-control.png?fit=max\&auto=format\&n=LqgBE7ANQmmfqfs0\&q=85\&s=1aabf93487ba8fce7a4fcb88018cfaf8) > > **4. Add the rule** > > Click **Add Rule**. It enforces on the next matching tool call. > > > [!TIP] > > > > **Extra Credit**: Go deeper with the Data Control Center guides — [Protection Profiles](/how-tos/data-control-center/protection-profiles), [MCP Policies](/how-tos/data-control-center/mcp-policies), and [Field Controls](/how-tos/data-control-center/field-controls). > [accordion] Step 4: Connect an Account > > ### Summary > > When you connect an account, Barndoor uses OAuth 2.0 to perform a secure handshake [on behalf of the user](https://datatracker.ietf.org/doc/html/rfc8693) with the provider. > After you log in, the provider (e.g., Salesforce) sends Barndoor an access token. > Barndoor securely stores this JWT token and uses it whenever an MCP server tool call needs to act on your behalf — for example, retrieving Salesforce data or updating records. The JWT token will live for 60 minutes and can always be refreshed. > Tokens can be revoked at any time through your provider’s account settings or through our API/SDK. > > ### What You'll Learn > > In this lab, you'll learn how to create and configure user accounts that will interact with your MCP servers through Barndoor's access control policies. > > ### Let's Get Started > > > [!TIP] > > > > Choose your own destiny: > > * Follow the buttons below to access the Barndoor account management interface > > * Check out our extensive documentation on account configuration > > > [card] [Connect an account](https://app.barndoor.ai/settings/accounts) > > > > Connect Barndoor on behalf of a user > > OR: > > > [card] [Connecting Account Docs](https://docs.barndoor.ai/how-tos/connected-accounts) > > > > Connect user accounts to Barndoor > [accordion] Step 5: Connect an AI Client > > ### Summary > > Connect your preferred AI chat client (Claude, ChatGPT, Cursor, VS Code) to Barndoor so AI agents can interact with your MCP servers through governed access controls. For a comprehensive walkthrough, see the [Connecting Barndoor to Agents guide](/how-tos/connecting-barndoor-to-agents). > > ![Authorize Barndoor](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/authorizeBarndoor.png?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=38fb92359fedaa1369d050722be0824d) > > ### What You'll Learn > > In this lab, you'll configure an AI client to connect to Barndoor's MCP gateway. Once connected, the AI will be able to use your MCP tools while respecting the policies you've configured. > > ### Let's Get Started > > > [!TIP] > > > > Choose your AI client below and follow the connection steps. Most clients can be connected in under 5 minutes. > > > > * Check out our [comprehensive connection guide](/how-tos/connecting-barndoor-to-agents) for detailed instructions > > > [tab] Claude > > > > **What you need:** > > > > * Active Claude account (Pro or Team plan) > > * Your Barndoor MCP URL: `https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}`. To locate this, simply view the details for any of your configured servers [here](https://app.barndoor.ai/servers) > > > > **Quick Steps:** > > > > 1. Open Claude → **Settings** → **Connectors** tab > > 2. Click **"Add custom connector"** > > 3. Enter your Barndoor MCP URL > > 4. Click **Connect** to authorize > > > > 📚 [Detailed Claude guide](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp) > > > [tab] ChatGPT > > > > **What you need:** > > > > * ChatGPT Plus or Enterprise account > > * Your Barndoor MCP URL: `https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}` > > > > **Quick Steps:** > > > > 1. Go to ChatGPT → **Settings** → **Apps** → **Create App** > > 2. Provide app name, description, and your Barndoor MCP URL > > 3. Click **Create** and test the connection > > > > 📚 [Detailed ChatGPT guide](https://developers.openai.com/apps-sdk/deploy/connect-chatgpt/) > > > [tab] Cursor IDE > > > > **What you need:** > > > > * Cursor IDE installed > > * Your Barndoor MCP URL: `https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}` > > > > **Quick Steps:** > > > > 1. **Cursor** → **Settings** (or `Cmd/Ctrl + ,`) > > 2. Navigate to **Extensions** → **MCP** > > 3. Add your Barndoor server configuration > > 4. Restart Cursor > > > > ```json theme={null} > > { > > "mcpServers": { > > "barndoor": { > > "url": "https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}" > > } > > } > > } > > ``` > > > [tab] VS Code > > > > **What you need:** > > > > * VS Code with MCP support > > * Your Barndoor MCP URL: `https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}` > > > > **Quick Steps:** > > > > 1. Open Command Palette (`Cmd/Ctrl + Shift + P`) > > 2. Select **Preferences: Open Settings (JSON)** > > 3. Add MCP server configuration > > 4. Reload VS Code window > > > > ```json theme={null} > > { > > "mcp.servers": [ > > { > > "name": "Barndoor", > > "url": "https://{{your-org}}.platform.barndoor.ai/mcp/{{servername}}" > > } > > ] > > } > > ``` > > > [!NOTE] > > > > **Connection Issues?** Verify your Barndoor URL is correct and that you've completed Steps 1-3 (MCP server connected, policies configured, account created). > [accordion] Step 6: Review Audit History > > ### Summary > > Use the **Audit Center** to monitor overall behavior and spot unusual patterns, or dive into **Audit History** for detailed, event-by-event records. Track who accessed what, when it happened, and whether policies allowed or blocked the action. > > ![Audit History Center](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/auditHistory.png?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=833918e076f28dfd14361b1566636be0) > > ### What You'll Learn > > In this lab, you'll learn how to access Barndoor's audit logs to review AI interactions with your MCP servers. You'll see: > > * **Who & what**: User, agent, or service activity > * **When & where**: Time and affected system > * **Outcome**: Policy decision result and full activity trace log > > ### Let's Get Started > > **1. Navigate to Audit History Center** > > Click [here](https://app.barndoor.ai/audit/history) to begin > > **2. Open Filters Panel** > > Click the **Filters** button (or filter icon) in the Audit History interface. > > **3. Navigate to Server Filter** > > In the filters modal, click on **Server** to expand the server source options. > > **4. Select Your Server(s)** > > Choose one or more servers from the list (i.e., Notion) > > You can use **Select all** or **None** to quickly manage selections. > > **5. Apply Filters** > > Click the **Apply** button at the bottom to filter the audit logs. > > The interface will show "X filters selected" and display only events related to your chosen server(s). > > **6. Review Filtered Results** > > Now you'll see only the audit events for your selected server(s), making it easy to: > > * View audit logs for specific servers, agents, etc. > * Investigate issues with a particular MCP server by clicking into the traceId to see a full stacktrace > * Monitor your inbound MCP calls across all users/agents/servers > > ### Additional Filter Options > > Beyond **Server**, you can also filter by: > > * **Agent type**: Which AI agent made the request > * **Event Type**: Type of action attempted > * **Resource**: Specific data or endpoint accessed > * **Status**: Allowed, denied, or blocked actions > * **User**: Individual user or service account > > Combine multiple filters to drill down into exactly the activity you need to review! > > > [!NOTE] > > > > **Pro tip**: Use the search bar within filters to quickly find specific servers or resources. Clear all filters with the **Clear** button to start fresh. > [accordion] Step 7: Invite Team Members > > ### Summary > > Collaborate with your team by inviting members to your Barndoor tenant. Team members can help manage MCP servers, configure policies, and monitor AI activity across your organization. Non-admin users will be able to login to the Barndoor dashboard and manage their connected accounts. > > ![Users](https://mintcdn.com/barndoor/dUOPVJcsXOqqDZXz/images/users.png?fit=max\&auto=format\&n=dUOPVJcsXOqqDZXz\&q=85\&s=d9a27e4a576f16823e60db19fb55a669) > > ### What You'll Learn > > In this lab, you'll learn how to invite colleagues to your Barndoor workspace. Once invited, they'll receive an email to join your tenant and can be assigned specific roles and permissions. > > ### Let's Get Started > > **1. Navigate to Users Page** > > Go to the **Users** section in your [Barndoor dashboard](https://app.barndoor.ai/users). You'll see: > > * Total number of active users in your tenant > * Monitored actions over the last 30 days > * A list of current team members > > **2. Click Invite Team Members** > > In the top right corner, click the **Invite Team Members** button. > > A modal will appear titled "Invite Team Members" with a form for adding invitees. > > **3. Fill Out Invitee Information** > > For each team member you want to invite, enter: > > * **First name**: Their first name > * **Last name**: Their last name > * **Email**: Their work email (e.g., `teammate@company.com`) > > 💡 **Tip**: The form has placeholder text showing the expected format. > > **4. Add Multiple Team Members (Optional)** > > Need to invite more people? Click **+ Add another team member** to add additional rows to the form. > > You can invite multiple colleagues in one batch—just keep adding rows as needed. > > **5. Remove Invitees (Optional)** > > Made a mistake? Click the **trash icon** (🗑️) next to any row to remove that invitee from the list. > > **6. Send Invitations** > > Once you've filled out all the information, click the **Send Invites** button at the bottom right of the modal. > > ✅ **Success!** Your team members will receive email invitations to join your Barndoor tenant. > > **7. Monitor Invitation Status** > > After sending invites, you'll return to the Users page where you can: > > * See pending invitations > > * Track which team members have accepted > > * Resend invitations if needed > > * Manage user roles once they've joined > > * Promote a team member to Admin > > > [!NOTE] > > > > **What happens next?** Invited team members will receive an email with a link to create their account and join your Barndoor workspace. > > > [!NOTE] > > > > **Security best practice**: Only promote trusted team members who need access to manage AI governance. AI Client consumers should be invited as users. *** ## Next Steps Congratulations! You've successfully completed the Barndoor Trial setup. Here's what you can explore next: > [card] [Our SDKs](/sdks/introduction) > > Whether you're building AI-driven applications with OpenAI or performing direct API calls, the SDK simplifies authentication, tool discovery, and data operations with a robust TypeScript and Python interface. > [card] [API Reference](/api-reference) > > Barndoor provides a robust API that allows developers to securely access their dashboard environment's data and programmatically update settings relevant to their Barndoor Org. > [card] [Building a custom Crew AI Agent](/sdks/examples/crewAI) > > This guide walks you through how to run a CrewAI task using the Barndoor SDK to connect to an MCP server (like Notion), fetch connection parameters, and use the MCP tools within a CrewAI agent. > [card] [MCP Server Catalog](/mcp-servers/servers) > > Check out our MCP server catalog including example policies, available tools and setup instructions *** ## Troubleshooting > [accordion] MCP Server Connection Failed > > **Common causes:** > > * Incorrect server URL or credentials > * Firewall blocking Barndoor's IP addresses > * OAuth token expired > > **Solution:** Verify your credentials and check network connectivity. Contact your MCP server administrator if issues persist. > [accordion] Policy Not Enforcing > > **Common causes:** > > * Policy not assigned to the account > * Policy priority conflicts with another policy > * Cache delay (policies can take 30-60 seconds to propagate) > > **Solution:** Verify policy assignment and wait a minute before testing. Check for conflicting policies. > [accordion] Pending Connection > > **What this means:** > The authentication to this service wasn't completed successfully. > > **Common causes:** > > * Authentication process was interrupted or not completed > * Invalid or expired credentials were provided > * Service connection permissions weren't granted > > **Solution:** Return to the server setup and complete the authentication process. Ensure you grant all necessary permissions when prompted. > [accordion] Agent Authentication Failed > > **Common causes:** > > * Invalid or expired API key > * Incorrect API endpoint > * Missing authentication headers > > **Solution:** Navigate to your Barndoor account settings >> disconnect >> and reauthorize Barndoor on behalf of your user account. > [accordion] Audit Logs Not Showing > > **Common causes:** > > * Time zone mismatch in date filter > * Requests not reaching Barndoor (direct server access) > * Log retention period expired > > **Solution:** Adjust date filters and ensure all requests go through Barndoor's proxy. ## Need Help? > [card] [Documentation](/) > > Browse our complete documentation > [card] [Support](mailto:support@barndoor.ai) > > Contact our support team # Use Codex with the LLM Gateway Source: https://docs.barndoor.ai/how-tos/use-codex-with-llm-gateway Point Codex CLI and Codex Desktop at the Barndoor LLM Gateway using the OpenAI Responses wire format. OpenAI Codex (CLI and Desktop) talks to models over the **OpenAI Responses API** (`POST /v1/responses`), not Chat Completions. The Barndoor LLM Gateway speaks that wire format natively — configure Codex with a custom provider whose `base_url` is your gateway endpoint and whose `wire_api` is `responses`. > [!NOTE] > > This guide covers the do-it-yourself `~/.codex/config.toml` setup. Copy your gateway base URL from [**Settings → My Models → Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) and create a `bd-…` key under [**API Keys**](https://app.barndoor.ai/settings/models?section=api-keys) first. See [Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway) if you don't have those yet. ## Prerequisites * Codex CLI installed, and/or the **Codex desktop app**. * The **OpenAI SDKs & compatible clients** URL from [**Settings → My Models → Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint). * A `bd-…` API key from [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys). * At least one model your key is allowed to call, served by a provider that supports the Responses API. Use the exact name shown under [**Available Models**](https://app.barndoor.ai/settings/models?section=models). ## Which models Codex can use The gateway translates between the OpenAI and Anthropic formats on Chat Completions and Messages, but not on the Responses API. A Responses request is passed to the provider in Responses format, so the model you give Codex must be served by a provider that implements it: | Works from Codex | Doesn't work from Codex | | - | - | | OpenAI, Azure OpenAI (with **Azure API Mode** set to **OpenAI v1 paths**, the default), xAI, OpenAI Codex OAuth, and custom OpenAI-compatible servers that implement `/v1/responses` | Anthropic, AWS Bedrock, Google Vertex AI, Google AI | A Model Route can mix provider types. If a route's first target is an Anthropic model, Codex requests to it fail with `provider '…' does not support endpoint /v1/responses`. Ask your admin for a route whose targets all serve Responses, or use a standalone model (`/`) from an OpenAI provider. > [!NOTE] > > **Self-hosted and private-cloud deployments:** swap `app.barndoor.ai` for your organization's portal hostname everywhere below. The path (`/api/llm-gateway/v1`) is the same. ## Why `/v1` matters Codex appends `/responses` to the provider `base_url`. The gateway's Responses endpoint is `/api/llm-gateway/v1/responses`. | `base_url` you set | Codex actually calls | Result | | - | - | - | | `https://app.barndoor.ai/api/llm-gateway/v1` | `…/llm-gateway/v1/responses` | Correct | | `https://app.barndoor.ai/api/llm-gateway` | `…/llm-gateway/responses` | Wrong — often a `401` with `invalid JWT header: InvalidToken` | Always use the **OpenAI SDKs & compatible clients** URL from the [**LLM Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) card, which ends in `/v1`. Claude Code is the opposite: it uses the URL without `/v1`, because it appends `/v1/messages` itself. ## Configure Codex CLI ### 1. Add a Barndoor provider Edit `~/.codex/config.toml` (create the file if it does not exist): ```toml theme={null} model_provider = "barndoor" model = "gpt-5.4-mini" # replace with a name from Settings → My Models → Available Models [model_providers.barndoor] name = "Barndoor" base_url = "https://app.barndoor.ai/api/llm-gateway/v1" wire_api = "responses" env_key = "BARNDOOR_API_KEY" ``` * `wire_api = "responses"` selects the Responses wire format Codex requires. * `env_key` is only the **name** of the environment variable Codex should read for the API key — it is not the secret itself. * `model` must match a name your key can call: a Model Route name like `gpt-5.4-mini`, or a standalone model in `/` form, exactly as **Available Models** lists it. ### 2. Export the gateway key ```bash theme={null} export BARNDOOR_API_KEY="bd-…" ``` `env_key` points Codex at this variable; the `export` supplies the value. Keeping the secret in the environment (not in `config.toml`) avoids committing it to git. Add the export to your shell profile if you want it available in every new terminal. ### 3. Run Codex ```bash theme={null} codex ``` Traffic goes to Barndoor on `POST /v1/responses`. Budgets, rate limits, model access policies, and usage reporting apply the same way as for any other gateway client. When a budget or rate limit blocks a request, Codex shows "You've hit your usage limit. Try again at …" with the time the limit lifts, if it is known, and does not retry. ## Configure Codex Desktop Codex Desktop uses the same provider configuration as the CLI. Custom providers are selected by `model_provider` / `model` in config — the in-app model picker may not list custom gateway models the way it lists built-in ones. 1. Put the same `model_provider`, `model`, and `[model_providers.barndoor]` block in `~/.codex/config.toml` (or in `$CODEX_HOME/config.toml` if you set `CODEX_HOME`). 2. Make `BARNDOOR_API_KEY` available to the Desktop process. Dock / Spotlight launches on macOS typically do **not** inherit exports from `.zshrc` or `.zprofile`. Prefer one of: * Start Desktop from a terminal after exporting the key (for example `export BARNDOOR_API_KEY="bd-…" && open -a "Codex"` — use the exact app name on your machine). * A small wrapper script that exports the key, then launches the app. 3. Fully quit and relaunch Desktop so it reloads `config.toml`. Routing follows the `model_provider` and `model` you set. You shouldn't need to pick "Barndoor" from a provider menu. > [!WARNING] > > If Desktop starts without `BARNDOOR_API_KEY` in its environment, requests fail auth even when the same key works in the CLI. Confirm the launch path actually exports the variable — a terminal-only `export` does not help a Dock-launched app. ## ChatGPT subscriptions (OpenAI Codex OAuth providers) The setup above works for providers with a stored credential, such as an OpenAI API key. Your admin can also add an **OpenAI Codex OAuth** provider under **LLM Management → Providers**, which bills each request against the developer's own ChatGPT subscription instead. Barndoor stores no OpenAI credential for it. A request to a Codex OAuth provider must carry two credentials: * your ChatGPT OAuth token in `Authorization: Bearer …`, which the gateway forwards to OpenAI, and * your Barndoor key in `x-api-key`, which the gateway uses to authenticate you. The `env_key` setup above sends only your Barndoor key, so a request that lands on a Codex OAuth provider fails with `401 OpenAI provider requires an incoming Codex OAuth bearer token`. If your organization runs Codex on ChatGPT subscriptions, launch it with Barndoor Bridge (`barndoor run codex`, or **Launch Codex Desktop** in the Bridge app) instead of configuring it by hand. See [Launching Claude Code or Codex with Barndoor Bridge](/how-tos/connect-tools-to-llm-gateway#launching-claude-code-or-codex-with-barndoor-bridge). > [!NOTE] > > Barndoor Bridge is in early access and may not be enabled for your organization yet. Contact Barndoor to turn it on. ## Smoke-test without Codex Confirm the gateway accepts Responses traffic with your key before debugging Codex itself: ```bash theme={null} curl https://app.barndoor.ai/api/llm-gateway/v1/responses \ -H "Authorization: Bearer bd-…" \ -H "Content-Type: application/json" \ -d '{ "model": "gpt-5.4-mini", "input": "Reply with the single word pong." }' ``` A successful JSON response means the endpoint, key, and model name are fine — remaining issues are almost always Codex `base_url` / `wire_api` / env wiring. ## Troubleshooting | Symptom | Likely cause | Fix | | - | - | - | | `401` / `invalid JWT header: InvalidToken` | `base_url` missing `/v1` | Use `…/api/llm-gateway/v1` | | `401` / `invalid API key` | Wrong, unset, disabled, or revoked `BARNDOOR_API_KEY` | Confirm `env_key` matches the variable you exported. Check the key's status under [**API Keys**](https://app.barndoor.ai/settings/models?section=api-keys), and create a new one if needed | | `404` / `model '…' not found` | `model` doesn't match a name enabled for your organization | Copy an exact name from [**Available Models**](https://app.barndoor.ai/settings/models?section=models) | | Desktop ignores the key | GUI process lacks the env var | Launch Desktop from a shell/wrapper that exports `BARNDOOR_API_KEY` (Dock launches usually will not see `.zshrc` exports) | | Works in `curl` but not in Codex | Wrong `wire_api` or provider block | Set `wire_api = "responses"` under `[model_providers.barndoor]` | | `does not support endpoint /v1/responses` | The model is served by a provider without a Responses API (Anthropic, Bedrock, Vertex, Google AI) | Pick a model from an OpenAI-family provider. See [Which models Codex can use](#which-models-codex-can-use) | | `401` / `requires an incoming Codex OAuth bearer token` | The model is served by an OpenAI Codex OAuth provider | See [ChatGPT subscriptions](#chatgpt-subscriptions-openai-codex-oauth-providers) | | `403` | A model access policy doesn't allow you to use this model | Ask your admin, or pick another name from **Available Models** | ## Related * [Using the LLM Gateway](/how-tos/use-llm-gateway) — overview and architecture * [Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway) — keys, model names, supported endpoints, Cursor, Claude Code, SDKs * [LLM Gateway Quickstart](/how-tos/llm-gateway-quickstart) — admin setup and request reference * [LLM Controls](/how-tos/use-llm-controls) — budgets, rate limits, and model access # Calling Jev Through the Gateway Source: https://docs.barndoor.ai/how-tos/use-jev-classifier Call TypeSafe's Jev classifier through the Barndoor LLM Gateway with TypeSafe's own SDKs, so classification traffic gets the same API keys, budgets, audit trail, and usage reporting as your chat models. [Jev](https://docs.typesafe.ai/) is TypeSafe's **System One** model. It is a classifier, not a chat model: you send it some content (the `state`) and a set of typed questions, and it answers each question with probabilities. For example, "is this ticket about billing?" comes back as `0.97`, not as a sentence. The gateway serves Jev on TypeSafe's own endpoint, `POST /v1/systemone`, with TypeSafe's request and response format unchanged. So TypeSafe's Python and JavaScript SDKs work against Barndoor once you change their base URL and API key. > [!NOTE] > > Jev answers **only** on `/v1/systemone`. It does not answer `/chat/completions`, `/responses`, or `/messages`. On **My Models**, Jev routes and models carry a **Classifier** badge so they aren't mistaken for chat models. ## Before you start An admin needs to make Jev available in **LLM Management**. There are two ways to serve it: * **TypeSafe AI provider.** Add the **TypeSafe AI** provider with a TypeSafe API key from the [TypeSafe console](https://console.typesafe.ai/), and enable `jev-latest`, or a pinned version such as `jev-1.13.0` if you need answers that don't change when TypeSafe releases a new model. * **OpenRouter.** OpenRouter also serves Jev, as `~typesafe/jev-latest`. Enable that model on an OpenRouter provider. Optionally, create a **model route** for Jev (for example `jev`) so callers use one stable name, and the route can fail over between TypeSafe and OpenRouter. A few rules apply, and the gateway enforces them when you save: * **A route holds Jev or chat models, never both.** A request that failed over from one kind to the other would fail, so the gateway refuses a mixed route. In the **Create Model Route** and **Add Targets** dialogs, models of the other kind are disabled. * **Jev can't be a routing-policy slot.** A slot has to answer chat. * **Jev can be a routing policy's determiner.** See [Routing Policies](/how-tos/llm-routing-policies#using-jev-as-the-determiner). ## Find the name to call Open **Settings → My Models**. A Jev route, or a Jev model listed under **Standalone Models**, carries a **Classifier** badge. Use its name in the `model` field: the route name (for example `jev`), or `/` for a standalone model. The copy button next to each name gives you the exact string. When you can see a Jev model, **Gateway Endpoint** also lists the System One URL: ```text theme={null} https://app.barndoor.ai/api/llm-gateway/v1/systemone ``` ## Call Jev Authenticate with a Barndoor gateway API key (`bd-…`), the same as for chat models. TypeSafe's SDKs add `/v1/systemone` themselves, so give them the gateway URL **without** `/v1`: `https://app.barndoor.ai/api/llm-gateway`. > [tab] Python > > Install TypeSafe's SDK with `pip install typesafe-sdk` (or `uv add typesafe-sdk`). > > ```python theme={null} > import os > > from typesafe_sdk import Noul, TypeSafeClient > > with TypeSafeClient( > api_key=os.environ["BARNDOOR_API_KEY"], > base_url="https://app.barndoor.ai/api/llm-gateway", > model="jev", # your Jev route, or "/jev-latest" > ) as client: > result = client.system_one( > "I was charged twice. Please fix this ASAP.", > {"billing": Noul(instructions="Is this ticket about billing?")}, > ) > print(result.nouls["billing"].noul) > ``` > > You can also set `TYPESAFE_BASE_URL` and `TYPESAFE_API_KEY` in the environment instead of passing them. > [tab] JavaScript > > Install TypeSafe's SDK with `npm install @typesafe-ai/sdk` (Node.js 20 or newer). > > ```ts theme={null} > import { choice, TypeSafeClient } from "@typesafe-ai/sdk"; > > const client = new TypeSafeClient({ > apiKey: process.env.BARNDOOR_API_KEY, > baseURL: "https://app.barndoor.ai/api/llm-gateway", > defaultModel: "jev", // your Jev route, or "/jev-latest" > }); > > const response = await client.systemOne({ > state: { document: "I was charged twice. Please fix this ASAP." }, > questions: { > category: choice("What is this ticket about?", { > billing: null, > technical: null, > other: null, > }), > }, > }); > > console.log(response.answers.category.choice); > ``` > [tab] cURL > > ```bash theme={null} > curl https://app.barndoor.ai/api/llm-gateway/v1/systemone \ > -H "Authorization: Bearer $BARNDOOR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "model": "jev", > "state": "Help! My payouts have been failing for 3 days.", > "questions": { > "is_urgent": { "type": "noul", "instructions": "Does this convey urgency?" } > } > }' > ``` Replace `app.barndoor.ai` with your own Barndoor host if you have one. The request body and the answers are TypeSafe's format: see TypeSafe's [API reference](https://docs.typesafe.ai/api) for the question types (`noul`, `choice`, `score`) and how to read the answers. ## Usage and cost Jev requests appear in LLM usage reporting like any other model, with the same user, API key, and budget attribution. TypeSafe charges for input tokens only, so Jev's output tokens are recorded but priced at zero. ## Troubleshooting > [accordion] A Jev model fails when called from a chat client > > Jev answers only on `/v1/systemone`. Sending its name to `/chat/completions`, `/responses`, or `/messages` returns a `400` saying the provider does not support that endpoint and to send Jev to `POST /v1/systemone`. Call it with TypeSafe's SDK or the `/v1/systemone` endpoint instead. > [accordion] The SDK gets a 401 with "invalid JWT header" > > Check the base URL. TypeSafe's SDKs add `/v1/systemone` themselves, so a base URL ending in `/v1` sends the request to `/v1/v1/systemone`, which isn't a gateway API path, and the gateway rejects your API key there. Use `https://app.barndoor.ai/api/llm-gateway`. > [accordion] I can't add Jev to an existing route > > That route holds chat models, and a route can't mix the two. Create a separate route for Jev. # Configuring LLM Controls Source: https://docs.barndoor.ai/how-tos/use-llm-controls Set token and spending budgets, rate limits, and model access policies on traffic flowing through the Barndoor LLM Gateway. ## Overview Once your LLM Gateway is set up — see [Using the LLM Gateway](/how-tos/use-llm-gateway) — the **Controls** group of **LLM Management** is where admins govern how the people, keys, and agents in their organization consume it: capping spend, throttling busy callers, and deciding who may use which models. ![The Controls group of the LLM Management hub showing the Budgets, Rate Limits, and Model Access sections](https://mintcdn.com/barndoor/aNN2f2MGdwSwBA-w/images/llm-controls/01-llm-controls-tabs.gif?s=da6a1211b0fa64eae32f964ccd88d7b9) The **Controls** group has three sections: | Section | What it does | | - | - | | **Budgets** | Cap the tokens and/or dollars a scope may spend per day, week, or month, optionally narrowed to one provider, provider model, model route, or routing policy. Block requests once exhausted, or warn only. | | **Rate Limits** | Cap requests per minute and/or tokens per minute over a rolling 60-second window, optionally narrowed the same way. | | **Model Access** | Allowlist or denylist routes, models, providers, and route groups for a scope, and choose whether models are open by default or require an explicit grant. | > [!NOTE] > > Per-request usage and cost reporting lives separately, under **Reporting → LLM Usage Dashboard** — see [Reading the LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard). ## Before You Begin You'll need: * A Barndoor account with **admin** privileges. * An LLM Gateway with at least one provider and one model route — see [Using the LLM Gateway](/how-tos/use-llm-gateway). * Nothing extra for **spending budgets**: Barndoor prices requests from its managed default catalog automatically. Add your own prices under **LLM Management → Model Pricing** only to override those defaults or to price a model the catalog doesn't cover. See [Managing Model Pricing](/how-tos/manage-model-pricing). ## Key Concepts Budgets and rate limits share the same two independent dimensions. Model access policies use the first one. ### Scope: who a rule applies to | Scope | Applies to | | - | - | | **Organization** | Every request in the organization. | | **Group** | Callers in an identity-provider group. | | **Role** | Callers holding an identity-provider role. | | **User** | A person, through any of their API keys. | | **API Key** | Requests authenticated with a particular key. | | **AI Agent** | Requests made with an API key bound to an AI agent. Keys not bound to an agent never match. | For every scope except **Organization** you can pick one specific entity, or leave the picker on **All users** / **All groups** / etc. Leaving it blank does **not** create one shared pot: * **User, API Key, AI Agent** left blank: *each* user, key, or agent gets their own allowance equal to the limits you set. * **Group, Role** left blank: each group or role gets one allowance, **shared by everyone in it**. A **User** budget or rate limit left on *All users* can additionally be narrowed with **Limit to group**. Every member of that group then gets their own allowance, and anyone who joins the group picks it up on their next request with no admin action. Compare this with a **Group** scope, which pools one allowance across all members. ### Target: what a rule counts By default a budget or rate limit counts **All targets**. Set a **Target** to count only matching traffic: | Target | Counts only… | | - | - | | **All targets** *(default)* | Everything in scope. | | **LLM Provider** | Requests served by one provider connection. Optionally pick an **Upstream model** to count only that model on that provider (leave it blank for the entire provider). | | **Model Route or Routing Policy** | Requests whose `model` field names this route or routing policy. | **Scope and Target combine**: a rule scoped to *User: Ada* with Target *LLM Provider: OpenAI* counts only Ada's traffic that OpenAI serves. > [!NOTE] > > A **Model Route or Routing Policy** target matches the name the caller sent in `model` — before the gateway routes it — not the model it ended up on. A routing policy target therefore counts every request for that policy, pooled across all of its slots. To cap a specific underlying model regardless of which route reached it, target **LLM Provider** with an **Upstream model** instead. > [!NOTE] > > Routing policies appear in the target picker only when your organization has routing policies enabled. That feature may not be enabled for your organization yet — contact Barndoor. See [Routing Policies](/how-tos/llm-routing-policies). ## How Limits Compose Governance runs on `/v1/chat/completions`, `/v1/completions`, `/v1/embeddings`, `/v1/responses`, and `/v1/messages`. (`/v1/models` and `/v1/messages/count_tokens` are not metered.) Checks run in a fixed order; the first denial stops the request. Inbound requestEvery request1**API-key auth**The `bd-…` key is valid, active, and not revoked401 2**Rate limits with no Target**Requests and tokens per window429 3**Budgets with no Target**Token budgets, then spending budgets429 4**Model resolution**The model maps to a route or provider model404 5**Model access policies**Allowlists and denylists for this caller403 · 503For each route in the plan6**Rate limits with a Target**Matching routes are droppedDrop route 7**Blocking budgets with a Target**Matching routes are droppedDrop route Forward**Send to the first remaining route**Usage is recorded from the tokens the provider reports429 if none left4xx Request refusedDrop route Route skipped, others still tried Things worth knowing about this chain: * **Usage is recorded after the upstream responds**, from the token counts the provider reports. Tokens counted are input (including cache reads and cache writes) plus output (which includes reasoning tokens). The pre-check enforces the limit; the recording keeps the counter accurate. * **Every applicable rule is checked, and the most restrictive result wins.** A user covered by an org budget and a user budget is checked against both, and both are debited. * **A more specific rule overrides a broader one of the same scope type and target.** For example, a *User: Ada* budget replaces the *All users* budget for Ada alone, and a **Limit to group** budget replaces the *All users* budget for that group's members. This lets you *raise* one person's or one group's allowance above the default. Rules of different scope types (say, Organization and User) don't override each other — both apply. * **Rules with a Target fail over instead of hard-blocking.** When a targeted budget or rate limit is exhausted, the gateway removes just the matching routes from the request's route plan and tries the remaining ones. The caller sees a `429` only when every eligible route is blocked. See [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns). * **Controls fail open on a transient outage.** If the usage store can't be reached within 2 seconds, budgets and rate limits are skipped for that request rather than blocking live traffic. Model access is the exception — see [Model Access](#model-access). *** ## Budgets Budgets cap how much a scope may consume in a calendar period. A budget can cap **tokens**, **spending**, or **both** — whichever limit is hit first triggers the action. ![LLM Budgets section listing budgets with token and spending usage bars](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/02-budgets-list.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=df81f81f427e51e2d50a870daa25cf8f) The **LLM Budgets** list shows each budget's **Usage** (a TOKENS and/or COST bar), **Status**, **Period**, **Resets in**, **On exhaust**, **Created**, **Last Updated**, and an **Enabled** toggle. Usage refreshes about every 10 seconds. You can search by name, scope, target, or period, and sort by any header; the default sort is **Usage**, highest first, so budgets closest to exhaustion float to the top. * **Status** shows an amber `NN%` pill once usage crosses one of the budget's alert thresholds, and a red **Exhausted** pill at 100%. * **Per-member budgets** (a blank entity at any scope other than Organization) have no single usage figure. Their row reads **Per member — expand for usage**; click the chevron at the left of the row to see each member's usage and breach status. ### Creating a budget **1. Open LLM Management → Budgets and click Create Budget** **2. Name, period, and scope** * **Name** — shown in the denial message callers receive and in alerts, so make it recognizable (for example `Engineering monthly`). * **Period** — **Daily**, **Weekly**, or **Monthly** (default). * **Scope** — see [Scope](#scope-who-a-rule-applies-to). Pick an entity, or leave it on *All …* for per-member allowances. For a **User** scope left on *All users*, optionally set **Limit to group**. **3. Action on Exhaust and alerts** * **Action on Exhaust** — **Block Requests** (default) returns `429` once the limit is reached. **Warn Only** keeps serving requests and only raises alerts. * **Alert Thresholds (%)** — comma-separated percentages of the limit at which to raise an alert, for example `80, 90` (the default). Leave blank for none. **4. Target (optional)** Leave on **All targets**, or narrow the budget as described in [Target](#target-what-a-rule-counts). Only **Block** budgets remove targeted routes; a **Warn Only** budget with a Target only alerts. **5. Budget type and limits** * **Budget Type** — **Tokens Only**, **Spending (\$) Only** (default), or **Both (first hit)**. * **Token Limit** — total tokens allowed in the period. * **Spending Limit (\$)** — a USD cap, costed from [model pricing](/how-tos/manage-model-pricing). * **Reason for change (optional)** — a note recorded in the audit trail. **6. Click Create** ![Create Budget dialog with name, period, scope, action, target, and limits filled in](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/03-create-budget_v2.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=9031126dee4023fd94794708eadf5a40) When editing a budget you can change its name, period, action, budget type, limits, and thresholds. **Scope and Target can't be changed** after creation — delete the budget and create a new one. > [!WARNING] > > A **spending** limit on a budget targeted at a provider whose **Calculate token cost** setting is off never fills up, because that provider's requests are recorded at \$0. The dialog warns you when this applies; use a token limit instead. ### How budgets are counted and reset * **Tokens** — input tokens (including cache reads and writes) plus output tokens, as reported by the provider. * **Spending** — the request's cost from [Model Pricing](/how-tos/manage-model-pricing), including cache and long-context rates. Requests that cost \$0 (unpriced models, providers that don't calculate token cost) don't move a spending counter. * **Reset** — every period boundary is **UTC**, with no per-organization override: **Daily** at 00:00 UTC, **Weekly** on Monday at 00:00 UTC, **Monthly** on the 1st at 00:00 UTC. The **Resets in** column shows the countdown, and its tooltip gives the exact UTC instant. ### Alerts Barndoor raises admin alerts from each budget's own thresholds: * **Threshold alert** (warning) — when usage crosses one of the configured percentages. * **Exhausted alert** (critical) — on a **Block Requests** budget, as soon as the request that crosses 100% completes. That request is still allowed to finish; the next one is blocked. Token and spending limits alert separately. Each alert is sent at most once per day per budget and threshold, and on a per-member budget, once per member, naming the member. Alerts link straight to the budget in the list (and open the member's row on a per-member budget). ### When a caller hits a budget A **Block Requests** budget with no Target returns: ```http theme={null} HTTP/1.1 429 Too Many Requests content-type: application/json ``` ```json theme={null} { "error": { "message": "Token monthly budget exhausted (budget: Engineering monthly) (100% used: 1001234 / 1000000 tokens).", "type": "budget_exhausted", "code": null } } ``` A spending budget reads `Spending monthly budget exhausted (budget: Engineering monthly) (100% used).` When a budget **with a Target** has removed every eligible route, the `429` has the same `type` and a message naming each blocked route, for example: ```text theme={null} All routes for model 'claude-sonnet' are blocked by exhausted budgets: Anthropic cap (token budget on Anthropic/claude-sonnet-5-5, 100% used) ``` > [!NOTE] > > `tokens_used` is often slightly **above** the limit in the message. The gateway checks the counter before forwarding and debits actual usage after the provider responds, so the request that crosses the limit finishes and the next one is denied. The percentage is rounded, so 1,001,234 / 1,000,000 prints as `100%`. > [!TIP] > > Tokens give predictability; spending tracks dollars across models with different prices. **Both (first hit)** is the safest configuration: the token cap absorbs a price change, and the spending cap catches an expensive model nobody noticed. *** ## Rate Limits Rate limits cap throughput on a **rolling 60-second window**. Use them to smooth bursts and stop one noisy caller or runaway loop from crowding out everyone else. (Use budgets to control total consumption over a day, week, or month.) ![LLM Rate Limits section listing policies with live RPM and TPM usage](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/04-rate-limits-list.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=e8912ba2414c4028cee532feedaed613) The **LLM Rate Limits** list shows **Live (60s)** usage, **Scope**, **Req/min**, **Tokens/min**, **Traffic**, **Last Updated**, and **Enabled**, refreshed about every 10 seconds. The default sort is **Live (60s)**, so policies closest to their limit surface first. A policy that gives each caller their own window (a blank entity) has a chevron to expand per-caller usage. ### Creating a rate limit **1. Open LLM Management → Rate Limits and click Create Policy** **2. Name and scope** * **Name** — appears in the denial message. * **Scope** — see [Scope](#scope-who-a-rule-applies-to), including **Limit to group** for a **User** scope left on *All users*. **3. Target (optional)** Leave on **All targets**, or narrow the policy as described in [Target](#target-what-a-rule-counts). While a targeted limit is exceeded, only the matching routes stop serving. **4. Limits** Set **Requests / min**, **Tokens / min**, or both. At least one is required. **5. Click Create** ![Create Rate Limit Policy dialog with name, scope, target, and limits](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/05-create-rate-limit.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=2a20b5941f94d8fc768987510395b5d5) Unlike budgets, a rate limit's scope and target **can** be edited later. (The one exception: a policy using **Limit to group** has its scope locked.) > [!NOTE] > > Older policies may show a scope of **Model** or **LLM Provider**. Those scopes never enforced correctly, and the edit dialog says so. Recreate them with the identity as **Scope** and the model route or provider as **Target**. ### When a caller hits the limit ```http theme={null} HTTP/1.1 429 Too Many Requests retry-after: 60 content-type: application/json ``` ```json theme={null} { "error": { "message": "Rate limit exceeded (policy: Sales-team rate cap). Try again in 60 seconds.", "type": "rate_limit_error", "code": null } } ``` A targeted rate limit that blocks every route returns `429` `rate_limit_error` with `Retry-After: 60` and a message like `All routes for model 'gpt-5.5' are blocked by rate limits: …`. > [!NOTE] > > `Retry-After` is always the full window length, 60 seconds: waiting that long is guaranteed to clear the window, though callers often succeed sooner as older requests age out. The OpenAI and Anthropic SDKs honor it automatically. > [!TIP] > > Requests per minute and tokens per minute are enforced independently. A caller under the request cap can still be throttled by the token cap, and vice versa. Token usage is recorded after each response, so a single very large request can overshoot the token limit before the next one is refused. *** ## Model Access Model access policies decide whether a caller may use a route at all. The section has two parts: an org-wide **posture** and a list of **Model Access Policies**. ![Model Access section with the posture card above the list of allowlist and denylist policies](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/06-model-access-list.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=1d3e9160d043bbe12f17201cccb2a1e7) ### Posture: open or locked down The card at the top of the section, **Require an explicit grant to use a model**, sets what happens to a route that no policy mentions: | Posture | Badge | Meaning | | - | - | - | | Off *(default)* | **Open** | Any model or route you set up is usable by everyone in the organization unless a policy restricts it. | | On | **Locked down** | A model is usable only where an allowlist policy grants it. New models and routes are unusable until granted. | Turning it on asks for confirmation, and warns you if no allowlist exists yet — in that state every request would be denied, including your own. > [!WARNING] > > Allowlists only ever **narrow** access in the Open posture — they never grant anything beyond it. To make "no grant, no access" the rule, switch the posture on. ### Creating a policy **1. Open LLM Management → Model Access and click Add Policy** **2. Name, policy type, and scope** * **Name** — appears in the denial message. * **Policy Type** — **Allowlist** (only these targets are allowed) or **Denylist** (these targets are blocked). * **Scope** — Organization, Group, Role, User, API Key, or AI Agent. Leaving the entity blank applies the policy to every entity of that type. **3. Add targets** Pick a kind under **Add a target**, choose a value, and click **Add target**. Mix any number of targets: | Target kind | Matches when… | | - | - | | **Model Route or Routing Policy** | The caller's `model` names this route or routing policy (a `provider/` prefix is ignored). | | **Model** | The route resolves to this underlying model, whichever route name the caller used. | | **Provider** | The route is served by this provider. | | **Provider + Model** | This route name is served by this specific provider. | | **Route Group** | The route belongs to this route group — so routes added to the group later are covered automatically. | Model, route, and provider + model values accept a trailing `*` wildcard (for example `claude-*`). **4. Save** The policy appears in the list. Use its **Enabled** toggle to switch it off without deleting it. ![Create Model Access Policy dialog with a Route Group target added](https://mintcdn.com/barndoor/pezu-dQLTMUCjAX8/images/llm-controls/07-create-model-access.png?fit=max\&auto=format\&n=pezu-dQLTMUCjAX8\&q=85\&s=dbf0943f567146ef59b39a4c4eb98efd) ### How policies combine Model access has no "more specific overrides broader" rule — every policy whose scope matches the caller is evaluated together: 1. If **any** matching denylist matches the route, the route is denied. 2. Otherwise, if **any** allowlist applies to the caller, at least one of them must grant the route. 3. Otherwise the **posture** decides: allowed when Open, denied when Locked down. Policies are evaluated per route. If a route name fans out to several providers and only some are denied, the request proceeds on the allowed ones — a denied provider is never used, not even for failover. The caller sees a `403` only when no route survives. > [!NOTE] > > **Provider** targets are deliberately asymmetric. In a **denylist**, a provider covers everything routed to it, including custom route names. In an **allowlist**, it grants only the provider's own models — to grant a custom route name that points at the provider, add it as a **Model Route** or **Provider + Model** target. ### When a caller is denied ```http theme={null} HTTP/1.1 403 Forbidden content-type: application/json ``` ```json theme={null} { "error": { "message": "Model 'claude-opus-5-5' is blocked by access policy: External-models-only", "type": "permission_error", "code": null } } ``` The message depends on why the route was refused: | Reason | Message | | - | - | | A denylist matched | `Model '' is blocked by access policy: ` | | No applicable allowlist granted it | `Model '' is not allowed by access policy: ` | | Locked-down posture, nothing granted it | `Model '' has not been granted to you. This organization requires an explicit model access grant.` | > [!NOTE] > > Model access **fails closed**. If Barndoor can't read the organization's posture when a decision depends on it, the request is refused with `503` `service_unavailable_error` ("Model access posture for this organization is temporarily unavailable…"), never silently allowed. A matching denylist or granting allowlist is still honored during such an outage. *** ## Governance settings Three org-wide switches sit alongside the controls. Each takes effect on the next request. | Setting | Where | Default | | - | - | - | | **Require an explicit grant to use a model** | **Model Access** | Off (Open) — see [Posture](#posture-open-or-locked-down). | | **Require pricing for Model Routes** | **Model Pricing** | Off — see [Managing Model Pricing](/how-tos/manage-model-pricing#require-pricing-for-model-routes). | | **Require requests to use a routing policy** | **Routing Policies** | Off. When on, requests must name a routing policy; naming a model or route directly is refused. Model access, budgets, and rate limits still apply. See [Routing Policies](/how-tos/llm-routing-policies); the feature may not be enabled for your organization yet — contact Barndoor. | *** ## What callers see when something is denied | Response | Triggered by | Example message | | - | - | - | | **401** `authentication_error` | Missing, invalid, or revoked API key | `invalid API key` | | **403** `permission_error` | Model access policy or locked-down posture | `Model 'foo' is not allowed by access policy: Production-only` | | **404** `not_found_error` | The `model` field doesn't resolve to a route | `model 'foo' not found or not available` | | **429** `rate_limit_error` | A rate limit (`Retry-After: 60`) | `Rate limit exceeded (policy: Sales-team rate cap). Try again in 60 seconds.` | | **429** `budget_exhausted` | A **Block Requests** budget | `Token monthly budget exhausted (budget: Engineering monthly) (100% used: 1001234 / 1000000 tokens).` | | **503** `service_unavailable_error` | Model access posture temporarily unreadable | `Model access posture for this organization is temporarily unavailable, …` | Denials use the error shape of the endpoint you called, so common LLM SDKs surface them as ordinary errors. OpenAI endpoints use `{ "error": { "message", "type", "code" } }`. `/v1/messages` and `/v1/messages/count_tokens` use Anthropic's envelope for every denial in this table, including the `401`: `{ "type": "error", "error": { "type", "message" } }`. On `/v1/responses`, the two `429`s also change `type`. Rate-limit and budget denials return `"type": "usage_limit_reached"`. The value in the table (`rate_limit_error` or `budget_exhausted`) moves to `code`, and `resets_at` gives the Unix time (in seconds) when the limit lifts. A budget denial omits `resets_at` when its reset time isn't known. Codex shows the message of a `429` only when its type is `usage_limit_reached`, as "You've hit your usage limit. Try again at …". If your own client calls `/v1/responses`, read `code` to tell the two denials apart: ```json theme={null} { "error": { "message": "Token monthly budget exhausted (budget: Engineering monthly) (100% used: 1001234 / 1000000 tokens).", "type": "usage_limit_reached", "code": "budget_exhausted", "resets_at": 1793491200 } } ``` *** ## Troubleshooting > [accordion] A user keeps getting 429s — which rule is responsible? > > Read `error.message`: it names the rule — `(policy: …)` for a rate limit, `(budget: …)` for a budget, or a list of blocked routes for a targeted rule. Open that rule to check its configuration and live usage. For a per-member rule, expand the row to find the user. > [accordion] A budget reset later than I expected > > Budget periods roll over at **midnight UTC**, not local time: daily at 00:00 UTC, weekly on Monday, monthly on the 1st. The **Resets in** column's tooltip shows the exact UTC instant. > [accordion] Everyone in a group is sharing one allowance, but I wanted one each > > A **Group** scope pools one allowance across all members. To give each member their own, use **Scope: User**, leave it on *All users*, and set **Limit to group** to that group. > [accordion] An AI Agent budget or rate limit never moves > > Agent-scoped rules only match requests made with an API key bound to that agent. Traffic on an unbound key isn't counted. > [accordion] My model access policy isn't firing > > Check the policy's **scope** and that it's **enabled**. Remember that in the Open posture an allowlist only restricts the callers it applies to — everyone else is unaffected. Wildcards must be trailing: `claude-*` works, `*-mini` doesn't. > [accordion] A spending budget stays at \$0 > > Either the models being called have no price (neither your rules nor Barndoor's defaults cover them), or the budget targets a provider whose **Calculate token cost** setting is off. See [Managing Model Pricing](/how-tos/manage-model-pricing). > [accordion] I want to know who's close to a budget > > Set **Alert Thresholds** (default `80, 90`) to be alerted before the budget blocks anyone. The **Status** column shows breached thresholds at a glance, and **Reporting → LLM Usage Dashboard** shows consumption trends. ## Frequently Asked Questions > [accordion] When should I use a budget vs a rate limit? > > Use a **budget** for total consumption over a long horizon (a team's monthly spend). Use a **rate limit** for short-term load (smoothing bursts, stopping a runaway loop). They compose: a budget for *how much*, a rate limit for *how fast*. > [accordion] Can I give one user more than the default allowance? > > Yes. Create the default as a **User** rule on *All users*, then a second rule for **User: that person** with the same Target and a higher limit. The specific rule replaces the default for that user only. The same works for a group of users via **Limit to group**. > [accordion] Do controls apply to embeddings? > > Yes. Embedding requests count tokens against budgets and rate limits and are subject to model access, like chat requests. > [accordion] Are warn-only budgets useful? > > Yes — they record usage and raise threshold alerts without blocking anyone. A common pattern is to run a budget in **Warn Only** for a period or two to calibrate the limit, then switch it to **Block**. > [accordion] How can I test a policy without disrupting other users? > > Scope it tightly — a single test **User** or a dedicated **API Key** — and call the gateway with that user or key. Widen the scope once you're happy with the behavior. ## Need Help? Reach out to [support@barndoor.ai](mailto:support@barndoor.ai) with: * The name of the budget, rate limit, or policy involved. * The exact `error.message` returned to the caller (if any). * The scope and target of the rule. # Using the LLM Gateway Source: https://docs.barndoor.ai/how-tos/use-llm-gateway Send LLM traffic from Cursor, Claude Code, Codex, your apps, and the OpenAI / Anthropic SDKs through the Barndoor LLM Gateway. ## Overview The Barndoor **LLM Gateway** is a proxy that sits between your AI tools and one or more upstream LLM providers. It speaks the **OpenAI** API (Chat Completions, Completions, Responses, Embeddings) and the **Anthropic Messages** API natively, so most clients — the OpenAI and Anthropic SDKs, Cursor, Claude Code, Codex, LangChain, and similar tools — work by pointing their base URL at Barndoor. Pointing your client at the gateway gives you a single endpoint that: * **Centralizes provider credentials** — provider API keys and cloud roles stay in Barndoor, never on developer machines. * **Enforces governance** — token and spending budgets, rate limits, and per-user / per-group model access policies. * **Routes intelligently** — named model routes with ordered fallbacks, automatic retries on upstream 429s, and health-aware failover. * **Records usage** — per-request tokens, cost, and request duration, reported on the [LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard). > [!NOTE] > > Anything that speaks the OpenAI API can use the gateway by setting its base URL. Clients built on Anthropic's Messages API (for example **Claude Code**) talk to the gateway directly as well. See [Supported Endpoints](#supported-endpoints). ## Architecture at a Glance Your clients Cursor Claude Code Codex SDKs curl `bd-…` API key · OpenAI or Anthropic JSON Barndoor LLM Gateway
  1. 1**Authenticate**Barndoor API key, user and org
  2. 2**Rate limits & budgets**Requests, tokens, and spend
  3. 3**Model access**Allow and deny policies
  4. 4**Route**Model routes, retries, failover
Every request's tokens, cost, and duration are recorded to the LLM Usage Dashboard Provider credentials, stored encrypted OpenAI Anthropic Azure OpenAI / Microsoft Foundry AWS Bedrock Google Vertex AI Google AI (Gemini) xAI (Grok) …and more Upstream providers ## Key Concepts The gateway is configured from a small set of building blocks. Each one references the one above it. | Concept | What it is | | - | - | | **Credentials** | A saved secret or identity that authorizes Barndoor against an upstream account — an API key, an AWS IAM role, a Google service account, an Entra ID service principal. Stored encrypted and never returned to the browser. | | **Provider** | A named upstream connection that uses one set of credentials. The provider carries the settings that decide how requests are sent — for example which model API family it targets, whether a failing health check blocks traffic, and whether token cost is calculated. | | **Model** | An upstream model enabled on a provider, such as `gpt-5.4-mini` on your OpenAI provider. Enabling a model makes it callable as `/`. | | **Model Route** | A client-facing model name that maps to one or more provider models, tried top to bottom as fallbacks. This is the name most callers put in the `model` field. | | **API key** | A `bd-…` key that callers send to authenticate. A key belongs to a user, a group, or the whole organization, and governance policies apply based on who the key belongs to. | ### Credentials and providers Credentials and providers are separate on purpose: **one set of credentials can back many providers.** You might save a single OpenAI key and create two providers from it — one for everyday traffic and one reserved for a specific team — or save one AWS IAM role and create a provider for each Bedrock API family you use. The split follows what each object is responsible for: * **Credentials** hold what authorizes the account: the key or identity, and the account-level location such as the base URL, AWS region, or GCP project. Rotating a key on the credentials updates every provider that uses it. * **Providers** hold how requests are made: the **Model API Family** (for AWS Bedrock, Google Vertex AI, and Microsoft Foundry), health-check enforcement, catalog model sync, and billing. Because many providers can share one set of credentials, usage and cost are reported per provider, not per credential. ### Models and routes A model has to be **enabled on a provider** before anything can call it. Once enabled, it is reachable by its provider-prefixed name (for example `OpenAI Prod/gpt-5.4-mini`, using the provider's name). A **Model Route** gives one or more enabled models a single plain name (for example `gpt-5.4-mini` or `team-coding-model`) and an order to try them in. If the first target fails with a failover-eligible error, the gateway tries the next. See [Model Naming](/how-tos/llm-gateway-quickstart#model-naming) for how the gateway reads the `model` field, and [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns) for when it moves to the next target. ### Routing policies A **routing policy** is a virtual model name that picks a model per request — routing each request to the cheapest model strong enough for it, from an ordered list of options — and **routing rules** constrain that choice for particular kinds of request. See [Routing Policies](/how-tos/llm-routing-policies). > [!NOTE] > > Routing policies may not be enabled for your organization yet — contact Barndoor if you don't see **Routing Policies** in **LLM Management**. ## Where Things Live in the Portal | Area | Who sees it | What's there | | - | - | - | | **LLM Management** | Admins | The configuration hub: **Credentials** and **Providers** (Connections); **Models**, **Model Pricing**, **Model Routes**, **Client settings**, **Routing Policies**, and **Routing Rules** (Models); **API Keys** and **Key Policies** (Access — see [Managing LLM API Keys](/how-tos/manage-llm-api-keys)); **Budgets**, **Rate Limits**, and **Model Access** (Controls). | | **Reporting → LLM Usage Dashboard** | Admins | Per-request usage, cost, and duration across the organization — see [Reading the LLM Usage Dashboard](/how-tos/read-llm-usage-dashboard). | | **Settings → My Models** | Every user | **Available Models** (the model names you can call), **Gateway Endpoint** (your base URLs), and **API Keys** (create, rotate, disable, and revoke your own `bd-…` keys). | Some sections of **LLM Management** appear only when the related feature is enabled for your organization: * **Client settings** govern the native capabilities of Claude Code and Codex sessions launched with Barndoor Bridge. See [Client settings](/how-tos/barndoor-bridge/client-settings). * **Routing Policies** and **Routing Rules** — see [Routing policies](#routing-policies). * **Key Policies** limits how long the keys users create for themselves may live. See [Managing LLM API Keys](/how-tos/manage-llm-api-keys#limit-key-lifetimes-with-key-policies). * In some organizations, the separate **Models** section is replaced by a **Models** panel on each provider's detail page (click the provider's name on **Providers**). The controls are the same. If a section described here is missing, contact Barndoor to have it enabled. ## Supported Providers Pick these from **Providers → Add Provider**. Cards marked **Official** come from Barndoor's provider catalog, with default base URLs and model lists pre-filled. | Provider | Authentication | | - | - | | **OpenAI** | API key | | **OpenAI Codex OAuth** | Forwards each developer's own ChatGPT sign-in from Codex — see [Use Codex with the LLM Gateway](/how-tos/use-codex-with-llm-gateway) | | **Anthropic** | API key | | **Anthropic OAuth** | Forwards each developer's own Claude sign-in from Claude Code — see [Anthropic OAuth passthrough](/how-tos/llm-gateway-quickstart#step-1-add-provider-credentials) | | **Azure OpenAI** | API key | | **Microsoft Foundry** | Deployment API key, or Entra ID service principal | | **AWS Bedrock** | AWS IAM role, static AWS keys, or Bedrock API key | | **Google Vertex AI** | Workload Identity / ADC, service account impersonation, or service account key | | **Google AI (Gemini)** | API key | | **Cohere**, **DeepSeek**, **Fireworks AI**, **Groq**, **Mistral AI**, **OpenRouter**, **Perplexity**, **Together AI**, **xAI (Grok)** | API key | | **TypeSafe AI** (Jev classifier) | API key. Serves `/systemone` only; see [Calling Jev Through the Gateway](/how-tos/use-jev-classifier). | | **Custom Provider** | Any OpenAI-compatible endpoint, with your own base URL and API key — including self-hosted models. See [Connect a Self-Hosted Model](/how-tos/connect-self-hosted-model). | ## Supported Endpoints All endpoints live under your gateway base URL, `https://app.barndoor.ai/api/llm-gateway/v1`. | Endpoint | Wire format | Typical clients | | - | - | - | | `POST /chat/completions` | OpenAI Chat Completions | OpenAI SDKs, LangChain, LlamaIndex, Cursor | | `POST /completions` | OpenAI legacy completions | Older OpenAI text-completion clients | | `POST /responses` | OpenAI Responses | Codex, OpenAI Responses API clients | | `POST /embeddings` | OpenAI Embeddings | OpenAI / LangChain embeddings clients | | `POST /messages` | Anthropic Messages | Claude Code, Anthropic SDKs | | `POST /messages/count_tokens` | Anthropic token counting | Claude Code and Anthropic clients that pre-flight token counts | | `GET /models` | OpenAI or Anthropic model list | Any client that lists models on startup | | `POST /systemone` | TypeSafe System One | TypeSafe's SDKs, for the Jev classifier. See [Calling Jev Through the Gateway](/how-tos/use-jev-classifier). | For chat-style traffic, the endpoint a client calls and the provider that serves it are independent: for example, a Claude Code request on `/messages` can be routed to Claude on Anthropic, AWS Bedrock, Google Vertex AI, or Microsoft Foundry. Request examples are in the [Quickstart Guide](/how-tos/llm-gateway-quickstart#sending-requests). ## Authentication Callers authenticate with a Barndoor gateway **API key** (`bd-…`), sent in either header: * `Authorization: Bearer bd-…` — what OpenAI clients send. * `x-api-key: bd-…` — what Anthropic clients send. When both are present, the gateway reads the key from `x-api-key`. That lets Claude Code and Codex send the gateway key in `x-api-key` while passing the developer's own Claude or ChatGPT sign-in token in `Authorization` for the OAuth passthrough providers. There are two ways to get a key: * **Developers** create their own under [**Settings → My Models → API Keys**](https://app.barndoor.ai/settings/models?section=api-keys). Usage is attributed to that user. * **Admins** create keys under **LLM Management → API Keys**, assigned to a user, to a group, or to neither (an organization-wide key, typically for services and CI). The gateway's configuration API (the one behind **LLM Management**) uses your Barndoor login instead of a `bd-…` key — see the [LLM Gateway API](/api-reference/llm-gateway/introduction). ## Before You Begin You'll need: * A Barndoor account with access to **LLM Management** (admins) and/or **Settings → My Models** (any user). * The base URL of your Barndoor portal. Throughout these guides we use `https://app.barndoor.ai` (the Barndoor SaaS host). The authoritative value for your tenant is on the **LLM Gateway Endpoint** card under [**Settings → My Models → Gateway Endpoint**](https://app.barndoor.ai/settings/models?section=endpoint) — copy it from there. * For **admins** setting up the gateway for the first time: an account with at least one upstream provider (OpenAI, Anthropic, AWS, Google Cloud, and so on) and credentials for it. > [!NOTE] > > The LLM Gateway is enabled per organization. If you don't see **LLM Management** or **My Models** in the sidebar, contact your Barndoor admin or [support@barndoor.ai](mailto:support@barndoor.ai) to have it enabled. **LLM Management** is visible to admins only. > [!NOTE] > > **Self-hosted and private-cloud deployments:** if Barndoor runs on your own infrastructure, swap `app.barndoor.ai` for your organization's portal hostname everywhere in these guides. The path (`/api/llm-gateway/v1`) is the same. ## Next Steps **Admins** set the gateway up first — continue to the **[Quickstart Guide](/how-tos/llm-gateway-quickstart)**, which walks through credentials, providers, models, routes, and keys, then sends a first request. After that, layer on: * **[Configuring LLM Controls](/how-tos/use-llm-controls)** — budgets, rate limits, and model access. * **[Managing Model Pricing](/how-tos/manage-model-pricing)** — override Barndoor's default prices. * **[Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns)** — how routes fail over and recover. **Developers** working against an already-configured gateway can go straight to **[Connecting Your Tools to the LLM Gateway](/how-tos/connect-tools-to-llm-gateway)** — getting a key, a model name, and the endpoint, then configuring Cursor, Claude Code, LangChain, and the OpenAI / Anthropic SDKs. For Codex CLI and Codex Desktop specifically, see **[Use Codex with the LLM Gateway](/how-tos/use-codex-with-llm-gateway)**. # Introduction Source: https://docs.barndoor.ai/index Welcome to the Barndoor documentation portal. Explore guides, tutorials, SDKs, code samples, reference docs, and more. ![Hero Light](https://mintcdn.com/barndoor/ZifzlSJyLS7S6A0-/images/arch.svg?fit=max\&auto=format\&n=ZifzlSJyLS7S6A0-\&q=85\&s=a06489c791bc261d40642f5dce0684c9) ### What is Barndoor? Barndoor is a centralized control plane purpose-built for managing Agentic AI. It enables organizations to confidently adopt AI agents across the enterprise — with the assurance that every action is monitored, every request is evaluated, and every agent operates within policy. With Barndoor, governance isn't just reactive — it's intelligent and continuous. ### Start Your Free Trial Ready to experience Barndoor? Sign up for a free trial and get started in minutes. Follow our [Self-Service Trial Guide](/how-tos/trial-guide) for a smooth onboarding experience. [Start Free Trial →](https://app.barndoor.ai/auth/signup/trial) > [card] [Looking for APIs? We've got plenty.](/api-reference/introduction) > > Explore the Barndoor API docs, where you'll find everything you need to > programatically manage MCP governance and the LLM gateway. > [card] [Building apps? Check out our SDKs.](/sdks/introduction) > > Barndoor SDKs are framework-agnostic. Connecting your apps and agents to MCP > servers protected by Barndoor can be done in just minutes. # Mcp servers Source: https://docs.barndoor.ai/mcp-servers/index Loading MCP servers... # CrewAI Source: https://docs.barndoor.ai/sdks/examples/crewAI # Running a CrewAI Agent with Barndoor This guide walks you through how to run a CrewAI task using the Barndoor SDK to connect to an MCP server (like Notion), fetch connection parameters, and use the MCP tools within a CrewAI agent. Feel free to checkout [the repo](https://github.com/barndoor-ai/crew-ai-python-example) here and also run the app with Streamlit for a browser UI demo ## 📹 Demo: Running CrewAI with Barndoor MCP [Embedded content](https://player.vimeo.com/video/1108252984?h=694c676d9f\&badge=0\&autopause=0\&player_id=0\&app_id=58479\&autoplay=1\&loop=1) ## Prerequisites * Python 3.10+ * A Barndoor account * An MCP server registered with Barndoor (connected/authenticated) * AI agent registered with Barndoor ## Source **Code Example** ```python theme={null} import streamlit as st from datetime import datetime from pathlib import Path from dotenv import load_dotenv import barndoor.sdk as bd import asyncio from crewai import Agent, Task, Crew from crewai_tools import MCPServerAdapter # ───────────────────────────────────────────── # Page Config # ───────────────────────────────────────────── st.set_page_config(page_title="Barndoor + CrewAI Assistant", layout="centered", page_icon="Robot") st.title("Barndoor MCP + CrewAI Universal Assistant") st.markdown("Connect any app — Notion, Salesforce, Gmail, Slack, GitHub, Box — and get real results.") # ───────────────────────────────────────────── # Core async function (DO NOT use asyncio.run!) # ───────────────────────────────────────────── async def run_crewai_task(server_slug: str, user_query: str, log): load_dotenv(Path(__file__).parent / ".env") sdk = None try: log("Logging in to Barndoor...") sdk = await bd.login_interactive() log("Logged in!") servers = await sdk.list_servers() server = next((s for s in servers if s.slug == server_slug), None) if not server: raise ValueError(f"Server '{server_slug}' not found.") display_name = ( server.name or getattr(server.mcp_server_directory, "name", None) or server_slug.replace("-", " ").title() ) log(f"Using: **{display_name}**") await bd.ensure_server_connected(sdk, server_slug) params, public_url = await bd.make_mcp_connection_params(sdk, server_slug) # Fix token → authorization (handles both formats) if "token" in params: params["authorization"] = f"Bearer {params.pop('token')}" elif "authorization" in params and not params["authorization"].startswith("Bearer "): params["authorization"] = f"Bearer {params['authorization']}" log("Connected! Loading tools...") with MCPServerAdapter(params) as tools: log(f"Loaded **{len(tools)} tools**") agent = Agent( role=f"{display_name} Expert", goal=f"Complete any task in the user's {display_name} account using real data.", backstory=f"You are a master of {display_name} with full access via Barndoor MCP.", tools=tools, verbose=True, allow_delegation=False, ) task = Task( description=user_query, expected_output="Clear, accurate, well-formatted answer. Use tables/lists when helpful.", agent=agent, ) crew = Crew(agents=[agent], tasks=[task], verbose=True) log("Running task...") result = await crew.kickoff_async() log("Done!") return str(result), display_name except Exception as e: error_msg = f"Error: {type(e).__name__}: {e}" log(error_msg) return error_msg, "Error" finally: if sdk: await sdk.aclose() # ───────────────────────────────────────────── # Load servers once at startup # ───────────────────────────────────────────── @st.cache_data(ttl=300) # Refresh every 5 minutes def load_servers(): import asyncio load_dotenv() loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: sdk = loop.run_until_complete(bd.login_interactive()) servers = loop.run_until_complete(sdk.list_servers()) loop.run_until_complete(sdk.aclose()) options = {} for s in servers: if s.connection_status in ("connected", "available"): name = ( s.name or getattr(s.mcp_server_directory, "name", None) or s.slug.replace("-", " ").title() ) options[f"{name} • {s.slug}"] = s.slug return options or {"No servers found": None} finally: loop.close() # ───────────────────────────────────────────── # Main UI # ───────────────────────────────────────────── servers = load_servers() if not servers or list(servers.values())[0] is None: st.error("No connected MCP servers found. Go to https://app.barndoor.ai and connect an app.") st.stop() server_choice = st.selectbox("Choose your app:", options=list(servers.keys())) selected_slug = servers[server_choice] query = st.text_area( "What do you want to do?", placeholder="Examples:\n• List my recent Salesforce opportunities\n• Summarize Notion pages tagged 'Q4'\n• Show unread Gmail from last 3 days", height=140, ) if st.button("Run Agent", type="primary", use_container_width=True): if not query.strip(): st.warning("Please enter a task.") st.stop() log_placeholder = st.empty() log_lines = [] def log(msg): ts = datetime.now().strftime("%H:%M:%S") log_lines.append(f"{ts} {msg}") log_placeholder.markdown("\n".join(log_lines), unsafe_allow_html=True) with st.spinner("Working..."): # This is the CORRECT way in Streamlit result, app_name = asyncio.run(run_crewai_task(selected_slug, query, log)) st.markdown("---") st.subheader(f"Result from {app_name}") if result.startswith("Error:"): st.error(result) else: st.markdown(result) st.caption(f"Completed • {datetime.now():%Y-%m-%d %I:%M %p}") ``` ### ### 1. Install Dependencies ```bash theme={null} uv pip install -r requirements.txt ``` ### 2. Create a .env File This script expects a .env file in the same directory as main.py. Add the following environment variables: ```bash theme={null} # Replace with your agent's client ID and secret from Barndoor # See: https://app.barndoor.ai/agents AGENT_CLIENT_ID={{barndoor-agent-client-id}} AGENT_CLIENT_SECRET={{barndoor-agent-client-secret}} # Replace with your tenant hostname BARNDOOR_API=https://{{your-tenant}}.platform.barndoor.ai BARNDOOR_URL=https://{{your-tenant}}.platform.barndoor.ai # Valid OpenAI API Key # see: https://platform.openai.com/api-keys OPENAI_API_KEY={{your-openapi-key}} # Default values, no changes required AUTH_DOMAIN=auth.barndoor.ai API_AUDIENCE=https://barndoor.ai/ MODE=production ``` Replace the placeholders with real values from your Barndoor project. ### 3. Run either Crew CLI or UI (browser) version: ```bash theme={null} uv run crew-cli.py or uv run streamlit run crew-ui.py ``` 🛠️ Troubleshooting * Missing .env values: Make sure all required keys are present. -using a stale token. try `rm ~/.barndoor/token.json` from root of project * Invalid server slug: Double-check SERVER\_SLUG = "notion" matches your Barndoor dashboard. * OAuth login doesn’t open: Manually open the URL shown in the terminal. # General Source: https://docs.barndoor.ai/sdks/examples/general # Barndoor SDK Examples This directory contains working examples that demonstrate how to use the Barndoor TypeScript SDK with MCP servers. ## Key Patterns Both examples follow the same proven pattern: ```typescript theme={null} // 1. Authenticate const sdk = await loginInteractive(); // 2. Ensure server is connected await ensureServerConnected(sdk, SERVER_SLUG); // 3. Create MCP client const mcpClient = await makeMcpClient(sdk, SERVER_SLUG); // 4. Use MCP client const { tools } = await mcpClient.listTools(); const result = await mcpClient.callTool({ name: 'tool_name', arguments: {} }); // 5. Cleanup await mcpClient.close(); await sdk.close(); ``` ## Configuration Both examples use the same authentication pattern: 1. **Environment Variables** (create a `.env` file): ``` AUTH_DOMAIN=your-auth-domain AGENT_CLIENT_ID=your-client-id AGENT_CLIENT_SECRET=your-client-secret MODE=development # or production ``` 2. **Server Configuration**: Change the `SERVER_SLUG` constant in each file to target different MCP servers: * `'salesforce'` - Salesforce integration * `'notion'` - Notion integration * Or any other configured MCP server ## Working Examples ### 1. `basic-mcp-client.js` - Direct MCP Client Basic example showing direct MCP server interaction without AI frameworks. **What it does:** * Authenticates with Barndoor * Connects to an MCP server * Lists available tools and resources * Executes basic operations **Requirements:** ```bash theme={null} npm install dotenv ``` **Run:** ```bash theme={null} node examples/basic-mcp-client.js ``` **Basic MCP client** ```typescript theme={null} /** * 🔗 Universal Barndoor MCP Client * * Lets the user pick any available MCP server, list its tools, * and run a custom prompt / command interactively — no hardcoded Salesforce or Notion. */ import 'dotenv/config'; import readline from 'readline/promises'; import { loginInteractive, ensureServerConnected, makeMcpClient, BarndoorSDK, getDynamicConfig, getStaticConfig, hasOrganizationInfo, } from '../dist/index.esm.js'; // simple input helper const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); async function ask(q) { return (await rl.question(q)).trim(); } async function main() { try { console.log('\n🚀 Starting Universal MCP Client Example...\n'); // --------------------------------------------------------------------- // 1. Authenticate to Barndoor // --------------------------------------------------------------------- console.log('🔐 Authenticating with Barndoor...'); let sdk; const envToken = process.env.BARNDOOR_ACCESS_TOKEN; if (envToken) { console.log('🔑 Using token from BARNDOOR_ACCESS_TOKEN'); const cfg = hasOrganizationInfo(envToken) ? getDynamicConfig(envToken) : getStaticConfig(); sdk = new BarndoorSDK(cfg.apiBaseUrl, { token: envToken }); await sdk.listServers(); console.log('✅ Authentication successful (env token)!'); } else { sdk = await loginInteractive(); await sdk.listServers(); console.log('✅ Authentication successful!'); } // --------------------------------------------------------------------- // 2. List all available servers // --------------------------------------------------------------------- const servers = await sdk.listServers(); if (!servers.length) throw new Error('No MCP servers found for this user.'); console.log('\n📡 Available MCP servers:'); servers.forEach((s, i) => console.log(` ${i + 1}. ${s.slug} (${s.connection_status})`)); // Ask user which one to use let idx = await ask('\n👉 Enter the number of the server you want to use: '); const choice = servers[parseInt(idx) - 1]; if (!choice) throw new Error('Invalid selection.'); const SERVER_SLUG = choice.slug; console.log(`\n🔗 Selected: ${SERVER_SLUG}\n`); // --------------------------------------------------------------------- // 3. Ensure it’s connected // --------------------------------------------------------------------- await ensureServerConnected(sdk, SERVER_SLUG); console.log(`✅ ${SERVER_SLUG} connected.`); // --------------------------------------------------------------------- // 4. Build MCP client and show available tools // --------------------------------------------------------------------- const mcpClient = await makeMcpClient(sdk, SERVER_SLUG); console.log('\n🔧 Fetching available tools...'); const { tools = [] } = await mcpClient.listTools(); if (!tools.length) console.log('⚠️ No tools found for this server.'); else tools.forEach((t, i) => console.log(` ${i + 1}. ${t.name} — ${t.description || 'No description'}`)); // --------------------------------------------------------------------- // 5. Ask user for a custom prompt // --------------------------------------------------------------------- const prompt = await ask('\n💬 What do you want to ask or do? (describe task): '); console.log(`\n🧠 Interpreting prompt: "${prompt}"`); // Naive tool selection: try to find one that matches keyword const matching = tools.find(t => prompt.toLowerCase().includes(t.name.toLowerCase().split('_')[0]) ); const tool = matching || tools[0]; if (!tool) throw new Error('No tools available to handle this prompt.'); console.log(`\n⚙️ Using tool: ${tool.name}`); // Ask user for optional JSON args let args = '{}'; if (tool.input_schema) { args = await ask('🧩 Optional JSON arguments (or Enter for none): '); if (!args.trim()) args = '{}'; } // --------------------------------------------------------------------- // 6. Call the selected tool // --------------------------------------------------------------------- console.log('\n🚀 Executing MCP tool...\n'); const parsedArgs = JSON.parse(args); const response = await mcpClient.callTool({ name: tool.name, arguments: parsedArgs, }); // --------------------------------------------------------------------- // 7. Pretty-print the result // --------------------------------------------------------------------- console.log('\n✅ MCP Response:'); if (response?.content?.[0]?.type === 'text') { console.log(response.content[0].text); } else { console.dir(response, { depth: 4, colors: true }); } // --------------------------------------------------------------------- // 8. Clean up // --------------------------------------------------------------------- await mcpClient.close(); await sdk.close(); rl.close(); console.log('\n✨ Done!\n'); } catch (error) { console.error('❌ Error:', error.message); if (error.stack) console.error(error.stack); rl.close(); process.exit(1); } } if (import.meta.url === `file://${process.argv[1]}`) { main(); } ``` **Requirements:** ```bash theme={null} npm install openai dotenv ``` ### 2. `openai-integration.js` - OpenAI + MCP Integration Complete example showing how to integrate OpenAI's function calling with MCP tools. **What it does:** * Authenticates with Barndoor * Connects to an MCP server (Salesforce by default) * Lets OpenAI decide which MCP tools to call * Executes the tools and feeds results back to OpenAI **Environment:** ```bash theme={null} export OPENAI_API_KEY="your-openai-api-key" ``` **Run:** ```bash theme={null} node examples/openai-integration.js ``` **Show Code Example** ```typescript theme={null} /** * 🤖 OpenAI Function Calling + Barndoor MCP Integration * * This script lets the user: * 1. Pick an available MCP server (e.g., salesforce, notion, etc) * 2. Type a natural-language query (e.g. "list ten notion pages") * 3. The model automatically selects the best MCP tool to call * 4. The result is returned and summarized in plain English * * Run with: * node examples/interactive-openai-mcp-client.js * * Requirements: * npm install openai dotenv readline-sync * * Make sure `.env` includes: * OPENAI_API_KEY=sk-... * AUTH_DOMAIN=auth.barndoor.ai * AGENT_CLIENT_ID=... * AGENT_CLIENT_SECRET=... * API_AUDIENCE=https://barndoor.ai/ * BARNDOOR_URL=https://.platform.barndoor.ai/mcp */ import 'dotenv/config'; import readlineSync from 'readline-sync'; import { OpenAI } from 'openai'; import { loginInteractive, ensureServerConnected, makeMcpClient, } from '../dist/index.esm.js'; // --- Step 0: Prepare OpenAI client ------------------------------------------------- const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); (async () => { let sdk; let mcpClient; try { console.log('🚀 Starting Interactive OpenAI + Barndoor MCP Client...\n'); // --------------------------------------------------------------------- // 1️⃣ Authenticate with Barndoor SDK // --------------------------------------------------------------------- console.log('🔐 Authenticating with Barndoor...'); sdk = await loginInteractive(); const servers = await sdk.listServers(); if (!servers.length) throw new Error('No MCP servers found! Connect at barndoor.ai.'); console.log('\n🌐 Available MCP servers:'); servers.forEach((s, i) => console.log(` ${i + 1}. ${s.slug} (${s.connection_status})`)); // Prompt user to choose one const idx = readlineSync.questionInt( '\n👉 Select a server by number: ', { limitMessage: 'Enter a valid number!' } ) - 1; const chosenServer = servers[idx]; if (!chosenServer) throw new Error('Invalid selection.'); const SERVER_SLUG = chosenServer.slug; console.log(`\n🔗 Ensuring ${SERVER_SLUG} server is connected...`); await ensureServerConnected(sdk, SERVER_SLUG); console.log(`✅ ${SERVER_SLUG} server connected!\n`); mcpClient = await makeMcpClient(sdk, SERVER_SLUG); // --------------------------------------------------------------------- // 2️⃣ Let user enter a natural language request // --------------------------------------------------------------------- const userPrompt = readlineSync.question( '💬 What do you want to ask or do? (describe task): ' ); // --------------------------------------------------------------------- // 3️⃣ List available MCP tools and convert to OpenAI function schemas // --------------------------------------------------------------------- const { tools = [] } = await mcpClient.listTools(); if (!tools.length) throw new Error(`No tools available on ${SERVER_SLUG}`); const functions = tools.map((t) => ({ type: 'function', function: { name: t.name.replace(/[^A-Za-z0-9_]/g, '_').slice(0, 64), description: t.description || 'MCP tool', parameters: t.parameters ?? { type: 'object', properties: {}, additionalProperties: true, }, }, })); // --------------------------------------------------------------------- // 4️⃣ Use OpenAI to decide which tool to call // --------------------------------------------------------------------- console.log(`\n🧠 Interpreting prompt: "${userPrompt}"`); const msgs = [{ role: 'user', content: userPrompt }]; let chat = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: msgs, tools: functions, tool_choice: 'auto', }); let msg = chat.choices[0].message; const toolCall = msg.tool_calls?.[0]; if (!toolCall) { console.log('\n🤔 Model did not choose a tool. Here’s its reply:'); console.log(msg.content); return; } const { name: toolName, arguments: raw } = toolCall.function; const args = JSON.parse(raw || '{}'); console.log(`\n⚙️ Using tool: ${toolName}`); console.log('🚀 Executing MCP tool...\n'); const mcpResult = await mcpClient.callTool({ name: toolName, arguments: args, }); console.log('✅ MCP Response:'); console.log(JSON.stringify(mcpResult, null, 2)); // --------------------------------------------------------------------- // 5️⃣ Feed MCP result back to OpenAI for a natural summary // --------------------------------------------------------------------- msgs.push(msg); msgs.push({ role: 'tool', tool_call_id: toolCall.id, name: toolName, content: JSON.stringify(mcpResult), }); chat = await openai.chat.completions.create({ model: 'gpt-4o-mini', messages: msgs, }); console.log('\n✨ Final Answer:\n'); console.log(chat.choices[0].message.content); } catch (error) { console.error('❌ Error:', error.message); if (error.stack) console.error(error.stack); } finally { if (sdk) await sdk.close(); if (mcpClient) await mcpClient.close(); } })(); ``` This pattern uses the `@modelcontextprotocol/sdk` package internally and handles all the complex MCP protocol details for you. **Note:** While the SDK is written in TypeScript, the current examples are still in JavaScript (.js files) for broader compatibility. You can easily convert them to TypeScript by changing the file extensions to `.ts` and adding type annotations as needed. # Barndoor SDKs Source: https://docs.barndoor.ai/sdks/introduction The Barndoor SDKs empowers developers to connect to governed Model Context Protocol (MCP) servers, enabling seamless interaction with platforms like Salesforce, Notion, and GitHub. Whether you're building AI-driven applications with OpenAI or performing direct API calls, the SDK simplifies authentication, tool discovery, and data operations with a robust TypeScript and Python interface. Get started with our examples to query Salesforce Opportunities, manage Notion pages, or integrate with GitHub repo > [card] [Check out our Python SDK](/sdks/python) > > Get your docs set up locally for easy development > [card] [Check out our Typescript SDK](/sdks/typescript) > > Preview your changes before you push to make sure they're perfect > [card] [Examples](/sdks/examples/general) > > Check out our example integrations # Python Source: https://docs.barndoor.ai/sdks/python # Barndoor SDK A lightweight, **framework-agnostic** Python client for the Barndoor Platform REST APIs and Model Context Protocol (MCP) servers. The SDK removes boiler-plate around: * Secure, offline-friendly **authentication to Barndoor** (interactive PKCE flow + token caching). * **Server registry** – list, inspect and connect third-party providers (Salesforce, Notion, Slack …). * **Managed Connector Proxy** – build ready-to-use connection parameters for any LLM/agent framework (CrewAI, LangChain, custom code …) without importing Barndoor-specific adapters. #### Download here: [https://pypi.org/project/barndoor/](https://pypi.org/project/barndoor/) *** ## How it works The SDK orchestrates a multi-step flow to connect your code to third-party services: ``` You → Barndoor Auth (get JWT) → Registry API (with JWT) → MCP Proxy (with JWT) → Third-party service ``` 1. **Authentication**: You log in via Barndoor to get a JWT token 2. **Registry API**: Using the JWT, query available MCP servers and manage OAuth connections 3. **MCP Proxy**: Stream requests through Barndoor's proxy with the JWT for authorization 4. **Third-party service**: The proxy forwards your requests to Salesforce, Notion, etc. This architecture provides secure, managed access to external services without handling OAuth flows or storing third-party credentials in your code. *** ## Installation ```bash theme={null} pip install barndoor-sdk # coming soon – for now use an editable install # or, inside this repo pip install -e libs/barndoor[dev] ``` Python ≥ 3.10 is required. *** ## Local development with uv For the fastest install and reproducible builds you can use [uv](https://github.com/astral-sh/uv) instead of `pip`. ```bash theme={null} # 1) (one-off) install uv brew install uv # or follow the install script on Linux/Windows # 2) create an isolated virtual environment in the repo uv venv .venv source .venv/bin/activate # 3) install the SDK in editable mode plus the example extras uv pip install -e '.[examples]' # 4) install MCP support for CrewAI examples uv pip install 'crewai-tools[mcp]' # 5) copy the environment template and add your credentials cp env.example .env # Edit .env to add AGENT_CLIENT_ID, AGENT_CLIENT_SECRET, and OPENAI_API_KEY # 6) run the interactive login utility once (opens browser) uv run python -m barndoor.sdk.cli_login # 7) kick off the Notion sample agent uv run python examples/sample_notion_agent.py ``` **Note:** The OAuth default callback uses port 52765. Make sure this is registered in your Barndoor Agent as: ``` http://localhost:52765/cb ``` ### Using a custom OAuth callback port If port `52765` is blocked (or you prefer another), you can: 1. **Register the new callback URL** in your Barndoor Agent application, e.g. ``` http://localhost:60000/cb ``` 2. **Run the login helper with the matching port** ```bash theme={null} # CLI uv run python -m barndoor.sdk.cli_login --port 60000 # In code sdk = await bd.login_interactive(port=60000) ``` The SDK will spin up the local callback server on that port and embed the new URL in the request. The examples expect a `.env` file next to each script containing: ```bash theme={null} # Copy env.example → .env and add your credentials ``` *** ## Authentication workflow Barndoor APIs expect a **JWT** issued by your Barndoor tenant. The SDK offers three ways to obtain such a token: | Option | Command | When to use | | - | - | - | | Interactive CLI | `python -m barndoor.sdk.cli_login` *(alias: `barndoor-login`)* | One-time setup on laptops / CI machines | | In-code helper | `await barndoor.sdk.login_interactive()` | Notebooks or scripts where you do not want a separate login step | | Client credentials | `await BarndoorSDK.from_client_credentials(...)` | Headless / machine-to-machine workloads (backend services, scheduled jobs) where no user is present | The interactive variants: 1. Spin up a tiny localhost callback server. 2. Open the system browser to Barndoor. 3. Exchange the returned *code* for a JWT. 4. Persist the token to `~/.barndoor/token.json` (0600 permissions). Environment variables (or a neighbouring `.env` file) must define the Agent OAuth application: ``` AGENT_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxx AGENT_CLIENT_SECRET=yyyyyyyyyyyyyyyyyyyy # optional overrides # See `internal_dev_env_setup` guide for local/dev options ``` The cached token is auto-refreshed on every run; if it is expired or revoked a new browser flow is launched. ### Machine-to-machine (client credentials) For headless services with no user present, use the standard OAuth 2.0 **client-credentials** grant. This requires a Barndoor OAuth application configured for the client-credentials grant type. The SDK exposes a one-call factory, `BarndoorSDK.from_client_credentials(...)`, that fetches the initial JWT, **refreshes it automatically** as it nears expiry, and transparently retries once on `401 Unauthorized`. ```python theme={null} import asyncio from barndoor.sdk import BarndoorSDK async def main(): async with await BarndoorSDK.from_client_credentials( "https://api.barndoor.host", client_id="YOUR_M2M_CLIENT_ID", client_secret="YOUR_M2M_CLIENT_SECRET", audience="https://barndoor.ai/", issuer="https://auth.barndoor.ai/realms/barndoor", ) as sdk: servers = await sdk.list_servers() print([s.slug for s in servers]) asyncio.run(main()) ``` Prefer the `issuer=` keyword argument (OIDC discovery finds the token endpoint automatically). The legacy `domain=` keyword is retained for backwards compatibility and posts directly to `https://{domain}/oauth/token`. If you only need the raw access token (e.g. to inject it into another HTTP client), use the lower-level helpers re-exported from `barndoor.sdk`: ```python theme={null} from barndoor.sdk import ( get_client_credentials_token, # synchronous get_client_credentials_token_async, # awaitable, non-blocking ) token = await get_client_credentials_token_async( client_id="...", client_secret="...", audience="https://barndoor.ai/", issuer="https://auth.barndoor.ai/realms/barndoor", ) ``` These return only the access-token string and do **not** persist anything to `~/.barndoor/token.json`. Use the `from_client_credentials` factory if you want the SDK to manage token lifetime for you. A complete runnable example is at [`examples/sample_m2m_client.py`](https://github.com/barndoor-ai/barndoor-python-sdk/blob/main/examples/sample_m2m_client.py). ## Quick-start in four lines ```python theme={null} import barndoor.sdk as bd sdk = await bd.login_interactive() # 1️⃣ ensure valid token await bd.ensure_server_connected(sdk, "salesforce") # 2️⃣ make sure OAuth is done params, _public_url = await bd.make_mcp_connection_params(sdk, "salesforce") ``` `params` is a plain dict with `url`, `headers` and (optionally) `transport` – ready to plug into **any** HTTP / SSE / WebSocket client. See the examples below for CrewAI & LangChain usage. *** ## Using the Registry API ```python theme={null} # List all MCP servers available to the current user servers = await sdk.list_servers() print([s.slug for s in servers]) # ['salesforce', 'notion', ...] # Get detailed metadata details = await sdk.get_server(server_id=servers[0].id) print(details) ``` Additional helpers: * `await sdk.initiate_connection(server_id)` – returns an OAuth URL the user must visit. * `await bd.ensure_server_connected(sdk, "notion")` – combines status polling + browser launch. *** ## Model Context Protocol Connection Once a server is **connected** you can stream requests through Barndoor’s proxy edge. ```python theme={null} params, public_url = await bd.make_mcp_connection_params(sdk, "notion") print(params["url"]) # http(s)://…/mcp/notion print(params["headers"]) # {'Authorization': 'Bearer ey…', 'x-barndoor-session-id': …} ``` ## API Documentation The complete API specification is available in [`barndoor/sdk/docs/openapi.yaml`](https://github.com/barndoor-ai/barndoor-python-sdk/blob/main/barndoor/sdk/docs/openapi.yaml). This covers all endpoints currently used by the SDK including: * Server listing and details * OAuth connection initiation * Connection status checking The spec can be viewed with tools like [Swagger UI](https://swagger.io/tools/swagger-ui/) or [Redoc](https://redocly.github.io/redoc/). # Typescript Source: https://docs.barndoor.ai/sdks/typescript # Barndoor TypeScript SDK A lightweight, **framework-agnostic** TypeScript/JavaScript client for the Barndoor Platform REST APIs and Model Context Protocol (MCP) servers. The SDK supports *lazy authentication*—you can build an SDK instance first, then inject a JWT later with `authenticate()`. The SDK removes boiler-plate around: * Secure, offline-friendly **authentication to Barndoor** (interactive PKCE flow + token caching). * **Server registry** – list, inspect and connect third-party providers (Salesforce, Notion, Slack …). * **Managed Connector Proxy** – build ready-to-use connection parameters for any LLM/agent framework (CrewAI, LangChain, custom code …) without importing Barndoor-specific adapters. #### Be sure to checkout our [examples](https://github.com/barndoor-ai/barndoor-ts-sdk/tree/main/examples) and our NPM [package](https://www.npmjs.com/package/@barndoor-ai/sdk) ## Installation ```bash theme={null} npm install @barndoor-ai/sdk ``` ## Quick Start ### Basic Usage ```typescript theme={null} import { BarndoorSDK } from '@barndoor-ai/sdk'; // ① token known at construction time (unchanged) const sdk = new BarndoorSDK('https://your-orgplatform.barndoor.ai', { token: 'your-jwt' }); ``` ```typescript theme={null} // ② deferred login (new) const sdk = new BarndoorSDK('https://your-org.platform.barndoor.ai'); await sdk.authenticate('your-jwt'); // List available MCP servers const servers = await sdk.listServers(); console.log('Available servers:', servers); // Get details for a specific server const server = await sdk.getServer('server-uuid'); console.log('Server details:', server); // Clean up await sdk.close(); ``` ### Interactive Login For development and prototyping, use the interactive login helper: `loginInteractive()` builds an SDK *without* requiring `token` in the ctor—it internally calls `sdk.authenticate()` for you. ```typescript theme={null} import { loginInteractive } from '@barndoor-ai/sdk'; // Automatically handles OAuth flow and token caching const sdk = await loginInteractive(); const servers = await sdk.listServers(); ``` ### Complete Workflow ```typescript theme={null} import { loginInteractive, ensureServerConnected, makeMcpConnectionParams } from '@barndoor-ai/sdk'; async function main() { // 1. Login (handles OAuth + caching) const sdk = await loginInteractive(); // 2. Ensure server is connected (launches OAuth if needed) await ensureServerConnected(sdk, 'notion'); // sdk.ensureServerConnected(...) is also available directly // 3. Get connection parameters for your AI framework const [params, publicUrl] = await makeMcpConnectionParams(sdk, 'notion'); // 4. Use with any MCP-compatible framework console.log('MCP URL:', params.url); console.log('Headers:', params.headers); await sdk.close(); } ``` ## Environment Configuration The SDK automatically detects your environment and configures appropriate endpoints: ```bash theme={null} # Development export MODE=development export AGENT_CLIENT_ID=your_client_id export AGENT_CLIENT_SECRET=your_client_secret # Production export MODE=production export AGENT_CLIENT_ID=your_client_id export AGENT_CLIENT_SECRET=your_client_secret # Local development export MODE=localdev export BARNDOOR_API=http://localhost:8000 export BARNDOOR_URL=http://localhost:8000 ``` If you run without a token at construction time the SDK will still read `AGENT_CLIENT_ID/SECRET` when `loginInteractive()` is invoked. ## API Reference ### BarndoorSDK Main SDK class for API interactions. ```javascript theme={null} const sdk = new BarndoorSDK(apiBaseUrl, options); ``` **Parameters:** * `apiBaseUrl` (string): Base URL of the Barndoor API * `options.token?` (string): Initial JWT (pass later via authenticate() if omitted) * `options.timeout` (number): Request timeout in seconds (default: 30) * `options.maxRetries` (number): Maximum retry attempts (default: 3) **Methods:** #### `authenticate(jwtToken)` Sets/validates token for the SDK instance. ```typescript theme={null} await sdk.authenticate(jwtToken); // Returns: Promise ``` #### `ensureServerConnected(serverSlug, options?)` Ensure a server is connected, launching OAuth if needed – same behaviour as quick-start helper. ```typescript theme={null} await sdk.ensureServerConnected('notion', { pollSeconds: 2 }); // Returns: Promise ``` #### `listServers()` List all MCP servers available to your organization. ```typescript theme={null} const servers = await sdk.listServers(); // Returns: ServerSummary[] ``` #### `getServer(serverId)` Get detailed information about a specific server. ```typescript theme={null} const server = await sdk.getServer('server-uuid'); // Returns: ServerDetail ``` #### `initiateConnection(serverId, returnUrl?)` Initiate OAuth connection flow for a server. ```typescript theme={null} const connection = await sdk.initiateConnection('server-uuid'); // Returns: { connection_id, auth_url, state } ``` #### `getConnectionStatus(serverId)` Get connection status for a server. ```typescript theme={null} const status = await sdk.getConnectionStatus('server-uuid'); // Returns: 'available' | 'pending' | 'connected' ``` ### Quick-start Helpers #### `loginInteractive(options?)` Perform interactive OAuth login and return initialized SDK. ```typescript theme={null} const sdk = await loginInteractive({ authDomain: 'auth.barndoor.ai', clientId: 'your-client-id', clientSecret: 'your-client-secret', port: 52765 }); ``` #### `ensureServerConnected(sdk, serverSlug, options?)` Ensure a server is connected, launching OAuth if needed. ```typescript theme={null} await ensureServerConnected(sdk, 'notion', { timeout: 90 }); ``` #### `makeMcpConnectionParams(sdk, serverSlug, options?)` Generate MCP connection parameters for AI frameworks. ```typescript theme={null} const [params, publicUrl] = await makeMcpConnectionParams(sdk, 'notion'); // params: { url, transport, headers } ``` ## Error Handling The SDK provides a comprehensive error hierarchy: ```typescript theme={null} import { BarndoorError, HTTPError, ConnectionError, TokenError, ConfigurationError } from '@barndoor-ai/sdk'; try { await sdk.listServers(); } catch (error) { if (error instanceof HTTPError) { console.error('HTTP Error:', error.statusCode, error.message); } else if (error instanceof TokenError) { console.error('Token Error:', error.message); // Re-authenticate } else if (error instanceof ConnectionError) { console.error('Connection Error:', error.message); // Check network } } ``` ## Browser Support The SDK works in both Node.js and browser environments: ```typescript theme={null} // Browser usage import { BarndoorSDK } from '@barndoor-ai/sdk'; // Token storage uses localStorage in browsers const sdk = new BarndoorSDK('https://api.barndoor.ai', { token: 'your-token' }); ``` When running in the browser you can also create the SDK first and later call `await sdk.authenticate(token)` once your SPA receives a JWT. **Note:** Interactive login (`loginInteractive`) requires Node.js for the local callback server. ## Examples See the `examples/` directory for complete working examples: * `openai-integration.js` - OpenAI + MCP function calling integration * `basic-mcp-client.js` - Direct MCP client without AI framework ## TypeScript Support The SDK is written in TypeScript and includes full type definitions: ```typescript theme={null} import { BarndoorSDK, ServerSummary } from '@barndoor-ai/sdk'; const sdk = new BarndoorSDK('https://api.barndoor.ai', { token: 'your-token' }); const servers: ServerSummary[] = await sdk.listServers(); ``` ## Contributing 1. Clone the repository 2. Install dependencies: `npm install` 3. Build the project: `npm run build` 4. Run tests: `npm test` 5. Run type checking: `npm run type-check` 6. Run safety checks: `npm run safety-check` # Best Practices Source: https://docs.barndoor.ai/terraform/best-practices Importing existing configuration, avoiding drift, destroy semantics, secrets hygiene, and running the Barndoor provider in CI Patterns for running the Barndoor Terraform provider in production, and the platform semantics worth knowing before you rely on it. ## One owner per object Give every Barndoor object exactly one owner: **either Terraform or the portal, never both**. If an admin edits a Terraform-managed policy in the app, the next `terraform plan` shows a diff and the next apply reverts their change — usually a surprise for both sides. Practical rules: * Agree which product areas are code-managed and note it where admins will see it (a policy's `description` or `tags = ["terraform-managed"]` work well). * To *reference* portal-managed objects from Terraform without owning them, use the data sources: [`barndoor_mcp_server`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server), [`barndoor_agent`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent), [`barndoor_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/policy), [`barndoor_llm_provider`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/llm_provider), [`barndoor_dlp_detection_engine`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/dlp_detection_engine), plus catalog lookups [`barndoor_mcp_server_directory`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server_directory) and [`barndoor_agent_directory`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent_directory). * To *take ownership* of a portal-created object, import it (below) — from then on, hands off in the UI. ## Secrets and state hygiene * Supply `client_secret` via `BARNDOOR_CLIENT_SECRET`, never in configuration. In CI, use your platform's secret store (see [CI/CD](#ci%2Fcd-with-github-actions)). * Mark your own secret inputs (`api_key` variables and the like) as `sensitive = true`. * Barndoor's write-only credential attributes (`barndoor_llm_connection.api_key` and `credentials`, MCP server OAuth secrets, log-export storage credentials such as S3 access keys and Azure account keys or SAS tokens) are stored in the platform's secret store and **never returned by the API** — but the values you supplied still live in your Terraform **state file**. Treat state as secret: use a remote backend with encryption and restricted access. * `barndoor_llm_api_key.key` is different: it is a secret the **platform issues**, returned only when the key is created or rotated, so Terraform keeps it in state for you to pass on. Anyone who can read your state can use that key. * Rotate the provider credential on a schedule that fits your team. Rotation keeps the client ID and invalidates only the secret — update `BARNDOOR_CLIENT_SECRET` wherever it's stored, and remember one credential is active per organization, so every pipeline shares it. ## Pin the provider version ```hcl theme={null} terraform { required_providers { barndoor = { source = "barndoor-ai/barndoor" version = "~> 0.3" } } } ``` `~> 0.3` accepts patch and minor updates within the 0.x line as they release. Check the [changelog](https://github.com/barndoor-ai/terraform-provider-barndoor/blob/main/CHANGELOG.md) before widening the range. ## Importing existing configuration Every resource supports `terraform import`, so an organization configured through the portal can move to code incrementally. With Terraform 1.5+, prefer `import` blocks — they're reviewable and plannable: ```hcl theme={null} import { to = barndoor_policy.search_read_only id = "6f1c9312-8f3e-4bde-9c2b-b3a1d1cf34a4" } ``` ```bash theme={null} terraform plan -generate-config-out=generated.tf ``` Most resources import by their UUID, with these exceptions: | Resource | Import ID | | - | - | | `barndoor_connection` | The **server's** ID or slug (a server has at most one tenant-wide connection) | | `barndoor_log_export` | Your organization ID, or `{organization_id}/{export_type}` | | `barndoor_llm_routing_rule` | `{policy_id}/{rule_id}` | | `barndoor_llm_model_pricing` | The rule's logical identity: `{model_provider}\|{model_pattern}`, or a bare `{model_pattern}` for provider-unscoped rules | | `barndoor_dlp_org_config`, `barndoor_idp`, `barndoor_llm_governance_config`, `barndoor_llm_api_key_lifetime_policy` | Your organization ID (they're org singletons) | Two things to expect right after an import: * **Write-only attributes come back empty.** Credentials the platform never returns (OAuth secrets, API keys, log-export storage credentials) can't be populated by import. The first plan after importing will propose re-sending any such values present in your configuration — that in-place update is expected and safe. * **Some resources only adopt via import.** `barndoor_idp`, `barndoor_dlp_field_control_policy`, and live `barndoor_llm_model_pricing` rules deliberately refuse to create over an existing object, so out-of-band setup is never silently overwritten — the error message directs you to import instead. ## Destroy is not always delete `terraform destroy` maps to whatever removal means for each object on the platform: | Resource | What destroy actually does | | - | - | | `barndoor_policy` | **Archives** the policy (terminal lifecycle state, kept for audit; never hard-deleted) | | `barndoor_llm_model_pricing` | Archives the rule with full version history; recreating the same rule restores it | | `barndoor_mcp_server` | Soft-deletes the server; its connections and stored credentials are torn down, the name is freed | | `barndoor_agent` | Unregisters the agent; the platform archives dependent policies | | `barndoor_log_export` | Removes the destination configuration; the platform-provisioned export slot survives | | `barndoor_dlp_org_config` | Resets the org singleton to platform defaults; nothing is deleted | | `barndoor_llm_governance_config` | Resets only `require_pricing_for_mappings`; default model access and routing-policy enforcement keep their values, so destroy never loosens access | | `barndoor_llm_connection` | Deletes the connection and its stored secret; fails with a `409` while a provider still uses it | | `barndoor_llm_routing_policy` | Deletes the policy **and all its routing rules**; callers sending its alias get an error | | `barndoor_llm_api_key` | **Revokes** the key; revocation is permanent, and recreating it issues a new key and secret | | `barndoor_llm_api_key_lifetime_policy` | Clears the organization default, so self-serve keys have no limit unless an override applies | | `barndoor_llm_model_route_group` | Deletes the group; access policies that target it keep a dangling target that matches nothing, so an allowlist relying on it denies those models | | Everything else | Deletes the object | > [!WARNING] > > Renames of immutable fields are replacements, and replacements are destroys. For example, `barndoor_policy.mcp_server_id` is immutable — changing it archives the existing policy and creates a new one. Read the plan output for `-/+` markers before applying. ## Plans that look like drift but aren't * `barndoor_llm_model_pricing.id` **changes on every price update** — pricing is an append-only versioned store, and each change creates a new version. That's by design, not drift. * `barndoor_llm_rate_limit`: removing `requests_per_minute` or `tokens_per_minute` from configuration **clears that metric on the platform** — the plan is telling the truth; make sure it's what you meant. * After importing resources with write-only credentials, the first plan re-sends those values (see [Importing](#importing-existing-configuration)). * `barndoor_llm_api_key.key` is **never refreshed**, for the same reason as a webhook signing secret below: the platform can't return it again. Rotate through `rotation_trigger` so Terraform receives the new secret; on **import** it is empty until the next rotation. A key revoked in the app is planned for re-creation. * `barndoor_notification_channel.signing_secret` is **never refreshed**. The platform reveals a webhook channel's signing secret exactly once, on creation or rotation, and cannot return it again — so state holds whatever was last issued to Terraform, and a plan will never show a difference even if the secret was rotated elsewhere. Rotate through `rotate_when_changed` (which rotates in place, preserving the channel) so Terraform stays the source of truth. On **import** the attribute is empty, because Terraform was not the recipient of the reveal; `has_signing_secret` still reports whether the platform holds one. ## CI/CD with GitHub Actions The standard shape — plan on pull requests, apply on merge to main: ```yaml .github/workflows/terraform.yml theme={null} name: terraform on: pull_request: push: branches: [main] env: BARNDOOR_BASE_URL: https://platform.barndoor.ai BARNDOOR_TOKEN_URL: https://auth.barndoor.ai/realms/barndoor/protocol/openid-connect/token BARNDOOR_CLIENT_ID: ${{ vars.BARNDOOR_CLIENT_ID }} BARNDOOR_ORGANIZATION_ID: ${{ vars.BARNDOOR_ORGANIZATION_ID }} BARNDOOR_CLIENT_SECRET: ${{ secrets.BARNDOOR_CLIENT_SECRET }} jobs: terraform: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 - run: terraform init - run: terraform plan -input=false if: github.event_name == 'pull_request' - run: terraform apply -input=false -auto-approve if: github.ref == 'refs/heads/main' ``` Notes: * Only `BARNDOOR_CLIENT_SECRET` is a secret; the other four values are identifiers and can live in plain repository variables. * Because one provider credential is active per organization, CI and humans share it — if you rotate it, update the CI secret in the same change. * Use a remote state backend (S3, GCS, Terraform Cloud, …) so CI runs and local runs see the same state. ## Troubleshooting > [accordion] Error: ... requires the organization admin role > > The credential reached the API but was refused. Confirm `organization_id` matches the organization the credential was generated in (copy both from **Settings → API Tokens**), and that the credential hasn't been revoked. > [accordion] Token request failed: invalid\_client or unauthorized\_client > > The token endpoint rejected the client ID/secret pair — the secret is wrong, was rotated out from under you, or the credential was revoked. Mint a fresh secret by rotating in **Settings → API Tokens**. > [accordion] base\_url must be the platform host root > > `base_url` may not carry a path suffix; the provider appends each service's API prefix itself. Use the bare origin. > [accordion] 409 Conflict on create > > You're creating something that already exists and has a uniqueness constraint — a duplicate policy name, a second rate limit on the same scope and traffic type, a second connection on a server. Either import the existing object or change the conflicting field. > [accordion] Blocks vs. attribute syntax: 'Blocks of type X are not expected here' > > Nested values in this provider are **attributes**, assigned with `=` — for example `destination = { ... }` on `barndoor_log_export`. Writing them as blocks (`destination { ... }`) is a syntax error. > [accordion] Intermittent failures under heavy applies > > Since v0.4.0 the provider retries transient failures (rate limiting, gateway errors, connection blips) with exponential backoff, so most blips never surface. If an apply still fails partway, re-run `terraform apply` — it converges from wherever it stopped. > [accordion] Seeing the full API exchange > > Run with `TF_LOG=DEBUG` — the provider logs request/response detail, including full error bodies, at debug level. # Manage Data Protection Source: https://docs.barndoor.ai/terraform/data-protection Define custom detection types, allow lists, and enforcement policies as code, with a dry-run-first rollout This guide manages your organization's Data Control Center configuration in Terraform: the org-level switch, a detection engine ([Protection Profile](/how-tos/data-control-center/protection-profiles)), a custom detection type, allow-list entries that suppress false positives, and an enforcement policy rolled out safely with dry run. The whole flow is self-contained — no IDs need to be copied from the app. > [!NOTE] > > **Estimated time**: 20–30 minutes. Complete [Getting Started](/terraform/getting-started) first. For the concepts, see the [Data Control Center overview](/how-tos/data-control-center/overview). ## Before You Begin * A configured `provider "barndoor"` block (see [Getting Started](/terraform/getting-started)) ## Step 1: Adopt the organization config Data protection has one configuration object per organization, provisioned by the platform. The `barndoor_dlp_org_config` resource **adopts** that singleton rather than creating anything: ```hcl theme={null} resource "barndoor_dlp_org_config" "this" { enabled = true # Observe-only mode: every policy records findings without acting. global_dry_run = false } ``` Reference: [`barndoor_dlp_org_config`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_org_config) > [!NOTE] > > Because it's a singleton, `terraform destroy` doesn't delete anything — it resets both settings to the platform defaults (`enabled = true`, `global_dry_run = false`) and drops the resource from state. ## Step 2: Define a detection engine (Protection Profile) A detection engine — a **Protection Profile** in the app — binds a detection provider to the data types it scans for. Enforcement policies reference engines, so at least one must exist. Manage it in Terraform, or look up one that was created in the portal: > [tab] New engine > > ```hcl theme={null} > resource "barndoor_dlp_detection_engine" "secrets" { > name = "Credential secrets" > provider_type = "builtin_secrets_regex" > > enabled_detection_types = [ > "DETECTION_TYPE_AWS_ACCESS_KEY_ID", > "DETECTION_TYPE_GITHUB_PAT", > ] > } > ``` > [tab] Existing engine (data source) > > ```hcl theme={null} > data "barndoor_dlp_detection_engine" "secrets" { > # Names are unique per provider_type; set provider_type (or use id) > # when one profile spans several engines. > name = "Credential secrets" > provider_type = "builtin_secrets_regex" > } > ``` References: [`barndoor_dlp_detection_engine` resource](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_detection_engine), [data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/dlp_detection_engine) > [!NOTE] > > Engines are unique per (`name`, `provider_type`) — the same name across several provider types renders as one merged profile in the app. Deleting an engine that is the only one on an enforcement policy fails with an error naming the referencing policy. ## Step 3: Define a custom detection type Custom detection types extend the built-in detectors with organization-specific patterns — project codenames, internal ticket formats, customer ID shapes: ```hcl theme={null} resource "barndoor_dlp_custom_detection_type" "codenames" { name = "Project codenames" description = "Internal project codenames that must not leave the organization" patterns = [ { pattern = "(?i)project\\s+aurora", pattern_type = "PATTERN_TYPE_REGEX" }, { pattern = "AURORA-CLASSIFIED", pattern_type = "PATTERN_TYPE_LITERAL" }, ] # Both default to *_MEDIUM when omitted. default_severity = "DETECTION_SEVERITY_HIGH" default_confidence = "DETECTION_CONFIDENCE_HIGH" } ``` Reference: [`barndoor_dlp_custom_detection_type`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_custom_detection_type) Patterns are evaluated in order. Regex patterns use Rust `regex` syntax and are validated by the API — a pattern that doesn't compile is rejected at apply time, not silently ignored. The platform assigns the type's wire name (`DETECTION_TYPE_CUSTOM_…`), exposed as the `detection_type` attribute — that's the value other data protection resources reference. ## Step 4: Suppress false positives with allow-list entries Allow-list entries stop known-safe values from being reported (and acted on) as findings: ```hcl theme={null} # Scoped to specific detection types — including the custom one from Step 3. resource "barndoor_dlp_allow_list_entry" "codename_docs_site" { pattern = "aurora.docs.example.com" pattern_type = "PATTERN_TYPE_LITERAL" detection_types = [barndoor_dlp_custom_detection_type.codenames.detection_type] reason = "Public documentation host, not a leak" } # Omit detection_types to suppress matches for every detection type. resource "barndoor_dlp_allow_list_entry" "support_mailbox" { pattern = "support@example.com" pattern_type = "PATTERN_TYPE_LITERAL" detection_types = ["DETECTION_TYPE_EMAIL"] reason = "Shared support mailbox, not PII" } ``` Reference: [`barndoor_dlp_allow_list_entry`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_allow_list_entry) > [!NOTE] > > The platform has no update operation for allow-list entries, so changing **any** attribute replaces the entry (delete + create). Plans will show this as a replacement — that's expected. ## Step 5: Enforce with a policy — dry run first Enforcement policies decide what happens when a detection engine reports a finding. A policy targets exactly one lane: **MCP traffic** (tool inputs/outputs) or **model-provider traffic** (prompts/responses). Start in dry run — the policy evaluates and records findings in activity, but takes no action: ```hcl theme={null} resource "barndoor_dlp_enforcement_policy" "block_secrets_in_prompts" { name = "Block secrets in prompts" action = "POLICY_ACTION_BLOCK" provider_ids = ["openai"] runtime_stage = "RUNTIME_STAGE_PROMPT" # Roll out observing first; flip to false to enforce. dry_run = true detection_engine_ids = [barndoor_dlp_detection_engine.secrets.id] } ``` And an MCP-lane example — tokenize PII in tool traffic for one group: ```hcl theme={null} resource "barndoor_dlp_enforcement_policy" "tokenize_mcp_pii" { name = "Tokenize PII on MCP traffic" action = "POLICY_ACTION_TOKENIZE" mcp_targets = [ { mcp_server_id = "*", direction = "BOTH" }, ] principals = [ { principal_type = "GROUP", principal_id = "engineering" }, ] dry_run = true detection_engine_ids = [barndoor_dlp_detection_engine.secrets.id] } ``` Reference: [`barndoor_dlp_enforcement_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_enforcement_policy) > [!WARNING] > > **The two lanes don't mix.** `MCP_SERVER` policies use `mcp_targets` with the `RUNTIME_STAGE_TOOL_INPUT` / `RUNTIME_STAGE_TOOL_OUTPUT` stages and may not set `provider_ids` or `model_alias`; `MODEL_PROVIDER` policies are the reverse, with `RUNTIME_STAGE_PROMPT` / `RUNTIME_STAGE_RESPONSE`. The API rejects mixed shapes. It also rejects (with a 422) any detection engine that doesn't support the policy's `action`. ## Step 6: Flip to enforcement Once dry-run findings in the activity view look right — expected matches, no false positives that an allow-list entry should cover — enforce by changing one line and re-applying: ```hcl theme={null} dry_run = false ``` This is the code-review moment the dry-run pattern exists for: the diff that turns on enforcement is one visible line in a pull request. > [!TIP] > > There are two dry-run levers, and they compose: `global_dry_run` on the org config forces *every* policy to observe-only (useful during initial rollout of the whole system), while per-policy `dry_run` stages an individual policy. Enforcement happens only when both are off. ## Complete example **Full configuration from this guide** ```hcl theme={null} resource "barndoor_dlp_org_config" "this" { enabled = true global_dry_run = false } resource "barndoor_dlp_detection_engine" "secrets" { name = "Credential secrets" provider_type = "builtin_secrets_regex" enabled_detection_types = [ "DETECTION_TYPE_AWS_ACCESS_KEY_ID", "DETECTION_TYPE_GITHUB_PAT", ] } resource "barndoor_dlp_custom_detection_type" "codenames" { name = "Project codenames" description = "Internal project codenames that must not leave the organization" patterns = [ { pattern = "(?i)project\\s+aurora", pattern_type = "PATTERN_TYPE_REGEX" }, { pattern = "AURORA-CLASSIFIED", pattern_type = "PATTERN_TYPE_LITERAL" }, ] default_severity = "DETECTION_SEVERITY_HIGH" default_confidence = "DETECTION_CONFIDENCE_HIGH" } resource "barndoor_dlp_allow_list_entry" "codename_docs_site" { pattern = "aurora.docs.example.com" pattern_type = "PATTERN_TYPE_LITERAL" detection_types = [barndoor_dlp_custom_detection_type.codenames.detection_type] reason = "Public documentation host, not a leak" } resource "barndoor_dlp_enforcement_policy" "block_secrets_in_prompts" { name = "Block secrets in prompts" action = "POLICY_ACTION_BLOCK" provider_ids = ["openai"] runtime_stage = "RUNTIME_STAGE_PROMPT" dry_run = true detection_engine_ids = [barndoor_dlp_detection_engine.secrets.id] } ``` # Getting Started Source: https://docs.barndoor.ai/terraform/getting-started Generate a provider credential, configure the Barndoor Terraform provider, and apply your first resource This guide takes you from an empty directory to your first `terraform apply` against your Barndoor organization. > [!NOTE] > > **Estimated time**: 10–15 minutes ## Before You Begin You'll need: * A Barndoor account with **admin privileges** for your organization * [Terraform](https://developer.hashicorp.com/terraform/install) 1.0 or later (OpenTofu works too) ## Step 1: Generate a provider credential The provider authenticates as a machine credential scoped to your organization — no interactive login, no user tokens. 1. In the Barndoor app, go to **Settings → API Tokens**. 2. Find the **Terraform provider credentials** panel and click **Generate credential**. 3. Choose a **secret expiry** (90 days by default; you can rotate at any time). 4. Copy the three values from the reveal dialog: **Client ID**, **Client secret**, and **Organization ID**. The dialog also offers a ready-made Terraform configuration you can copy directly. > [!WARNING] > > The **client secret is shown only once**. If you lose it, rotate the credential to get a fresh secret — the client ID stays the same. > [!NOTE] > > **One credential is active per organization.** Rotating replaces the secret in place; revoking disables the credential entirely. If your team already uses Terraform with Barndoor, coordinate before rotating — a rotation invalidates the secret everyone else is using. ## Step 2: Configure the provider Create a working directory with a `main.tf`: ```hcl main.tf theme={null} terraform { required_providers { barndoor = { source = "barndoor-ai/barndoor" version = "~> 0.3" } } } provider "barndoor" { # The platform host root, with no path — the provider appends each # service's API prefix itself. base_url = "https://platform.barndoor.ai" token_url = "https://auth.barndoor.ai/realms/barndoor/protocol/openid-connect/token" client_id = "your-client-id" organization_id = "your-organization-id" # client_secret is read from the BARNDOOR_CLIENT_SECRET environment # variable — never commit it to configuration. } ``` Then export the secret: ```bash theme={null} export BARNDOOR_CLIENT_SECRET="the-secret-from-step-1" ``` Every provider argument has an environment-variable fallback, which is the recommended way to configure CI: | Argument | Environment variable | | - | - | | `base_url` | `BARNDOOR_BASE_URL` | | `token_url` | `BARNDOOR_TOKEN_URL` | | `client_id` | `BARNDOOR_CLIENT_ID` | | `client_secret` | `BARNDOOR_CLIENT_SECRET` | | `organization_id` | `BARNDOOR_ORGANIZATION_ID` | All five values are required — the provider fails with a clear error naming any that are missing. > [!WARNING] > > `base_url` is the **platform host root with no path**. The provider appends each service's API prefix itself, and rejects a `base_url` that carries a path suffix. ## Step 3: Write your first resource We'll create a data-protection allow-list entry — it has no dependencies, changes no runtime behavior beyond suppressing findings for one harmless literal, and is fully deleted on destroy. Add to `main.tf`: ```hcl main.tf theme={null} resource "barndoor_dlp_allow_list_entry" "quickstart" { pattern = "docs.example.com" pattern_type = "PATTERN_TYPE_LITERAL" reason = "Terraform quickstart — safe to delete" } ``` Reference: [`barndoor_dlp_allow_list_entry`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_allow_list_entry) ## Step 4: Init, plan, apply ```bash theme={null} terraform init terraform plan ``` The plan should show one resource to add. Apply it: ```bash theme={null} terraform apply ``` ```text theme={null} barndoor_dlp_allow_list_entry.quickstart: Creating... barndoor_dlp_allow_list_entry.quickstart: Creation complete after 1s Apply complete! Resources: 1 added, 0 changed, 0 destroyed. ``` ## Step 5: Verify Two quick checks that everything is wired correctly: 1. Run `terraform plan` again — it should report `No changes`, confirming that what Terraform created matches what the platform stored. 2. In the Barndoor app, open **Data Control Center** and find the allow-list entry you just created. ## Step 6: Clean up ```bash theme={null} terraform destroy ``` > [!WARNING] > > For this resource, destroy really deletes the entry. That is **not true of every resource**: destroying a `barndoor_policy` archives it, destroying an org-singleton like `barndoor_dlp_org_config` resets it to platform defaults, and destroying a `barndoor_mcp_server` tears down its connections. Check the resource's Registry page — and see the [destroy semantics table](/terraform/best-practices#destroy-is-not-always-delete) — before destroying anything you care about. ## Next Steps > [card] [Manage MCP Access](/terraform/manage-mcp-access) > > Onboard an MCP server, connect it, and govern which AI Agents can use it. > [card] [Manage the LLM Gateway](/terraform/llm-gateway) > > Providers, model routing, access policies, rate limits, and budgets. > [card] [Manage Data Protection](/terraform/data-protection) > > Detection types, allow lists, and enforcement policies. > [card] [Best Practices](/terraform/best-practices) > > Importing, drift, CI/CD, and troubleshooting. ## Troubleshooting > [accordion] Token request failed: invalid\_client > > The `client_id` / `client_secret` pair was rejected by the token endpoint. Confirm you exported `BARNDOOR_CLIENT_SECRET` in the shell running Terraform, and that the credential hasn't been rotated (rotation invalidates the old secret) or revoked. > [accordion] 403 errors mentioning the organization admin role > > The credential exists but isn't authorized for the operation. This usually means `organization_id` doesn't match the organization the credential was generated in — copy it from the credential panel in **Settings → API Tokens** rather than from elsewhere. > [accordion] base\_url must be the platform host root > > The provider rejects a `base_url` with a path suffix (for example a trailing `/api`). Use the bare origin, e.g. `https://platform.barndoor.ai`. > [accordion] The provider block validates but apply hangs or times out > > Check that `base_url` and `token_url` are reachable from the machine running Terraform — corporate proxies and VPNs are the usual cause. The provider uses plain HTTPS with a 30-second timeout per request. # Terraform Provider Source: https://docs.barndoor.ai/terraform/index Manage your Barndoor organization as code with the official Terraform provider The official Barndoor Terraform provider lets you manage your organization's configuration — MCP servers, access policies, LLM Gateway routing and controls, and data protection — as versioned, reviewable infrastructure-as-code. The provider is published on the Terraform Registry as [`barndoor-ai/barndoor`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest) and developed on [GitHub](https://github.com/barndoor-ai/terraform-provider-barndoor). > [card] [Getting Started](/terraform/getting-started) > > Generate a provider credential, configure the provider, and apply your first resource. > [card] [Manage MCP Access](/terraform/manage-mcp-access) > > Onboard an MCP server, connect it, register an AI Agent, and govern access with a policy. > [card] [Manage the LLM Gateway](/terraform/llm-gateway) > > Configure providers, model routing with failover, access policies, rate limits, and budgets. > [card] [Manage Data Protection](/terraform/data-protection) > > Define custom detection types, allow lists, and enforcement policies with a safe rollout path. > [card] [Best Practices](/terraform/best-practices) > > Importing existing configuration, avoiding drift, CI/CD, and troubleshooting. > [card] [Provider Reference](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs) > > The complete argument-level reference for every resource and data source, on the Terraform Registry. ## What you can manage This page groups the provider's resources by product area. For argument-level detail, each resource links to its [Terraform Registry](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs) reference page — the registry is always the authoritative schema documentation for the provider version you have installed. ### MCP Gateway | Resource | Manages | | - | - | | [`barndoor_mcp_server`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/mcp_server) | An MCP server instance created from a directory entry, including OAuth or pre-populated credentials | | [`barndoor_connection`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/connection) | A tenant-wide credential connection to an MCP server (non-OAuth providers) | | [`barndoor_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/policy) | An MCP access policy: which AI Agents may call which tools, under what conditions | | [`barndoor_agent`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/agent) | An AI Agent registration with your organization | Data sources: [`barndoor_mcp_server`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server), [`barndoor_agent`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent), and [`barndoor_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/policy) look up existing objects by ID or name so you can reference them without managing them. [`barndoor_mcp_server_directory`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server_directory) and [`barndoor_agent_directory`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent_directory) look up catalog entries by slug or name, so onboarding a server or registering an agent needs no hand-copied IDs. ### LLM Gateway | Resource | Manages | | - | - | | [`barndoor_llm_connection`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_connection) | A shareable credential for a model vendor: an API key, structured credentials, or an assumed IAM role | | [`barndoor_llm_provider`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_provider) | An upstream LLM provider (OpenAI, Anthropic, …), the connection it reads its credential from, and how its usage is billed | | [`barndoor_llm_model_mapping`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_mapping) | A route from a caller-facing model alias to an upstream model, with failover priority and cooldowns | | [`barndoor_llm_model_route_group`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_route_group) | A named set of route aliases that access policies can grant or deny as one | | [`barndoor_llm_routing_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_routing_policy) | A caller-facing alias that picks one of several model slots per request | | [`barndoor_llm_routing_rule`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_routing_rule) | A plain-English rule that sets a routing policy's minimum or banned slots for a kind of work | | [`barndoor_llm_model_access`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_access) | An allowlist or denylist of models for an organization, group, or user scope | | [`barndoor_llm_rate_limit`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_rate_limit) | Requests-per-minute and tokens-per-minute ceilings on a scope or on each member of an IdP group, optionally for one provider, model, alias or MCP server | | [`barndoor_llm_token_budget`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_token_budget) | Daily, weekly, or monthly token or spend budgets with alert thresholds, on a scope or on each member of an IdP group, optionally for one provider, model, alias or MCP server | | [`barndoor_llm_model_pricing`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_pricing) | Pricing rules used for cost attribution | | [`barndoor_llm_governance_config`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_governance_config) | Organization-wide LLM Gateway governance settings: pricing enforcement, default model access, and routing-policy enforcement | | [`barndoor_llm_api_key`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key) | A gateway API key for an app, a service, an IdP group or a user, with in-place rotation and expiry | | [`barndoor_llm_api_key_lifetime_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_policy) | The organization's default limit on how long API keys that users create for themselves may live | | [`barndoor_llm_api_key_lifetime_group_override`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_group_override), [`barndoor_llm_api_key_lifetime_user_override`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_user_override) | Exceptions to that limit for one IdP group or one user | Data source: [`barndoor_llm_provider`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/llm_provider) looks up a provider created in the Barndoor app by ID or name, so mappings, access policies, and pricing rules can reference it without managing it. ### Data Control Center | Resource | Manages | | - | - | | [`barndoor_dlp_org_config`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_org_config) | The organization's data protection master switch and global dry-run mode | | [`barndoor_dlp_detection_engine`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_detection_engine) | A detection engine (a Protection Profile in the app): which detection provider scans for which data types | | [`barndoor_dlp_custom_detection_type`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_custom_detection_type) | Organization-defined detection types built from literal and regex patterns | | [`barndoor_dlp_allow_list_entry`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_allow_list_entry) | Allow-list entries that suppress false-positive findings | | [`barndoor_dlp_enforcement_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_enforcement_policy) | Enforcement policies that block, redact, or tokenize findings in MCP or LLM traffic | | [`barndoor_dlp_field_control_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/dlp_field_control_policy) | Per-tool field rules applied to an MCP server's tool output | Data source: [`barndoor_dlp_detection_engine`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/dlp_detection_engine) looks up an existing Protection Profile by ID or name. ### Security & Access | Resource | Manages | | - | - | | [`barndoor_idp`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/idp) | Your organization's enterprise SSO / OIDC federation | | [`barndoor_log_export`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/log_export) | Streaming audit-log export to your own S3-compatible or Azure Blob Storage container | | [`barndoor_notification_channel`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/notification_channel) | Where admin alerts are delivered: an email address, a signed webhook, a Slack channel, or a Teams workflow | Data sources: [`barndoor_idp_settings`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/idp_settings), [`barndoor_log_export_aws_trust_info`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/log_export_aws_trust_info). ## When to use Terraform Terraform is the right tool when you want your Barndoor configuration to be reviewable, repeatable, and auditable — policy changes that go through pull requests, environments that can be rebuilt from code, and governance settings that can't drift silently. A few things intentionally remain portal-only: * **OAuth-connected MCP servers** — the interactive browser consent step can't be performed by a declarative apply. Terraform manages non-OAuth connections (`api_key`, `bearer_token`, `basic_auth`, `generic`); OAuth servers are connected in the Barndoor app. * **SSO enforcement and break-glass accounts** — enforcement is irreversible and member-impacting, so it stays behind the portal's confirmation flow. * **Interactive setup flows** such as provider catalogs and connectivity testing — including the Slack app install a `slack` notification channel depends on, and the channel **test** action. * **Personal notification preferences** — a user's own in-app and email alert settings belong to that user, not to the organization, so Terraform manages only the organization-wide channels. > [!TIP] > > Give each object exactly one owner: either Terraform or the portal. Managing the same policy or server from both places causes plans that fight the UI and vice versa. See [Best Practices](/terraform/best-practices#one-owner-per-object). ## Versioning and stability The provider follows semantic versioning. The platform APIs it uses are covered by Barndoor's public API stability contract: changes within a major version are additive, and breaking changes ship as a new API version served in parallel with the old one for a deprecation window. Review the [provider changelog](https://github.com/barndoor-ai/terraform-provider-barndoor/blob/main/CHANGELOG.md) before upgrading, and pin a version range in your configuration: ```hcl theme={null} terraform { required_providers { barndoor = { source = "barndoor-ai/barndoor" version = "~> 0.3" } } } ``` # Manage the LLM Gateway Source: https://docs.barndoor.ai/terraform/llm-gateway Configure model routes with failover, access policies, route groups, rate limits, budgets, pricing, routing policies, and governance settings in Terraform This guide builds a governed LLM Gateway setup as code: a connection and provider for an upstream vendor, model routes with a failover alias, an access policy, usage controls, pricing, and the organization's governance settings. > [!NOTE] > > **Estimated time**: 20–30 minutes. Complete [Getting Started](/terraform/getting-started) first. For the concepts behind budgets, rate limits, and model access, see [LLM Controls](/how-tos/use-llm-controls). ## Before You Begin * A configured `provider "barndoor"` block (see [Getting Started](/terraform/getting-started)), using provider version 0.9.0 or later * An API key for your upstream model vendor (this guide uses OpenAI), passed in as a sensitive variable rather than committed to configuration ## Step 1: Create a connection and a provider Upstream keys live on a **connection** (shown as a credential under **LLM Management** → **Connections** in the app), and providers reference the connection rather than storing a key of their own. One connection can back several providers, so rotating its key rotates it for all of them. ```hcl theme={null} variable "openai_api_key" { type = string sensitive = true } resource "barndoor_llm_connection" "openai" { name = "OpenAI production key" model_provider = "openai" base_url = "https://api.openai.com" api_key = var.openai_api_key } resource "barndoor_llm_provider" "openai" { name = "OpenAI" model_provider = "openai" connection_id = barndoor_llm_connection.openai.id } ``` Reference: [`barndoor_llm_connection`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_connection), [`barndoor_llm_provider`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_provider) The provider takes its `auth_type`, resource settings and, when its own `base_url` is unset, its endpoint from the connection. Changing `connection_id` rebinds the provider in place. Removing it forces a replacement, because a provider can't be detached from its credential. `base_url` stops at the host: don't add `/v1` for OpenAI-compatible vendors, because the gateway appends the version itself. The provider rejects a trailing `/v1` at plan time and suggests the corrected URL. The connection's `api_key` is write-only. The platform never returns it, and Terraform reports only its last four characters as `key_last4`, but the value you supply is kept in your Terraform state. Treat state as secret (see [Best Practices](/terraform/best-practices)). > [!WARNING] > > **Upgrading from a provider version before 0.8.0?** Since platform v2.40.0, a provider can't store its own key, so creating `barndoor_llm_provider` with `api_key` fails with a `400` ("a provider cannot store its own key"). Move the key to a `barndoor_llm_connection` and set `connection_id`. Setting `api_key` or `auth_type` together with `connection_id` is a plan-time error, and `api_key` on the provider is deprecated. To reference a provider created in the Barndoor app instead, look it up by name with the [`barndoor_llm_provider` data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/llm_provider) and use `data.barndoor_llm_provider.openai.id` wherever this guide uses `barndoor_llm_provider.openai.id`: ```hcl theme={null} data "barndoor_llm_provider" "openai" { name = "OpenAI" } ``` The name match is case-insensitive. The data source also exposes `connection_id` and `health_status`, so you can surface connectivity problems as a Terraform output. ### Bedrock with an IAM role A connection can assume an IAM role instead of storing a key. The platform generates the external ID the role's trust policy must require, and the connection exposes it in `effective_settings`: ```hcl theme={null} resource "barndoor_llm_connection" "bedrock" { name = "Bedrock (us-east-1)" model_provider = "bedrock" auth_type = "aws_role" base_url = "https://bedrock-runtime.us-east-1.amazonaws.com" settings = jsonencode({ region = "us-east-1" iam_role_arn = "arn:aws:iam::123456789012:role/barndoor-bedrock" }) } output "bedrock_trust_policy_external_id" { value = jsondecode(barndoor_llm_connection.bedrock.effective_settings).external_id } ``` ### Subscriptions and unmetered providers Providers with a request-scoped OAuth passthrough (`claude_oauth`, `codex_oauth`) need no connection: callers bring their own subscription. Such a provider is billed flat rather than per token, so mark it `not_metered`. Token usage is still reported, but its cost is recorded as \$0: ```hcl theme={null} resource "barndoor_llm_provider" "claude_subscription" { name = "Claude (subscription)" model_provider = "anthropic" auth_type = "claude_oauth" base_url = "https://api.anthropic.com" billing_mode = "not_metered" billing_reason = "subscription" } ``` `not_metered` requires a `billing_reason` (`subscription`, `local`, `external` or `other`), and the optional `billing_note` holds up to 200 characters of context. If your configuration never sets the billing attributes, Terraform leaves billing set in the app alone. Changing `billing_mode` doesn't change the cost of usage already recorded. ## Step 2: Enable models with 1:1 mappings A model mapping makes an upstream model servable through the gateway. A 1:1 mapping (alias equals upstream model) is the enablement: ```hcl theme={null} resource "barndoor_llm_model_mapping" "gpt_4o" { provider_id = barndoor_llm_provider.openai.id model_alias = "gpt-5.5" upstream_model = "gpt-5.5" } ``` Reference: [`barndoor_llm_model_mapping`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_mapping) A 1:1 enablement is addressable as `/gpt-5.5`. Set `bare_alias = true` to also serve the bare name `gpt-5.5`. If the enablement already exists on the platform, for example because it was created in the app, applying this resource adopts and updates the existing row instead of failing. ## Step 3: Add a custom alias with failover Custom aliases decouple what your agents call from what serves it. You can re-point `fast` at a different model later without touching any agent: ```hcl theme={null} resource "barndoor_llm_model_mapping" "fast" { provider_id = barndoor_llm_provider.openai.id model_alias = "fast" upstream_model = "gpt-5.5" priority = 10 retry_on_429_count = 3 retry_on_429_max_wait_secs = 60 depends_on = [barndoor_llm_model_mapping.gpt_4o] } ``` > [!WARNING] > > **A custom alias requires the 1:1 enablement for its `(provider, upstream_model)` pair to exist first.** The API rejects orphan aliases. Terraform can't infer this ordering from the attribute values, so declare it with `depends_on`, as above. Without it, a fresh apply can fail intermittently depending on creation order. Multiple mappings with the same alias across providers form a failover chain ordered by `priority` (lower first). The `retry_on_429_*` settings control how the gateway rides out upstream rate limiting before failing over: `retry_on_429_count` is 0–10 retries, and `retry_on_429_max_wait_secs` caps how long it honors `Retry-After` (0–180 seconds). The optional `request_timeout_secs` (1–600, default 120) and `stream_idle_timeout_secs` (1–300, default 180) set per-route timeouts. The six optional `cooldown_*` attributes set when a failing route is taken out of rotation, and for how long. `cooldown_failure_threshold` failures within `cooldown_window_secs` start a cooldown of `cooldown_base_secs`, which doubles on each failed recovery probe up to `cooldown_max_secs`. `cooldown_429_default_secs` applies to a `429` without `Retry-After`, and `cooldown_overloaded_secs` to a `529`: ```hcl theme={null} resource "barndoor_llm_model_mapping" "fast" { # ...the arguments above, plus: cooldown_failure_threshold = 5 cooldown_window_secs = 60 cooldown_base_secs = 30 cooldown_max_secs = 600 } ``` `cooldown_failure_threshold = 0` turns cooldowns off for the route. `cooldown_base_secs`, `cooldown_429_default_secs` and a non-zero `cooldown_overloaded_secs` can't exceed `cooldown_max_secs`, and the provider checks this at plan time. Unset attributes take the platform defaults on create and keep their stored value afterwards, so a policy tuned in the app isn't reset. Cooldown attributes need platform v2.43.0 or later. See [Failover, Cooldowns, and Route Health](/how-tos/llm-gateway-failover-and-cooldowns) for how cooldowns work. ## Step 4: Restrict which models can be used An access policy allowlists (or denylists) models for a scope, such as the whole organization, an IdP group, or a single user: ```hcl theme={null} resource "barndoor_llm_model_access" "frontier_only" { name = "Frontier models only" scope_type = "org" policy_type = "allowlist" targets = [ { kind = "model_alias", alias = "gpt-*" }, ] } ``` Reference: [`barndoor_llm_model_access`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_access) A target can name a model alias pattern (as above), a specific upstream model (`kind = "model"`), an entire provider (`kind = "provider"`), a provider and alias pair (`kind = "provider_model"`), or a route group (`kind = "route_group"`). Policies apply to LLM traffic unless you set `traffic_type`. A route group is a named set of route aliases that policies can grant or deny as one: ```hcl theme={null} resource "barndoor_llm_model_route_group" "approved" { name = "Approved for production" model_aliases = ["fast", "gpt-5.5"] } resource "barndoor_llm_model_access" "production_agents" { name = "Production agents: approved models" scope_type = "group" scope_value = "production-agents" policy_type = "allowlist" targets = [ { kind = "route_group", group_id = barndoor_llm_model_route_group.approved.id }, ] } ``` Reference: [`barndoor_llm_model_route_group`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_route_group) The platform also changes a group's membership on its own. Renaming a route's alias moves the alias's memberships, and deleting a route's last mapping removes the alias from every group. Terraform reads `model_aliases` back, so either change shows up as a diff on the next plan. The platform doesn't check that a targeted group exists: an allowlist whose only target is an empty or deleted group denies every model. ## Step 5: Add rate limits Rate limits throttle a scope over a rolling 60-second window: ```hcl theme={null} resource "barndoor_llm_rate_limit" "org_ceiling" { name = "Org ceiling" scope_type = "org" requests_per_minute = 600 } resource "barndoor_llm_rate_limit" "engineering_tokens" { name = "Engineering token ceiling" scope_type = "group" scope_value = "engineering" tokens_per_minute = 250000 traffic_type = "llm" } ``` Reference: [`barndoor_llm_rate_limit`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_rate_limit) > [!WARNING] > > At least one of `requests_per_minute` / `tokens_per_minute` is required, and **removing one from your configuration clears that metric on the platform** rather than leaving it unchanged. One rate limit exists per scope, traffic type and set of targets; creating a duplicate fails with a conflict. Don't use the `llm_provider` or `model` scope types to limit one provider or model: the platform accepts them only for compatibility, and they don't match any traffic. Narrow the rule with a target instead: ```hcl theme={null} resource "barndoor_llm_rate_limit" "fast_alias" { name = "Fast alias ceiling" scope_type = "org" tokens_per_minute = 100000 traffic_type = "llm" target_model_alias = "fast" } ``` There are four targets: * `target_provider_id` narrows the rule to one provider. Add `target_upstream_model` to narrow it to one of that provider's models. * `target_model_alias` narrows it to one alias, matched against what the caller sent before routing. * `target_mcp_server_id` narrows it to one MCP server's tool traffic. It needs `traffic_type` `mcp` or `all`. An alias target can't be combined with a provider target, and an MCP target can't be combined with a model target. The provider checks these combinations at plan time. Rate-limit targets change in place, and removing one clears it. A target is part of a rule's identity, so an org-wide ceiling and a ceiling on one alias can coexist. ## Step 6: Set budgets Budgets cap total token consumption over a day, week, or month, the spend-control counterpart to rate limits: ```hcl theme={null} resource "barndoor_llm_token_budget" "org_monthly" { name = "Org monthly cap" scope_type = "org" period = "monthly" token_limit = 500000000 } resource "barndoor_llm_token_budget" "contractors_weekly" { name = "Contractors weekly cap" scope_type = "group" scope_value = "contractors" period = "weekly" token_limit = 5000000 alert_thresholds = [50, 75, 95] action_on_exhaust = "warn" traffic_type = "llm" } ``` Reference: [`barndoor_llm_token_budget`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_token_budget) Alert thresholds default to `[80, 90]` (percent), and `action_on_exhaust` defaults to `block`. `warn` lets traffic continue while notifying. One budget exists per scope, traffic type, period and set of targets. Periods reset at UTC boundaries: daily at 00:00, weekly on Monday, monthly on the 1st. To give every member of an IdP group their **own** allowance from a single rule, use a per-user budget with `member_of_group`. `scope_type = "group"` is the opposite: **one** allowance shared by the whole group. ```hcl theme={null} resource "barndoor_llm_token_budget" "contractor_each_weekly" { name = "Per-contractor weekly cap" scope_type = "user" member_of_group = "contractors" period = "weekly" token_limit = 1000000 } ``` `member_of_group` requires `scope_type = "user"` with neither `scope_id` nor `scope_value` set. Someone who joins the group picks up the allowance on their next request. Changing or removing it replaces the budget. `barndoor_llm_rate_limit` takes the same attribute, for per-member rate limits. A budget can cap spend instead of, or as well as, tokens. Spend is computed from your pricing rules (Step 7). Set `cost_limit` without `token_limit` for a cost-only budget. Budgets take the same `target_*` attributes as rate limits: ```hcl theme={null} resource "barndoor_llm_token_budget" "fast_daily_spend" { name = "Per-user daily spend on fast" scope_type = "user" period = "daily" cost_limit = 25 traffic_type = "llm" target_model_alias = "fast" } ``` `cost_limit` is in `currency` (default `USD`), with at most four decimal places. Removing a limit clears it in place. Unlike on rate limits, a budget's targets and `currency` can't be updated, so changing one replaces the budget. ## Step 7: Price your models Pricing rules set the per-million-token costs that usage reports and cost figures are calculated from: ```hcl theme={null} resource "barndoor_llm_model_pricing" "gpt55" { model_pattern = "gpt-5.5" model_provider = "openai" input_cost_per_million_tokens = 5 output_cost_per_million_tokens = 30 change_reason = "Managed by Terraform" } ``` Reference: [`barndoor_llm_model_pricing`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_model_pricing) For models whose vendor charges more for long prompts, add a `long_context` tier. A request whose prompt exceeds `threshold_prompt_tokens` bills all its tokens at the tier's rates: ```hcl theme={null} resource "barndoor_llm_model_pricing" "gemini_pro" { model_pattern = "gemini-2.5-pro" model_provider = "google_ai" input_cost_per_million_tokens = 1.25 output_cost_per_million_tokens = 10 long_context = { threshold_prompt_tokens = 200000 input_cost_per_million_tokens = 2.5 output_cost_per_million_tokens = 15 } } ``` > [!WARNING] > > **Provider versions before 0.9.0 drop long-context tiers.** Each price change appends a version that copies nothing from the one before it, and older versions never sent the tier. So a price change from Terraform deleted any tier set in the app. From 0.9.0 the tier is sent with every version, and a tier set in the app shows up as a diff. Pricing is versioned on the platform. Each price change appends a new version, so the resource's `id` changes on update by design. Set a future `effective_from` to schedule a change. `terraform destroy` archives the rule, keeping its history, rather than deleting it. Leave `sync_mode` at its default, `pinned`, so Barndoor's default-pricing updates never change a price Terraform owns. See [Manage Model Pricing](/how-tos/manage-model-pricing) for how rules are matched. ## Step 8: Route requests with a routing policy A routing policy is a caller-facing alias that picks one of several model **slots** for each request, instead of always calling one model. A small determiner model reads the request and chooses a slot. Routing rules, written in plain English, then set a minimum slot or ban slots for particular kinds of work: ```hcl theme={null} resource "barndoor_llm_routing_policy" "auto" { model_alias = "auto" determiner_model_alias = "fast" posture = "balanced" slots = [ { label = "Everyday", model_alias = "fast" }, { label = "Strong", model_alias = "OpenAI/gpt-5.5" }, ] context_breakpoints = [128000] depends_on = [barndoor_llm_model_mapping.fast] } resource "barndoor_llm_routing_rule" "contracts" { policy_id = barndoor_llm_routing_policy.auto.id name = "Contract review" description = "Contract review, legal analysis, or anything a customer will sign must use the strong slot." floor_slot = 1 } ``` Reference: [`barndoor_llm_routing_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_routing_policy), [`barndoor_llm_routing_rule`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_routing_rule) Callers send `auto` as the request model. Each slot's `model_alias` must already resolve to enabled routes. That means either a bare-callable alias, such as the custom `fast` alias from Step 3, or the provider-scoped form `/` of a 1:1 enablement. `context_breakpoints` needs one entry fewer than the number of slots. Its default, `[128000, 512000]`, only fits three slots, so set it explicitly for any other count. The provider checks the slot, breakpoint and default-slot rules at plan time. Rules refer to slots by index. List slots from cheapest to strongest, and `floor_slot = 1` then means "at least the second slot". The platform doesn't check the order against prices. Use `deny_slots` to ban slots. Rule conflicts the platform reports appear as warnings and don't fail the apply. Import a rule with `/`. ## Step 9: Governance settings `barndoor_llm_governance_config` manages the organization's single LLM Gateway governance configuration. With `require_pricing_for_mappings = true`, the gateway refuses to enable a model route that no pricing rule matches: ```hcl theme={null} resource "barndoor_llm_governance_config" "org" { require_pricing_for_mappings = true depends_on = [barndoor_llm_model_pricing.gpt55] } ``` Reference: [`barndoor_llm_governance_config`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_governance_config) Two optional attributes manage the other settings: * `default_model_access`: `allow` (the default) or `deny`. `deny` is **Require an explicit grant to use a model** on the **Model Access** page. It requires an enabled allowlist, such as the one in Step 4. * `require_routing_policy`: **Require requests to use a routing policy** on the **Routing Policies** page, so callers must send a policy alias such as `auto` from Step 8. The `/v1/systemone` classifier endpoint is exempt. An attribute you don't set keeps whatever is stored, so you can manage pricing enforcement in Terraform and leave the other settings to the app. > [!WARNING] > > **Provider versions before 0.8.0 reset these settings on every apply.** They sent only `require_pricing_for_mappings`, and the platform replaces the whole configuration on each save, so an organization set to `deny` in the app went back to `allow`. Upgrade before managing this resource in an organization that uses either setting. `terraform destroy` can't delete the configuration. It resets only `require_pricing_for_mappings`, so removing the resource never loosens model access. ## Step 10: Issue API keys and limit their lifetime Apps and agents call the gateway with a Barndoor API key. `barndoor_llm_api_key` issues one: here a service key bound to an IdP group, so the group's budgets, rate limits and model access apply to it: ```hcl theme={null} resource "barndoor_llm_api_key" "billing" { name = "billing-service" group_name = "engineering" expires_at = "2027-06-30T23:59:59Z" # Change this value to rotate the secret in place. rotation_trigger = { rotated = "2026-11" } grace_period_secs = 3600 } output "billing_api_key" { value = barndoor_llm_api_key.billing.key sensitive = true } ``` Reference: [`barndoor_llm_api_key`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key) > [!WARNING] > > **The key's secret is stored in your Terraform state.** The platform returns it only when the key is created or rotated, so `key` is kept in state, marked sensitive, for you to pass on, for example to a secrets manager. Use an encrypted remote backend with restricted access (see [Secrets and state hygiene](/terraform/best-practices#secrets-and-state-hygiene)). * **Rotation**: changing `rotation_trigger` issues a new secret in place. The key keeps its ID, agent binding and usage history. With `grace_period_secs` (up to 7 days), the previous secret keeps working for that long so clients can move over. A `time_rotating` resource's ID makes a good trigger for scheduled rotation. * **In-place changes**: `expires_at` and `disabled` change without a new secret, and extending an expired key reactivates it. Changing `name`, `user_id`, `group_name` or `scopes` creates a new key with a new secret. * **Destroy** revokes the key. To limit how long keys that people create for themselves may live, set an organization default and, where needed, exceptions for a group or a user: ```hcl theme={null} # Every self-serve key gets exactly 60 days; users don't pick an expiry. resource "barndoor_llm_api_key_lifetime_policy" "org" { max_lifetime_days = 60 fixed_lifetime = true } # Contractors' keys expire within a week. resource "barndoor_llm_api_key_lifetime_group_override" "contractors" { group_name = "contractors" max_lifetime_days = 7 } ``` References: [`barndoor_llm_api_key_lifetime_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_policy), [`barndoor_llm_api_key_lifetime_group_override`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_group_override), [`barndoor_llm_api_key_lifetime_user_override`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/llm_api_key_lifetime_user_override) A user's own override wins. Otherwise the strictest of their groups' overrides applies, and otherwise the default. An override with no limits exempts its group or user. Keys created by admins, including those Terraform creates, are exempt, and existing keys keep their expiry: the policy is checked when a key is created or rotated. These resources need provider 0.11.0 and platform v2.52.0 or later. ## Behavior worth knowing * **Scope immutability**: changing the scope of a budget forces a replacement. On model access policies and rate limits, removing `scope_id` or `scope_value` also forces a new resource. * **Two-step creates**: some LLM Gateway resources are created with a follow-up update under the hood, because not every field is settable on create. If an apply is interrupted at exactly the wrong moment, a partially configured object can exist. A re-apply converges it, or the next plan shows the difference. * **Verify in the app**: everything in this guide is visible under **LLM Management** in the Barndoor app. Model routes and pricing are in the **Models** section, and budgets, rate limits, and model access are under **Controls** (see [LLM Controls](/how-tos/use-llm-controls)). API keys and key policies are under **Access**. ## Complete example **Full configuration from this guide** ```hcl theme={null} variable "openai_api_key" { type = string sensitive = true } resource "barndoor_llm_connection" "openai" { name = "OpenAI production key" model_provider = "openai" base_url = "https://api.openai.com" api_key = var.openai_api_key } resource "barndoor_llm_provider" "openai" { name = "OpenAI" model_provider = "openai" connection_id = barndoor_llm_connection.openai.id } resource "barndoor_llm_model_mapping" "gpt_4o" { provider_id = barndoor_llm_provider.openai.id model_alias = "gpt-5.5" upstream_model = "gpt-5.5" } resource "barndoor_llm_model_mapping" "fast" { provider_id = barndoor_llm_provider.openai.id model_alias = "fast" upstream_model = "gpt-5.5" priority = 10 retry_on_429_count = 3 retry_on_429_max_wait_secs = 60 depends_on = [barndoor_llm_model_mapping.gpt_4o] } resource "barndoor_llm_model_access" "frontier_only" { name = "Frontier models only" scope_type = "org" policy_type = "allowlist" targets = [ { kind = "model_alias", alias = "gpt-*" }, ] } resource "barndoor_llm_rate_limit" "org_ceiling" { name = "Org ceiling" scope_type = "org" requests_per_minute = 600 } resource "barndoor_llm_token_budget" "org_monthly" { name = "Org monthly cap" scope_type = "org" period = "monthly" token_limit = 500000000 } resource "barndoor_llm_model_pricing" "gpt55" { model_pattern = "gpt-5.5" model_provider = "openai" input_cost_per_million_tokens = 5 output_cost_per_million_tokens = 30 change_reason = "Managed by Terraform" } resource "barndoor_llm_governance_config" "org" { require_pricing_for_mappings = true depends_on = [barndoor_llm_model_pricing.gpt55] } resource "barndoor_llm_api_key" "billing" { name = "billing-service" group_name = "engineering" expires_at = "2027-06-30T23:59:59Z" rotation_trigger = { rotated = "2026-11" } grace_period_secs = 3600 } output "billing_api_key" { value = barndoor_llm_api_key.billing.key sensitive = true } resource "barndoor_llm_api_key_lifetime_policy" "org" { max_lifetime_days = 60 fixed_lifetime = true } resource "barndoor_llm_api_key_lifetime_group_override" "contractors" { group_name = "contractors" max_lifetime_days = 7 } ``` # Manage MCP Access Source: https://docs.barndoor.ai/terraform/manage-mcp-access Onboard an MCP server, connect it tenant-wide, register an AI Agent, and govern access with a policy — all in Terraform This guide builds the core Barndoor workflow as code: an MCP server your organization can reach, a credential connection for it, a registered AI Agent, and an access policy that governs what that agent may do. > [!NOTE] > > **Estimated time**: 20–30 minutes. Complete [Getting Started](/terraform/getting-started) first — this guide assumes a working provider configuration. ## Before You Begin * A configured `provider "barndoor"` block (see [Getting Started](/terraform/getting-started)) * An API key for the service your MCP server fronts (this guide uses a non-OAuth server) * The catalog **slug or name** of the MCP server you want to onboard and the **name** of the agent you want to register — directory entries are looked up by data source, so no IDs need to be copied from the app ## Step 1: Onboard the MCP server If the server is new to your organization, create it from its directory entry. If it was already onboarded in the portal, look it up with a data source instead — don't manage the same server from both places. > [tab] New server > > ```hcl theme={null} > # Look up the catalog entry by its connector slug (or name, or id). > data "barndoor_mcp_server_directory" "search" { > slug = "search" > } > > resource "barndoor_mcp_server" "search" { > name = "Search" > mcp_server_directory_id = data.barndoor_mcp_server_directory.search.id > } > ``` > [tab] Existing server (data source) > > ```hcl theme={null} > data "barndoor_mcp_server" "search" { > # Look up by name, slug, or id. Name matching is case- and > # whitespace-insensitive; an ambiguous name fails with candidates. > name = "Search" > } > ``` References: [`barndoor_mcp_server` resource](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/mcp_server), [data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server), [`barndoor_mcp_server_directory` data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/mcp_server_directory) > [!NOTE] > > Server names are unique within an organization (case- and whitespace-insensitively), and destroying a `barndoor_mcp_server` soft-deletes it: its connections and stored credentials are torn down, and the name is freed for reuse. ## Step 2: Connect it tenant-wide A `barndoor_connection` stores a service-account-owned credential for the server, so every authorized agent can use it without each user connecting individually: ```hcl theme={null} resource "barndoor_connection" "search" { server_id = barndoor_mcp_server.search.id # Write-only: stored in Barndoor's secret store, never returned by the API. api_key = var.search_api_key } variable "search_api_key" { type = string sensitive = true } ``` Reference: [`barndoor_connection`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/connection) > [!WARNING] > > **OAuth servers can't be connected by Terraform** — the interactive browser consent can't happen inside a declarative apply. Terraform supports the non-OAuth credential providers (`api_key`, `bearer_token`, `basic_auth`, `generic`); connect OAuth servers in the Barndoor app. Also note: an organization can have at most **one tenant-wide connection per server**, and changing any credential attribute replaces the connection. ## Step 3: Register the AI Agent Registration attaches the agent's directory entry to your organization and creates the service account that policies bind to: ```hcl theme={null} data "barndoor_agent_directory" "assistant" { name = "Assistant" } resource "barndoor_agent" "assistant" { application_directory_id = data.barndoor_agent_directory.assistant.id llm_gateway_enabled = true } ``` References: [`barndoor_agent`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/agent), [`barndoor_agent_directory` data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent_directory) An agent directory entry can have one live registration per organization. To reference an agent registered outside Terraform, use the [`barndoor_agent` data source](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/data-sources/agent). ## Step 4: Govern access with a policy The policy is where the three pieces meet: it binds the agent (`application_ids`) to the server (`mcp_server_id`) and defines what's allowed: ```hcl theme={null} resource "barndoor_policy" "search_read_only" { name = "Search read-only for the assistant" mcp_server_id = barndoor_mcp_server.search.id description = "The assistant may run searches; everything else is blocked." support_contact = "platform@example.com" status = "ACTIVE" # DRAFT (default), ACTIVE, or INACTIVE application_ids = [barndoor_agent.assistant.id] tags = ["search", "terraform-managed"] rules = [ { name = "allow searches" effect = "ALLOW" actions = ["tools/call:search", "tools/call:get_document"] roles = ["*"] }, ] } ``` Reference: [`barndoor_policy`](https://registry.terraform.io/providers/barndoor-ai/barndoor/latest/docs/resources/policy) > [!WARNING] > > **Always set `actions` and `roles` explicitly on every rule.** If you omit either list, the platform API defaults it to `["*"]` — *everything*. An "allow" rule you meant to scope narrowly becomes an allow-all. Write `["*"]` only when you mean it. ### Requiring approval for a tool A tool can be granted outright or granted subject to user approval. The distinction lives in the action string: * `tools/call:` — runs without confirmation. * `tools/call::approve` — the user approves the specific call before it runs. A tool listed in no applicable rule is not granted at all. ```hcl theme={null} rules = [ { name = "reads free, writes reviewed" effect = "ALLOW" actions = [ "tools/call:search", "tools/call:get_document", "tools/call:update_document:approve", ] roles = ["*"] }, ] ``` > [!WARNING] > > Use one form per tool, and check the whole rule set before relying on an `:approve` grant. Where several rules apply to the same principal the **most permissive** grant wins (`tools/call:X` beats `tools/call:X:approve` beats absence), so a broad plain grant elsewhere in the policy silently removes the approval gate you configured here. > [!NOTE] > > Approval prompting happens on Barndoor's tool-router path. A client connecting straight to the MCP endpoint executes an `:approve`-only grant without prompting — omit the tool instead if you need it stopped on every path. See [Granular Tool Use Confirmations](/how-tos/tool-confirmations) for the behaviour end to end. ### Conditional rules Rules accept an optional condition tree, passed as JSON. Each node has exactly one of `expr` or a combinator (`all` / `any` / `none`) with `of = [...]`: ```hcl theme={null} rules = [ { name = "allow small reads" effect = "ALLOW" actions = ["tools/call:search"] roles = ["role:analyst"] condition = jsonencode({ all = { of = [ { expr = { expr = "request.size < 100" } }, ] } }) }, ] ``` > [!TIP] > > Start new policies in `DRAFT` (the default), review the result in the Barndoor app under **MCP Gateway → Policies**, then flip `status` to `ACTIVE` in a follow-up apply — the same draft-then-activate flow the portal uses. ## Lifecycle notes * **Destroy archives, it doesn't delete.** Destroying a `barndoor_policy` moves it to `ARCHIVED` — the platform's terminal lifecycle state, kept for audit history. The name is freed for non-archived reuse. * **`mcp_server_id` is immutable** on a policy; changing it forces a replacement (a new policy is created and the old one archived). * **Importing existing objects:** all four resources support `terraform import`. Policies, servers, and agents import by ID; connections import by their **server ID** (or slug). See [Best Practices → Importing](/terraform/best-practices#importing-existing-configuration). ## Complete example **Full configuration from this guide** ```hcl theme={null} data "barndoor_mcp_server_directory" "search" { slug = "search" } resource "barndoor_mcp_server" "search" { name = "Search" mcp_server_directory_id = data.barndoor_mcp_server_directory.search.id } resource "barndoor_connection" "search" { server_id = barndoor_mcp_server.search.id api_key = var.search_api_key } data "barndoor_agent_directory" "assistant" { name = "Assistant" } resource "barndoor_agent" "assistant" { application_directory_id = data.barndoor_agent_directory.assistant.id llm_gateway_enabled = true } resource "barndoor_policy" "search_read_only" { name = "Search read-only for the assistant" mcp_server_id = barndoor_mcp_server.search.id description = "The assistant may run searches; everything else is blocked." support_contact = "platform@example.com" status = "ACTIVE" application_ids = [barndoor_agent.assistant.id] tags = ["search", "terraform-managed"] rules = [ { name = "allow searches" effect = "ALLOW" actions = ["tools/call:search", "tools/call:get_document"] roles = ["*"] }, ] } variable "search_api_key" { type = string sensitive = true } ```