SPB Git

Repository Public

inference-hooks-endpoint.md 41.3 KB 739 lines markdown

1---2title: Develop an Inference hooks integration3url: https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint4description: Build the AI security server that receives signed Inference hooks requests, verifies them, and returns allow or deny verdicts.5---67<Note>8  Inference hooks are in beta and available to Claude Enterprise organizations. Field names, request shapes, and headers may change during the beta.9</Note>1011An Inference hooks integration is an AI security server: an HTTPS service that Anthropic calls. For each governed request, your server receives a signed `POST` carrying the conversation transcript and responds with an allow or deny verdict. This page documents the protocol for building that server: the request and verdict schemas, signature verification, and the operational contract.1213To turn Inference hooks on and point them at your endpoint, see [Configure Inference hooks](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration). To learn what Inference hooks are and when to use them, see the [Inference hooks overview](https://platform.claude.com/docs/en/manage-claude/inference-hooks).1415## Get a first verdict round trip1617The smallest working integration is a server that reads each request and allows it. Run one of the following servers, expose it at a public `https://` URL (for example, behind a TLS-terminating reverse proxy on a host you control, not a reverse-tunnel service; see [Receive a request](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#receive-a-request)), then have your administrator [set it as the endpoint and test the connection](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration): the **Test connection** result reports the allow verdict your server returned.1819<CodeGroup exclude="shell">20  ```python Python21  # Run with: python server.py22  from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer232425  class VerdictHandler(BaseHTTPRequestHandler):26      protocol_version = "HTTP/1.1"  # keep the connection open between verdicts2728      def do_POST(self):29          # Drain the body; transcripts can be megabytes.30          self.rfile.read(int(self.headers.get("Content-Length", 0)))31          verdict = b'{"action": "allow"}'32          self.send_response(200)33          self.send_header("Content-Type", "application/json")34          self.send_header("Content-Length", str(len(verdict)))35          self.end_headers()36          self.wfile.write(verdict)373839  ThreadingHTTPServer(("", 8000), VerdictHandler).serve_forever()40  ```4142  ```typescript TypeScript43  // Run with: node server.ts44  import { createServer } from "node:http";4546  createServer((request, response) => {47    // Drain the body before answering; transcripts can be megabytes.48    request.resume();49    request.on("end", () => {50      response.writeHead(200, { "Content-Type": "application/json" });51      response.end('{"action": "allow"}');52    });53  }).listen(8000);54  ```5556  ```csharp C#57  #:sdk Microsoft.NET.Sdk.Web58  #:property PublishAot=false59  // Run with: dotnet run server.cs6061  var app = WebApplication.Create();6263  app.MapPost("/{**path}", async (HttpRequest request) =>64  {65      // Drain the body; transcripts can be megabytes.66      await request.Body.CopyToAsync(Stream.Null);67      return Results.Text("""{"action": "allow"}""", "application/json");68  });6970  app.Run("http://0.0.0.0:8000");71  ```7273  ```go Go74  // Run with: go run server.go75  package main7677  import (78  	"io"79  	"log"80  	"net/http"81  )8283  func main() {84  	http.HandleFunc("POST /", func(writer http.ResponseWriter, request *http.Request) {85  		// Drain the body so the connection can be reused; transcripts can be megabytes.86  		io.Copy(io.Discard, request.Body)87  		writer.Header().Set("Content-Type", "application/json")88  		writer.Write([]byte(`{"action": "allow"}`))89  	})90  	log.Fatal(http.ListenAndServe(":8000", nil))91  }92  ```9394  ```java Java95  // Run with: java VerdictServer.java96  import com.sun.net.httpserver.HttpServer;9798  void main() throws IOException {99      HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);100      server.createContext("/", exchange -> {101          // Drain the body without buffering it; transcripts can be megabytes.102          exchange.getRequestBody().transferTo(OutputStream.nullOutputStream());103          byte[] verdict = "{\"action\": \"allow\"}".getBytes(StandardCharsets.UTF_8);104          exchange.getResponseHeaders().set("Content-Type", "application/json");105          exchange.sendResponseHeaders(200, verdict.length);106          try (OutputStream responseBody = exchange.getResponseBody()) {107              responseBody.write(verdict);108          }109      });110      server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());111      server.start();112  }113  ```114115  ```php PHP116  <?php117  // Run with: php -S 0.0.0.0:8000 server.php118119  // Drain the body; transcripts can be megabytes.120  file_get_contents('php://input');121122  http_response_code(200);123  header('Content-Type: application/json');124  echo '{"action": "allow"}';125  ```126127  ```ruby Ruby128  # webrick is a regular gem in Ruby 3.4: gem install webrick, or add gem "webrick".129  # Run with: ruby server.rb130  require "webrick"131132  server = WEBrick::HTTPServer.new(Port: 8000)133  server.mount_proc("/") do |request, response|134    request.body # Drain the body; transcripts can be megabytes.135    response.status = 200136    response["Content-Type"] = "application/json"137    response.body = '{"action": "allow"}'138  end139  server.start140  ```141</CodeGroup>142143<Note>144  These servers accept every request, including unsigned ones. Add [signature verification](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#verify-the-signature) before you enforce.145</Note>146147## Receive a request148149Anthropic sends an HTTPS `POST` to the URL your administrator configures. The whole configured URL is the endpoint: there is no fixed path suffix, so choose any path that suits your server.150151Host your AI security server where Anthropic can reach it: an `https://` URL on port 443, on a publicly routable host (private, loopback, and carrier-grade NAT ranges are refused at connect time), with a certificate that validates against the public CA trust store, responding without redirects. The configured URL must be the final destination. Reverse-tunnel hosts (ngrok and similar tunnel services) are not supported: Anthropic's network policy blocks them. Host your server on a domain you control. [Configure Inference hooks](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration) covers how your administrator sets and tests the URL.152153Every request carries these fixed headers, along with any [custom request headers](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration) your administrator configured and, once your organization has a signing secret, the `webhook-*` signature headers described in [Verify the signature](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#verify-the-signature):154155| Header            | Value              |156| ----------------- | ------------------ |157| `Content-Type`    | `application/json` |158| `User-Agent`      | `anthropic-dlp/1`  |159| `Accept-Encoding` | `identity`         |160161There is one hook event today: the prompt frame, sent once per governed inference request, before inference begins. Anthropic holds the request until your AI security server responds or the verdict timeout elapses.162163## The prompt frame164165The request body is a JSON object with these fields:166167| Field        | Type           | Description                                                                                                                                                                                                                                                              |168| ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |169| `type`       | string         | The hook event. Always `"prompt"` today; other event types will be introduced in the future, so handle an unrecognized value gracefully (see [Forward compatibility](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#forward-compatibility)). |170| `request_id` | string         | Opaque per-inference-call identifier for correlation. Equals the `webhook-id` header.                                                                                                                                                                                    |171| `tenant_id`  | string or null | Opaque identifier for the organization the request belongs to.                                                                                                                                                                                                           |172| `actor`      | object         | The principal the request is attributed to, discriminated on `type` (`"user"` is the only value sent today): `id` (a tagged identifier, stable across requests for the same account) and `email_address` (when available). Both `id` and `email_address` can be null.    |173| `source`     | object         | The originating application: `application` (see [Source values](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#source-values)).                                                                                                              |174| `messages`   | array          | The conversation transcript up to the point of inference. See [Content blocks](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#content-blocks).                                                                                               |175| `session_id` | string or null | Opaque conversation identifier, when one exists. Don't parse it. For Claude Code it is a best-effort, client-asserted session identifier.                                                                                                                                |176| `model`      | string or null | Public model identifier for this request, when available.                                                                                                                                                                                                                |177| `metadata`   | object         | Reserved extension map of string keys to string values, sent empty today. Require nothing from it, and tolerate its absence, its presence, and any keys that appear.                                                                                                     |178179An example request body:180181```json182{183  "type": "prompt",184  "request_id": "req_abc123",185  "tenant_id": "11111111-1111-1111-1111-111111111111",186  "actor": {187    "type": "user",188    "id": "user_01AbCdEfGhIjKlMnOpQrStUv",189    "email_address": "alice@example.com"190  },191  "source": {192    "application": "claude-ai"193  },194  "session_id": "22222222-2222-2222-2222-222222222222",195  "model": "claude-sonnet-4-5",196  "messages": [197    {198      "role": "user",199      "content": [200        {201          "type": "text",202          "text": "Summarize the attached report."203        },204        {205          "type": "attachment",206          "file_name": "q2-report.pdf",207          "media_type": "application/pdf",208          "size_bytes": 48213,209          "text": "Q2 revenue grew 14% quarter over quarter..."210        }211      ]212    }213  ],214  "metadata": {}215}216```217218### Content blocks219220Each entry in `messages` has a `role` of `user` or `assistant` (tool results appear under the `user` role, matching the public Messages API content model) and a `content` array of blocks discriminated by `type`:221222| Block `type`  | Fields                                                                                                                                                                                                                                                                                                                                                                                       |223| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |224| `text`        | `text`: the text content.                                                                                                                                                                                                                                                                                                                                                                    |225| `tool_use`    | `id`: the identifier the matching tool result references. `tool_name`: the tool's name. `input`: the arguments the model passed to the tool.                                                                                                                                                                                                                                                 |226| `tool_result` | `content`: the tool's output as text, with parts joined by newlines; binary parts such as images are replaced by placeholder markers, and raw bytes are never sent. `is_error`: whether the tool call failed. `tool_name`: the tool's name, so a policy can condition on tool identity without cross-referencing an earlier block. `tool_use_id`: the `id` of the matching `tool_use` block. |227| `attachment`  | `file_name`: the original file name or path. `media_type`: the attachment's media type. `size_bytes`: the size of the original file. `text`: the text content of the attachment when available, such as extracted document text, an audio transcript, or link metadata. Raw attachment bytes are never sent.                                                                                 |228229Apart from `type`, a `text` block's `text`, and a `tool_result` block's `content` and `is_error`, any of these fields can be `null` when the value isn't known; for example, an image arrives as an `attachment` block with `file_name` and `text` set to `null`.230231A block whose `type` you don't recognize is a forward-compatible addition. The only field it guarantees is `type`; your policy may inspect whatever other fields are present, but must not reject the request because of an unrecognized type.232233### What the transcript contains234235The transcript is the conversation as the end user sees it, up to the point of inference: transcript text, tool calls and their results, extracted attachment text, and prior turns. It never includes system prompts, tool definitions, Anthropic-internal context, Claude's hidden reasoning, or raw file bytes.236237A turn whose every block is excluded is omitted entirely, so don't assume strict user and assistant alternation.238239Transcripts are sent untruncated, so a long conversation with large attachments produces a large request body. In practice the model's context window keeps bodies under about 10 MB, but the protocol allows up to 64 MiB. Several common defaults are much smaller, including nginx `client_max_body_size` at 1 MB and Express `express.json()` at 100 kB, and a rejected body counts as a webhook failure, so under **Allow the request** failure handling an oversized prompt would reach the model uninspected.240241### Source values242243`source.application` is an open string, not a closed enum. Common values are `claude-ai`, `claude-code`, and `cowork`; [connection tests](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration) and automatic circuit-breaker [recovery checks](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#circuit-breaker) use `config-test`. New values may appear, and your server must not reject a request because of one it doesn't recognize.244245Treat `source.application` as advisory routing metadata, not a trust boundary: don't rest a security-critical policy decision on it alone.246247## Return a verdict248249Respond with HTTP 200 and a JSON verdict body for both outcomes; the `action` field discriminates. To allow the request:250251```json252{253  "action": "allow"254}255```256257To deny it:258259```json260{261  "action": "deny",262  "deny_reason": "This prompt appears to contain customer payment card data, which your organization's policy does not allow.",263  "reference_id": "scan_01HXPT4R9V"264}265```266267| Field          | Constraints                                                     | Semantics                                                                                                                                                                                                                                                                                           |268| -------------- | --------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |269| `action`       | `"allow"` or `"deny"`; required                                 | `allow` lets inference proceed; `deny` rejects it.                                                                                                                                                                                                                                                  |270| `deny_reason`  | string or null; at most 500 characters, longer values truncated | Shown to the end user when `action` is `deny`; ignored on `allow`.                                                                                                                                                                                                                                  |271| `reference_id` | string or null; at most 50 characters from `[A-Za-z0-9._:/-]`   | Your own identifier for this evaluation. It's recorded on the denial's `inference_hooks_request_denied` [compliance activity](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) and never shown to the end user. Keep it opaque: no request content and no personal data. |272273A deny is never discarded over a formatting problem: an oversize `deny_reason` is truncated, a malformed `reference_id` is silently dropped, and the `action` is still honored.274275The reverse doesn't hold. Anything other than HTTP 200 with a parseable verdict is a webhook failure, and your organization's [failure handling](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration) applies instead of a verdict. In particular:276277* Don't signal a deny with an error status. A non-200 response is a failure, not a deny.278* Any `action` value other than `allow` or `deny` is treated as a webhook failure.279280Anthropic reads at most 64 KiB of the response body, and the body must be uncompressed. Redirects are not followed, and cookies are ignored. Unknown fields in the verdict body are ignored, so you can return a richer object alongside the fields documented here.281282## Verify the signature283284Requests are signed per the [Standard Webhooks](https://www.standardwebhooks.com/) specification, using three headers. Anthropic sends the header names in lowercase, and proxies are free to re-case them, so look them up case-insensitively.285286| Header              | Contents                                                                                                                                                                                                         |287| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |288| `webhook-id`        | Unique identifier for this delivery. Equals the body's `request_id`. Use it as an idempotency key and as the first component of the signed payload.                                                              |289| `webhook-timestamp` | Unix time in seconds, as a decimal string, when the request was signed. Reject a timestamp more than five minutes from your server's clock, in either direction.                                                 |290| `webhook-signature` | One or more space-separated `v1,<base64>` values, each an HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{raw body bytes}`. Accept the request if any value matches yours, using a constant-time comparison. |291292Two details cause most verification bugs:293294* **Verify raw bytes.** Compute the HMAC over the body exactly as received, before any JSON parsing or re-encoding.295* **Decode the secret with a standard base64 decoder.** The signing secret is the value after the `whsec_` prefix, encoded with the standard base64 alphabet (`+` and `/`), as is the signature in the header. A URL-safe decoder derives the wrong key bytes whenever the secret contains `+` or `/`, which is most of the time.296297Once your organization has a signing secret, every request Anthropic sends is signed, including the connection test, because the setup flow generates the secret before the first test. [Enabling Inference hooks requires a secret](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration), so reject any request that arrives unsigned. One exception: an organization that enabled Inference hooks before the secret was required keeps sending unsigned requests until its administrator generates one. Accept unsigned requests only until your administrator confirms the secret exists, then reject them.298299[Rotating the secret](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration#rotate-your-signing-secret) is an immediate cutover, but requests signed with the previous secret can still arrive for about a minute afterward, plus anything already in flight. Have your AI security server accept signatures from both secrets during the switchover so those stragglers aren't rejected.300301The following samples are server implementations, so there is no shell tab: an AI security server is a long-running HTTPS service rather than a one-shot request. Each sample uses only the language's standard library; the [Standard Webhooks](https://www.standardwebhooks.com/) project also publishes verification libraries for most languages.302303<CodeGroup exclude="shell">304  ```python Python305  import base64306  import hashlib307  import hmac308  import time309310  TOLERANCE_SECONDS = 300311312313  def verify(secret: str, headers: dict[str, str], body: bytes) -> bool:314      """Return True if the body was signed by Anthropic for this organization.315316      Anthropic sends header names in lowercase, but proxies are free to317      re-case them, so normalize the lookup to lowercase.318      """319      lowercased = {name.lower(): value for name, value in headers.items()}320      try:321          message_id = lowercased["webhook-id"]322          timestamp = lowercased["webhook-timestamp"]323          signatures = lowercased["webhook-signature"]324      except KeyError:325          return False  # unsigned request: not from Anthropic326327      try:328          signed_at = int(timestamp)329      except ValueError:330          return False331      if abs(time.time() - signed_at) > TOLERANCE_SECONDS:332          return False  # replayed, or the clocks disagree333334      try:335          key = base64.b64decode(secret.removeprefix("whsec_"), validate=True)336      except ValueError:337          return False  # misconfigured secret: reject rather than crash338339      payload = f"{message_id}.{timestamp}.".encode() + body340      expected = b"v1," + base64.b64encode(341          hmac.new(key, payload, hashlib.sha256).digest()342      )343344      # Compare bytes: compare_digest on str raises on non-ASCII input.345      return any(346          hmac.compare_digest(expected, candidate.encode())347          for candidate in signatures.split()348      )349  ```350351  ```typescript TypeScript352  import { createHmac, timingSafeEqual } from "node:crypto";353  import type { IncomingHttpHeaders } from "node:http";354355  const TOLERANCE_SECONDS = 300;356357  /**358   * Returns true if the body was signed by Anthropic for this organization.359   *360   * Node lowercases incoming header names, matching how Anthropic sends361   * them, so look them up in lowercase.362   */363  export function verify(secret: string, headers: IncomingHttpHeaders, body: Buffer): boolean {364    const messageId = headers["webhook-id"];365    const timestamp = headers["webhook-timestamp"];366    const signatures = headers["webhook-signature"];367    if (368      typeof messageId !== "string" ||369      typeof timestamp !== "string" ||370      typeof signatures !== "string"371    ) {372      return false; // unsigned request: not from Anthropic373    }374375    const signedAt = Number(timestamp);376    if (377      !Number.isFinite(signedAt) ||378      Math.abs(Date.now() / 1000 - signedAt) > TOLERANCE_SECONDS379    ) {380      return false; // replayed, or the clocks disagree381    }382383    const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");384    const payload = Buffer.concat([Buffer.from(`${messageId}.${timestamp}.`), body]);385    const expected = Buffer.from(386      "v1," + createHmac("sha256", key).update(payload).digest("base64")387    );388389    return signatures.split(" ").some((candidate) => {390      const candidateBytes = Buffer.from(candidate);391      return (392        candidateBytes.length === expected.length && timingSafeEqual(candidateBytes, expected)393      );394    });395  }396  ```397398  ```csharp C#399  using System.Security.Cryptography;400  using System.Text;401402  static class InferenceHooks403  {404      private const int ToleranceSeconds = 300;405406      /// <summary>407      /// Returns true if the body was signed by Anthropic for this organization.408      /// Anthropic sends header names in lowercase, but proxies are free to409      /// re-case them, so match them case-insensitively.410      /// </summary>411      public static bool Verify(string secret, IReadOnlyDictionary<string, string> headers, byte[] body)412      {413          // TryAdd keeps the first value if a proxy delivered case-duplicate414          // names; the copying constructor would throw on them instead.415          var lookup = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);416          foreach (var (name, value) in headers)417          {418              lookup.TryAdd(name, value);419          }420421          if (!lookup.TryGetValue("webhook-id", out var messageId) ||422              !lookup.TryGetValue("webhook-timestamp", out var timestamp) ||423              !lookup.TryGetValue("webhook-signature", out var signatures))424          {425              return false; // unsigned request: not from Anthropic426          }427428          if (!long.TryParse(timestamp, out var signedAt) ||429              Math.Abs(DateTimeOffset.UtcNow.ToUnixTimeSeconds() - signedAt) > ToleranceSeconds)430          {431              return false; // replayed, or the clocks disagree432          }433434          // Standard base64 alphabet: a URL-safe decoder derives the wrong key bytes.435          var encodedKey = secret.StartsWith("whsec_") ? secret["whsec_".Length..] : secret;436          byte[] key;437          try438          {439              key = Convert.FromBase64String(encodedKey);440          }441          catch (FormatException)442          {443              return false; // misconfigured secret: reject rather than crash444          }445446          byte[] payload = [.. Encoding.UTF8.GetBytes($"{messageId}.{timestamp}."), .. body];447          var expected = Encoding.UTF8.GetBytes(448              "v1," + Convert.ToBase64String(HMACSHA256.HashData(key, payload)));449450          // FixedTimeEquals is constant-time and returns false on a length mismatch.451          return signatures.Split(' ', StringSplitOptions.RemoveEmptyEntries).Any(candidate =>452              CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(candidate), expected));453      }454  }455  ```456457  ```go Go458  package hooks459460  import (461  	"crypto/hmac"462  	"crypto/sha256"463  	"encoding/base64"464  	"net/http"465  	"strconv"466  	"strings"467  	"time"468  )469470  const toleranceSeconds = 300471472  // verify reports whether body was signed by Anthropic for this organization.473  // net/http canonicalizes header names on lookup, so re-cased names still match.474  func verify(secret string, header http.Header, body []byte) bool {475  	messageID := header.Get("webhook-id")476  	timestamp := header.Get("webhook-timestamp")477  	signatures := header.Get("webhook-signature")478  	if messageID == "" || timestamp == "" || signatures == "" {479  		return false // unsigned request: not from Anthropic480  	}481482  	signedAt, err := strconv.ParseInt(timestamp, 10, 64)483  	if err != nil {484  		return false485  	}486  	age := time.Now().Unix() - signedAt487  	if age > toleranceSeconds || age < -toleranceSeconds {488  		return false // replayed, or the clocks disagree489  	}490491  	// Standard base64 alphabet: a URL-safe decoder derives the wrong key bytes.492  	key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))493  	if err != nil {494  		return false495  	}496497  	mac := hmac.New(sha256.New, key)498  	mac.Write([]byte(messageID + "." + timestamp + "."))499  	mac.Write(body)500  	expected := "v1," + base64.StdEncoding.EncodeToString(mac.Sum(nil))501502  	for _, candidate := range strings.Fields(signatures) {503  		if hmac.Equal([]byte(candidate), []byte(expected)) { // constant-time504  			return true505  		}506  	}507  	return false508  }509  ```510511  ```java Java512  import java.nio.charset.StandardCharsets;513  import java.security.GeneralSecurityException;514  import java.security.MessageDigest;515  import java.time.Instant;516  import java.util.Base64;517  import java.util.HashMap;518  import java.util.Locale;519  import java.util.Map;520  import javax.crypto.Mac;521  import javax.crypto.spec.SecretKeySpec;522523  public final class InferenceHookVerifier {524      private static final long TOLERANCE_SECONDS = 300;525526      /**527       * Returns true if the body was signed by Anthropic for this organization.528       *529       * <p>Anthropic sends header names in lowercase, but proxies are free to530       * re-case them, so normalize the lookup to lowercase.531       */532      public static boolean verify(String secret, Map<String, String> headers, byte[] body) {533          Map<String, String> lowercased = new HashMap<>();534          headers.forEach((name, value) -> lowercased.put(name.toLowerCase(Locale.ROOT), value));535536          String messageId = lowercased.get("webhook-id");537          String timestamp = lowercased.get("webhook-timestamp");538          String signatures = lowercased.get("webhook-signature");539          if (messageId == null || timestamp == null || signatures == null) {540              return false; // unsigned request: not from Anthropic541          }542543          long signedAt;544          try {545              signedAt = Long.parseLong(timestamp);546          } catch (NumberFormatException _) {547              return false;548          }549          if (Math.abs(Instant.now().getEpochSecond() - signedAt) > TOLERANCE_SECONDS) {550              return false; // replayed, or the clocks disagree551          }552553          // Standard base64 alphabet: a URL-safe decoder derives the wrong key bytes.554          byte[] key;555          try {556              key = Base64.getDecoder().decode(557                      secret.startsWith("whsec_") ? secret.substring("whsec_".length()) : secret);558          } catch (IllegalArgumentException _) {559              return false; // misconfigured secret: reject rather than crash560          }561562          byte[] expected;563          try {564              Mac mac = Mac.getInstance("HmacSHA256");565              mac.init(new SecretKeySpec(key, "HmacSHA256"));566              mac.update((messageId + "." + timestamp + ".").getBytes(StandardCharsets.UTF_8));567              expected = ("v1," + Base64.getEncoder().encodeToString(mac.doFinal(body)))568                      .getBytes(StandardCharsets.UTF_8);569          } catch (GeneralSecurityException impossible) {570              // Every JVM ships HmacSHA256, so this never fires at runtime.571              throw new IllegalStateException(impossible);572          }573574          for (String candidate : signatures.split(" ")) {575              if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.UTF_8), expected)) {576                  return true; // MessageDigest.isEqual is constant-time577              }578          }579          return false;580      }581  }582  ```583584  ```php PHP585  const TOLERANCE_SECONDS = 300;586587  /**588   * Returns true if the body was signed by Anthropic for this organization.589   *590   * Anthropic sends header names in lowercase, but proxies are free to591   * re-case them, so normalize the lookup to lowercase.592   */593  function verify(string $secret, array $headers, string $body): bool594  {595      $lowercased = array_change_key_case($headers, CASE_LOWER);596      $messageId = $lowercased['webhook-id'] ?? null;597      $timestamp = $lowercased['webhook-timestamp'] ?? null;598      $signatures = $lowercased['webhook-signature'] ?? null;599      if ($messageId === null || $timestamp === null || $signatures === null) {600          return false; // unsigned request: not from Anthropic601      }602603      $signedAt = filter_var($timestamp, FILTER_VALIDATE_INT);604      if ($signedAt === false || abs(time() - $signedAt) > TOLERANCE_SECONDS) {605          return false; // replayed, or the clocks disagree606      }607608      // Standard base64 alphabet: a URL-safe decoder derives the wrong key bytes.609      $encodedKey = str_starts_with($secret, 'whsec_') ? substr($secret, strlen('whsec_')) : $secret;610      $key = base64_decode($encodedKey, strict: true);611      if ($key === false) {612          return false;613      }614615      $payload = "{$messageId}.{$timestamp}." . $body;616      $expected = 'v1,' . base64_encode(hash_hmac('sha256', $payload, $key, binary: true));617618      foreach (explode(' ', $signatures) as $candidate) {619          if (hash_equals($expected, $candidate)) { // constant-time620              return true;621          }622      }623      return false;624  }625  ```626627  ```ruby Ruby628  # base64 is a bundled gem in Ruby 3.4: Bundler-managed apps add gem "base64".629  require "base64"630  require "openssl"631632  TOLERANCE_SECONDS = 300633634  # Returns true if the body was signed by Anthropic for this organization.635  #636  # Anthropic sends header names in lowercase, but proxies are free to637  # re-case them, so normalize the lookup to lowercase.638  def verify(secret, headers, body)639    lowercased = headers.transform_keys(&:downcase)640    message_id = lowercased["webhook-id"]641    timestamp = lowercased["webhook-timestamp"]642    signatures = lowercased["webhook-signature"]643    if message_id.nil? || timestamp.nil? || signatures.nil?644      return false # unsigned request: not from Anthropic645    end646647    signed_at = Integer(timestamp, exception: false)648    if signed_at.nil? || (Time.now.to_i - signed_at).abs > TOLERANCE_SECONDS649      return false # replayed, or the clocks disagree650    end651652    # Standard base64 alphabet: a URL-safe decoder derives the wrong key bytes.653    begin654      key = Base64.strict_decode64(secret.delete_prefix("whsec_"))655    rescue ArgumentError656      return false # misconfigured secret: reject rather than crash657    end658659    # Feed the body separately so its encoding never has to match the prefix's.660    hmac = OpenSSL::HMAC.new(key, "SHA256")661    hmac.update("#{message_id}.#{timestamp}.")662    hmac.update(body)663    expected = "v1," + Base64.strict_encode64(hmac.digest)664665    signatures.split(" ").any? do |candidate|666      # fixed_length_secure_compare raises on a length mismatch, so screen lengths first.667      candidate.bytesize == expected.bytesize &&668        OpenSSL.fixed_length_secure_compare(candidate, expected)669    end670  end671  ```672</CodeGroup>673674## Operational semantics675676### Timeout and retry677678Your administrator sets a verdict timeout between 1 and 10,000ms (5,000ms by default). The budget covers the entire exchange: connection, TLS handshake, request, and response.679680Anthropic retries exactly once, after a 100ms delay, and only when the connection attempt fails. The retry shares the same timeout budget and carries the same `webhook-id` and the same signature. Once your AI security server has responded, the exchange is never retried.681682### Webhook failures683684Timeouts, non-200 statuses (redirects included), unparseable or oversized response bodies, and unreachable endpoints are all webhook failures. A webhook failure never becomes a deny; instead, your organization's [failure handling](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration) setting decides whether the affected request is blocked or proceeds without inspection.685686### Circuit breaker687688Sustained webhook failures attributable to your AI security server trip a circuit breaker that stops enforcement: Anthropic stops contacting your server, and failure handling applies to every request.689690Starting 10 minutes after the trip, Anthropic checks whether your server has recovered: at most about once per minute it sends your server the same synthetic test request that **Test connection** sends (`source.application` is `config-test`), signed like any other request and carrying no user content. Respond to it normally. A valid verdict, allow or deny, resets the breaker and enforcement resumes; a webhook failure leaves the breaker tripped, and the checks continue. An administrator can also reset the breaker at any time, and administrator configuration changes stop the automatic checks; see [Circuit breaker](https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration#circuit-breaker).691692Each trip is recorded as an `inference_hooks_circuit_breaker_tripped` activity in the [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed), one activity per trip. While the breaker is tripped, no per-request Inference hooks activities are recorded, so the trip activity is the feed's only record of the tripped window.693694### Latency695696Enforcement adds your AI security server's round trip to the latency of every governed request in your organization. Keep the verdict fast, and load-test your server before rolling it out to a large organization.697698### Source IP addresses699700Requests to your AI security server originate from `160.79.106.0/24`, part of Anthropic's published [outbound IP ranges](https://platform.claude.com/docs/en/api/ip-addresses). Allowlist that block, not the inbound ranges on the same page, which don't cover it. Allowlisting narrows your server's exposure, but it is not a substitute for signature verification: the block carries Anthropic egress traffic beyond Inference hooks.701702## Forward compatibility703704The protocol grows without breaking correctly written servers. Your server must ignore:705706* Unknown top-level fields on the prompt frame.707* Unknown keys in `metadata`.708* New `source.application` values.709* New `actor.type` values. `actor` is a union discriminated on `type`, and `"user"` is the only kind sent today; a future kind guarantees only that `type` is present.710* Content blocks with an unrecognized `type`.711712Never reject a request because of an unrecognized block type or field; read the fields you know and skip the rest.713714Other hook event types will be introduced in the future. A new event type is an addition your server can't handle by skipping a field: the request still needs a verdict. When the top-level `type` is a value you don't recognize, return an allow verdict rather than an error status; an error response is a [webhook failure](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#webhook-failures), and sustained failures trip the [circuit breaker](https://platform.claude.com/docs/en/manage-claude/inference-hooks-endpoint#circuit-breaker).715716## Design your integration717718A production AI security server makes a few design choices beyond the wire protocol.719720**Deduplicate on `webhook-id`.** The `webhook-id` header is unique per delivery and equals the body's `request_id`, and a connection-failure retry reuses it, so it works as an idempotency key. If you record verdicts, key the records on it.721722**Record verdicts and join denials.** Store each verdict you return along with its `reference_id`. Every denial is recorded as an `inference_hooks_request_denied` compliance activity carrying the `reference_id` your server returned, so you can join denials in the [Activity Feed](https://platform.claude.com/docs/en/manage-claude/compliance-activity-feed) to the matching records in your own system.723724**Archive with an always-allow server.** To capture transcripts in real time without policing them, return `{"action": "allow"}` unconditionally and persist the frame after responding. This is a push-based alternative to polling the [Compliance API](https://platform.claude.com/docs/en/manage-claude/compliance-api), and answering before you persist keeps your round trip out of the user's critical path.725726**Write `deny_reason` for the end user.** The text you return is what the user sees when their request is blocked, truncated at 500 characters. Tell them what to change, such as which kind of content to remove, rather than emitting a scanner code that only your team can interpret.727728## Next steps729730<CardGroup cols={2}>731  <Card title="Configure Inference hooks" href="https://platform.claude.com/docs/en/manage-claude/inference-hooks-configuration">732    Enable Inference hooks, connect and test your endpoint, and control enforcement, failure handling, and rollout.733  </Card>734735  <Card title="Inference hooks overview" href="https://platform.claude.com/docs/en/manage-claude/inference-hooks">736    What Inference hooks are, how the verdict round trip works, and when to use them.737  </Card>738</CardGroup>739
Files main
Menu

Theme