> ## Documentation Index
> Fetch the complete documentation index at: https://developers.telnyx.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Add a guardrail

> Adds a check the instance runs on model and tool requests. It runs on every request when `always_on`, and otherwise on the requests that name it in `guardrails`. The instance must be `ready`; otherwise the request answers `409`.



## OpenAPI

````yaml /openapi/source/external/agent-gateway/agent-gateway.json post /agent_gateways/{instance_id}/guardrails
openapi: 3.1.0
info:
  version: 1.0.0
  title: Telnyx API
  x-latency-category: interactive
  x-endpoint-cost: light
  description: >-
    Agent Gateway authenticates, authorizes, and audits the requests agents send
    to models, tools, and other agents. Each gateway runs as a dedicated
    instance on the account's
    [*Network*](https://developers.telnyx.com/docs/network/overview). This API
    creates, lists, and deletes instances, and manages the keys, teams, spend
    logs, MCP servers, APIs, tool permissions, and guardrails on them. Each
    instance serves an OpenAI-compatible API at its `gateway_url`.
servers:
  - url: https://api.telnyx.com/v2
    description: Telnyx API v2
security:
  - bearerAuth: []
tags:
  - name: Agent Gateways
    description: Create, list, retrieve, and delete Agent Gateway instances.
  - name: Agent Gateway Keys
    description: Keys on an instance.
  - name: Agent Gateway Teams
    description: 'Teams on an instance: shared model lists, budgets, and rate limits.'
  - name: Agent Gateway Spend Logs
    description: The requests an instance served, with their cost.
  - name: Agent Gateway MCP Servers
    description: MCP servers on an instance, served to agents at one MCP endpoint.
  - name: Agent Gateway APIs
    description: REST APIs on an instance, served to agents as tools.
  - name: Agent Gateway Tool Permissions
    description: The MCP servers and tools a key or team may use.
  - name: Agent Gateway Guardrails
    description: Checks an instance runs on model and tool requests.
  - name: Agent Gateway Policies
    description: Named sets of guardrails an instance applies to requests.
  - name: Agent Gateway Policy Attachments
    description: Where an instance applies each policy.
paths:
  /agent_gateways/{instance_id}/guardrails:
    post:
      tags:
        - Agent Gateway Guardrails
      summary: Add a guardrail
      description: >-
        Adds a check the instance runs on model and tool requests. It runs on
        every request when `always_on`, and otherwise on the requests that name
        it in `guardrails`. The instance must be `ready`; otherwise the request
        answers `409`.
      operationId: CreateAgentGatewayGuardrail
      parameters:
        - name: instance_id
          in: path
          required: true
          description: The Agent Gateway's `id`.
          schema:
            type: string
            format: uuid
          example: 32ce035d-3165-4031-b1a7-a7c0c259590a
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/AgentGatewayGuardrailCreate'
            examples:
              mask:
                summary: Mask personal data
                value:
                  name: mask-pii
                  modes:
                    - before_request
                  type: content_filter
                  settings:
                    patterns:
                      - name: us_ssn
                        action: mask
                      - name: email
                        action: mask
              code:
                summary: Custom code
                value:
                  name: no-forbidden
                  modes:
                    - before_request
                  type: custom_code
                  settings:
                    code: |
                      def apply_guardrail(inputs, request_data, input_type):
                          for text in inputs["texts"]:
                              if "forbidden" in text.lower():
                                  return block("The word forbidden is not allowed")
                          return allow()
      responses:
        '201':
          description: The added guardrail
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/AgentGatewayGuardrailResponse'
              example:
                data:
                  id: 9645e556-6532-4341-8cab-21b58cdef529
                  name: mask-pii
                  modes:
                    - before_request
                  always_on: false
                  type: content_filter
                  settings:
                    patterns:
                      - name: us_ssn
                        action: mask
                      - name: email
                        action: mask
                    regexes: []
                    keywords: []
                    categories: []
                  created_at: '2026-10-28T17:07:48.905000Z'
                  updated_at: '2026-10-28T17:07:48.905000Z'
        '400':
          description: A name the instance already uses
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '10012'
                    title: Duplicate resource
                    detail: Resource is a duplicate.
                    meta:
                      url: https://developers.telnyx.com/docs/overview/errors/10012
                    source:
                      pointer: /name
        '401':
          description: Unauthorized
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '10009'
                    title: Authentication failed
                    detail: >-
                      The required authentication headers were either invalid or
                      not included in the request.
                    meta:
                      url: https://developers.telnyx.com/docs/overview/errors/10009
        '404':
          description: Not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '10005'
                    title: Resource not found
                    detail: The requested resource or URL could not be found.
                    meta:
                      url: https://developers.telnyx.com/docs/overview/errors/10005
        '409':
          description: The instance is not `ready`
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '99901'
                    title: Instance not ready
                    detail: The instance is not ready; its engine is not running.
        '422':
          description: A mode the type does not run in
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '10027'
                    title: Unprocessable Entity
                    detail: The type does not run in one of these modes.
                    meta:
                      url: https://developers.telnyx.com/docs/overview/errors/10027
                    source:
                      pointer: /modes
        '502':
          description: The instance's engine did not answer
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TelnyxErrors'
              example:
                errors:
                  - code: '99903'
                    title: Engine unavailable
                    detail: The instance's engine did not answer; try again shortly.
      x-codeSamples:
        - lang: JavaScript
          source: >-
            import Telnyx from 'telnyx';


            const client = new Telnyx({
              apiKey: process.env['TELNYX_API_KEY'], // This is the default and can be omitted
            });


            const AgentGatewayGuardrail = await
            client.agentGateways.guardrails.create('instance_id', {
              modes: [],
              name: 'name',
              type: 'content_filter',
            });


            console.log(AgentGatewayGuardrail.data);
        - lang: Python
          source: |
            import os
            from telnyx import Telnyx

            client = Telnyx(
                api_key=os.environ.get("TELNYX_API_KEY"),  # This is the default and can be omitted
            )
            agent_gateway_guardrail = client.agent_gateways.guardrails.create(
                instance_id="instance_id",
                modes=[],
                name="name",
                type="content_filter",
            )
            print(agent_gateway_guardrail.data)
        - lang: Go
          source: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/team-telnyx/telnyx-go\"\n\t\"github.com/team-telnyx/telnyx-go/option\"\n)\n\nfunc main() {\n\tclient := telnyx.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tguardrail, err := client.AgentGateways.Guardrails.New(\n\t\tcontext.TODO(),\n\t\t\"instance_id\",\n\t\ttelnyx.AgentGatewayGuardrailNewParams{\n\t\t\tModes: \"modes\",\n\t\t\tName:  \"name\",\n\t\t\tType:  \"content_filter\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", guardrail.Data)\n}\n"
        - lang: Java
          source: >-
            package com.telnyx.sdk.example;


            import com.telnyx.sdk.client.TelnyxClient;

            import com.telnyx.sdk.client.okhttp.TelnyxOkHttpClient;

            import
            com.telnyx.sdk.models.agentGateways.guardrails.GuardrailCreateParams;

            import java.util.List;


            public final class Main {
                private Main() {}

                public static void main(String[] args) {
                    TelnyxClient client = TelnyxOkHttpClient.fromEnv();

                    GuardrailCreateParams params = GuardrailCreateParams.builder()
                        .modes(List.of())
                        .name("name")
                        .type(GuardrailCreateParams.Type.CONTENT_FILTER)
                        .build();
                    var response = client.agentGateways().guardrails().create("instance_id", params);
                }
            }
        - lang: Ruby
          source: |-
            require "telnyx"

            telnyx = Telnyx::Client.new(api_key: "My API Key")

            agent_gateway_guardrail = telnyx.agent_gateways.guardrails.create(
              "instance_id",
              modes: [],
              name: "name",
              type: :content_filter
            )

            puts(agent_gateway_guardrail)
        - lang: PHP
          source: >-
            <?php


            require_once dirname(__DIR__) . '/vendor/autoload.php';


            use Telnyx\Client;

            use Telnyx\Core\Exceptions\APIException;


            $client = new Client(apiKey: getenv('TELNYX_API_KEY') ?: 'My API
            Key');


            try {
              $agent_gateway_guardrail = $client->agentGateways->guardrails->create(
                'instance_id',
                modes: [],
                name: 'name',
                type: 'content_filter',
              );

              var_dump($agent_gateway_guardrail);
            } catch (APIException $e) {
              echo $e->getMessage();
            }
        - lang: CLI
          source: |-
            telnyx agent-gateways:guardrails create \
              --api-key 'My API Key' \
              --instance-id 32ce035d-3165-4031-b1a7-a7c0c259590a \
              --name name \
              --modes before_request \
              --type content_filter
components:
  schemas:
    AgentGatewayGuardrailCreate:
      type: object
      required:
        - name
        - modes
        - type
      additionalProperties: false
      properties:
        name:
          type: string
          pattern: ^[A-Za-z0-9_.-]{1,100}$
          description: >-
            A name, unique on the instance. A request names it in its
            `guardrails` field.
        modes:
          type: array
          minItems: 1
          items:
            type: string
            enum:
              - before_request
              - during_request
              - after_request
              - logging_only
              - before_tool_request
              - during_tool_request
              - after_tool_request
          description: When the guardrail runs. Each type runs in some modes only.
        always_on:
          type: boolean
          default: false
          description: >-
            `true` runs the guardrail on every request, and a request cannot
            turn it off. `false` runs it on the requests that name it.
        type:
          type: string
          enum:
            - content_filter
            - tool_permission
            - model_judge
            - custom_code
            - lakera
            - presidio
            - bedrock
            - azure_content_safety
          description: The kind of check. It cannot change after create.
        settings:
          type: object
          additionalProperties: true
          description: >-
            The type's settings. `content_filter`: `patterns` (prebuilt patterns
            by `name`, such as `us_ssn` or `email`), `regexes` (each a `name`,
            which tags masked matches, and a `pattern`), `keywords` (each a
            `keyword`), and `categories` (each a `name`), each entry with an
            `action` of `block` or `mask`. `tool_permission`: `rules` (`id`,
            `tool_name`, `tool_type`, `decision`, `argument_patterns`), a
            `default` decision, and `on_denied` (`block` or `rewrite`).
            `model_judge`: a `model` on the instance and weighted `criteria`
            (`name`, `description`, `weight`, the weights summing to 100).
            `custom_code`: `code` defining `apply_guardrail(inputs,
            request_data, input_type)`. `lakera`: `api_key`, `project_id`,
            `api_base`. `presidio`: `analyzer_url`, `anonymizer_url`, `entities`
            (entity name to `block` or `mask`), `language`. `bedrock`:
            `guardrail_id`, `version`, `region`, and `access_key_id` with
            `secret_access_key`, or `role_name`. `azure_content_safety`:
            `api_key`, `endpoint`, `severity` (0 to 7). Provider secrets are
            write-only.
    AgentGatewayGuardrailResponse:
      type: object
      required:
        - data
      properties:
        data:
          $ref: '#/components/schemas/AgentGatewayGuardrail'
    TelnyxErrors:
      type: object
      properties:
        errors:
          type: array
          items:
            $ref: '#/components/schemas/TelnyxError'
    AgentGatewayGuardrail:
      type: object
      required:
        - id
        - name
        - modes
        - always_on
        - type
        - settings
        - created_at
        - updated_at
      properties:
        id:
          type: string
          format: uuid
          description: Identifies the guardrail.
        name:
          type: string
          description: What a request names in its `guardrails` field.
        modes:
          type: array
          items:
            type: string
            enum:
              - before_request
              - during_request
              - after_request
              - logging_only
              - before_tool_request
              - during_tool_request
              - after_tool_request
          description: When the guardrail runs.
        always_on:
          type: boolean
          description: Whether it runs on every request.
        type:
          type: string
          enum:
            - content_filter
            - tool_permission
            - model_judge
            - custom_code
            - lakera
            - presidio
            - bedrock
            - azure_content_safety
        settings:
          type: object
          additionalProperties: true
          description: >-
            The type's settings. `content_filter`: `patterns` (prebuilt patterns
            by name, such as `us_ssn` or `email`), `regexes`, `keywords`, and
            `categories` (such as `prompt_injection`), each with an `action` of
            `block` or `mask`. `tool_permission`: `rules` (`id`, `tool_name`,
            `tool_type`, `decision`, `argument_patterns`), a `default` decision,
            and `on_denied` (`block` or `rewrite`). `model_judge`: a `model` on
            the instance and weighted `criteria` (`name`, `description`,
            `weight`, the weights summing to 100). `custom_code`: `code`
            defining `apply_guardrail(inputs, request_data, input_type)`.
            `lakera`: `api_key`, `project_id`, `api_base`. `presidio`:
            `analyzer_url`, `anonymizer_url`, `entities` (entity name to `block`
            or `mask`), `language`. `bedrock`: `guardrail_id`, `version`,
            `region`, and `access_key_id` with `secret_access_key`, or
            `role_name`. `azure_content_safety`: `api_key`, `endpoint`,
            `severity` (0 to 7). Provider secrets are write-only. Responses
            leave the secrets out.
        created_at:
          type:
            - string
            - 'null'
          format: date-time
        updated_at:
          type:
            - string
            - 'null'
          format: date-time
    TelnyxError:
      type: object
      properties:
        code:
          type: string
        title:
          type: string
        detail:
          type: string
        source:
          type: object
          properties:
            pointer:
              type: string
            parameter:
              type: string
        meta:
          type: object
          properties:
            url:
              type: string
  securitySchemes:
    bearerAuth:
      type: http
      scheme: bearer
      description: Telnyx API key

````