Verify Claude Managed Agents webhooks
Anthropic signs each delivery so you can confirm it came from Anthropic and wasn't changed. Deliveries follow Standard Webhooks: webhook-signature holds a base64 HMAC-SHA256 over webhook-id, webhook-timestamp and the raw body, keyed with the endpoint's whsec_ secret. client.beta.webhooks.unwrap(), in every Anthropic SDK except C#, checks the signature and rejects anything more than 5 minutes old.
These pages cover the events Anthropic sends about Claude Managed Agents. To start Claude Code from another system's webhook, you call a scheduled task's API trigger instead. Organization webhooks, for enforcement actions on user profiles, are a separate API whose docs say no events are sent yet.
The facts
webhook-signature Format: v1,<base64>, as a space-separated list
{webhook-id}.{webhook-timestamp}.{raw body} The two header values and the body as sent, joined with literal dots.
webhook-timestamp Reject deliveries older than 5 minutes.
Recompute a digest over the timestamp and raw body, and compare Claude Managed Agents webhook secret
Each endpoint has its own signing secret, generated when you create the endpoint and shown only once. Keep it in an environment variable, not in source code.
- Where: the Webhooks page in the Claude Console shows it when you create the endpoint. Each endpoint belongs to one workspace.
- Format: 32 bytes with a
whsec_prefix. Standard Webhooks encodes the part after the prefix as base64, so decode it if you compute the HMAC yourself. - SDKs: set
ANTHROPIC_WEBHOOK_SIGNING_KEY, whichunwrap()reads from the environment. - Replacing an endpoint: a new endpoint has a new secret, so update the variable when you move to one.
- Rotation: the Managed Agents docs describe no way to rotate a secret on an existing endpoint.
Source: Claude Managed Agents docs ↗
Code
// Generated with: claude-managed-agents-webhooks skill
// https://github.com/hookdeck/webhook-skills
require('dotenv').config();
const express = require('express');
const crypto = require('crypto');
const app = express();
/**
* Verify Claude Managed Agents webhook signature (Standard Webhooks).
*
* @param {Buffer|string} payload - Raw request body
* @param {string} webhookId - Value of webhook-id header
* @param {string} webhookTimestamp - Value of webhook-timestamp header
* @param {string} webhookSignature - Value of webhook-signature header
* @param {string} secret - whsec_-prefixed signing key
* @returns {boolean} Whether the signature is valid
*/
function verifyClaudeSignature(payload, webhookId, webhookTimestamp, webhookSignature, secret) {
if (!webhookId || !webhookTimestamp || !webhookSignature || !webhookSignature.includes(',')) {
return false;
}
// Reject payloads older than 5 minutes to prevent replay attacks
const currentTime = Math.floor(Date.now() / 1000);
const timestampDiff = currentTime - parseInt(webhookTimestamp);
if (Number.isNaN(timestampDiff) || timestampDiff > 300 || timestampDiff < -300) {
return false;
}
// The signature is HMAC-SHA256 over "{id}.{timestamp}.{rawBody}"
const payloadStr = payload instanceof Buffer ? payload.toString('utf8') : payload;
const signedContent = `${webhookId}.${webhookTimestamp}.${payloadStr}`;
// whsec_ prefix wraps a base64-encoded 32-byte key
const secretKey = secret.startsWith('whsec_') ? secret.slice(6) : secret;
let secretBytes;
try {
secretBytes = Buffer.from(secretKey, 'base64');
} catch {
return false;
}
const expectedSignature = crypto
.createHmac('sha256', secretBytes)
.update(signedContent, 'utf8')
.digest('base64');
// The header may carry multiple space-separated "v1,<sig>" pairs (rotation)
return webhookSignature.split(' ').some((pair) => {
const [version, signature] = pair.split(',');
if (version !== 'v1' || !signature) return false;
try {
return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature));
} catch {
return false;
}
});
}
// CRITICAL: Use express.raw() for the webhook endpoint — signature is over raw bytes
app.post(
'/webhooks/claude-managed-agents',
express.raw({ type: 'application/json' }),
async (req, res) => {
const webhookId = req.headers['webhook-id'];
const webhookTimestamp = req.headers['webhook-timestamp'];
const webhookSignature = req.headers['webhook-signature'];
const secret = process.env.ANTHROPIC_WEBHOOK_SIGNING_KEY;
if (!secret) {
console.error('ANTHROPIC_WEBHOOK_SIGNING_KEY is not set');
return res.status(500).send('Webhook signing key not configured');
}
if (!verifyClaudeSignature(req.body, webhookId, webhookTimestamp, webhookSignature, secret)) {
console.error('Claude Managed Agents webhook signature verification failed');
return res.status(400).send('Invalid signature');
}
// Parse the verified payload
let event;
try {
event = JSON.parse(req.body.toString());
} catch (err) {
console.error('Failed to parse webhook payload:', err);
return res.status(400).send('Invalid JSON payload');
}
// CMA payloads carry the event type under data.type; the top-level
// event.type is always "event". Switch on event.data.type.
const eventType = event.data && event.data.type;
const resourceId = event.data && event.data.id;
switch (eventType) {
case 'session.status_run_started':
console.log(`Session run started: ${resourceId}`);
break;
case 'session.status_idled':
console.log(`Session idled (awaiting input): ${resourceId}`);
// Your code: client.beta.sessions.retrieve(resourceId) and notify user
break;
case 'session.status_rescheduled':
console.log(`Session rescheduled (transient error, auto-retrying): ${resourceId}`);
break;
case 'session.status_terminated':
console.log(`Session terminated: ${resourceId}`);
// Your code: alert on-call, persist final state
break;
case 'session.thread_created':
console.log(`Multiagent thread created: ${resourceId}`);
break;
case 'session.thread_idled':
console.log(`Multiagent thread idled: ${resourceId}`);
break;
case 'session.thread_terminated':
console.log(`Multiagent thread terminated: ${resourceId}`);
break;
case 'session.outcome_evaluation_ended':
console.log(`Outcome evaluation ended for session: ${resourceId}`);
break;
case 'vault.created':
console.log(`Vault created: ${resourceId}`);
break;
case 'vault.archived':
console.log(`Vault archived: ${resourceId}`);
break;
case 'vault.deleted':
console.log(`Vault deleted: ${resourceId}`);
break;
case 'vault_credential.created':
console.log(`Vault credential created: ${resourceId}`);
break;
case 'vault_credential.archived':
console.log(`Vault credential archived: ${resourceId}`);
break;
case 'vault_credential.deleted':
console.log(`Vault credential deleted: ${resourceId}`);
break;
case 'vault_credential.refresh_failed':
console.log(`Vault credential refresh failed: ${resourceId}`);
// Your code: trigger OAuth re-consent flow for the user
break;
default:
console.log(`Unhandled event type: ${eventType}`);
}
// Return 200 to acknowledge receipt. Anything other than 2xx triggers a retry.
res.status(200).json({ received: true });
}
);
app.get('/health', (req, res) => {
res.json({ status: 'ok' });
});
module.exports = app;
if (require.main === module) {
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
console.log(`Webhook endpoint: POST http://localhost:${PORT}/webhooks/claude-managed-agents`);
});
} // Generated with: claude-managed-agents-webhooks skill
// https://github.com/hookdeck/webhook-skills
import { NextRequest, NextResponse } from 'next/server';
import { createHmac, timingSafeEqual } from 'crypto';
/**
* Verify Claude Managed Agents webhook signature (Standard Webhooks).
*
* Signed content: "{webhook-id}.{webhook-timestamp}.{rawBody}"
* Algorithm: HMAC-SHA256, base64-encoded, with the whsec_-prefixed secret
* base64-decoded as the HMAC key.
*/
function verifyClaudeSignature(
payload: string,
webhookId: string | null,
webhookTimestamp: string | null,
webhookSignature: string | null,
secret: string
): boolean {
if (!webhookId || !webhookTimestamp || !webhookSignature || !webhookSignature.includes(',')) {
return false;
}
// Reject payloads older than 5 minutes to prevent replay attacks
const currentTime = Math.floor(Date.now() / 1000);
const timestampDiff = currentTime - parseInt(webhookTimestamp);
if (Number.isNaN(timestampDiff) || timestampDiff > 300 || timestampDiff < -300) {
return false;
}
const signedContent = `${webhookId}.${webhookTimestamp}.${payload}`;
// whsec_ prefix wraps a base64-encoded 32-byte key
const secretKey = secret.startsWith('whsec_') ? secret.slice(6) : secret;
let secretBytes: Buffer;
try {
secretBytes = Buffer.from(secretKey, 'base64');
} catch {
return false;
}
const expectedSignature = createHmac('sha256', secretBytes)
.update(signedContent, 'utf8')
.digest('base64');
// The header may carry multiple space-separated "v1,<sig>" pairs (rotation)
return webhookSignature.split(' ').some((pair) => {
const [version, signature] = pair.split(',');
if (version !== 'v1' || !signature) return false;
try {
return timingSafeEqual(Buffer.from(signature), Buffer.from(expectedSignature));
} catch {
return false;
}
});
}
export async function POST(request: NextRequest) {
// CRITICAL: read the raw body as text. Calling request.json() first would
// re-serialise the payload and break verification.
const rawBody = await request.text();
const webhookId = request.headers.get('webhook-id');
const webhookTimestamp = request.headers.get('webhook-timestamp');
const webhookSignature = request.headers.get('webhook-signature');
const secret = process.env.ANTHROPIC_WEBHOOK_SIGNING_KEY;
if (!secret) {
console.error('ANTHROPIC_WEBHOOK_SIGNING_KEY is not set');
return NextResponse.json({ error: 'Webhook signing key not configured' }, { status: 500 });
}
if (!verifyClaudeSignature(rawBody, webhookId, webhookTimestamp, webhookSignature, secret)) {
console.error('Claude Managed Agents webhook signature verification failed');
return NextResponse.json({ error: 'Invalid signature' }, { status: 400 });
}
let event: any;
try {
event = JSON.parse(rawBody);
} catch (err) {
console.error('Failed to parse webhook payload:', err);
return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
}
// CMA payloads carry the event type under data.type; the top-level
// event.type is always "event". Switch on event.data.type.
const eventType = event?.data?.type;
const resourceId = event?.data?.id;
switch (eventType) {
case 'session.status_run_started':
console.log(`Session run started: ${resourceId}`);
break;
case 'session.status_idled':
console.log(`Session idled (awaiting input): ${resourceId}`);
// Your code: client.beta.sessions.retrieve(resourceId) and notify user
break;
case 'session.status_rescheduled':
console.log(`Session rescheduled (transient error, auto-retrying): ${resourceId}`);
break;
case 'session.status_terminated':
console.log(`Session terminated: ${resourceId}`);
// Your code: alert on-call, persist final state
break;
case 'session.thread_created':
console.log(`Multiagent thread created: ${resourceId}`);
break;
case 'session.thread_idled':
console.log(`Multiagent thread idled: ${resourceId}`);
break;
case 'session.thread_terminated':
console.log(`Multiagent thread terminated: ${resourceId}`);
break;
case 'session.outcome_evaluation_ended':
console.log(`Outcome evaluation ended for session: ${resourceId}`);
break;
case 'vault.created':
console.log(`Vault created: ${resourceId}`);
break;
case 'vault.archived':
console.log(`Vault archived: ${resourceId}`);
break;
case 'vault.deleted':
console.log(`Vault deleted: ${resourceId}`);
break;
case 'vault_credential.created':
console.log(`Vault credential created: ${resourceId}`);
break;
case 'vault_credential.archived':
console.log(`Vault credential archived: ${resourceId}`);
break;
case 'vault_credential.deleted':
console.log(`Vault credential deleted: ${resourceId}`);
break;
case 'vault_credential.refresh_failed':
console.log(`Vault credential refresh failed: ${resourceId}`);
// Your code: trigger OAuth re-consent flow for the user
break;
default:
console.log(`Unhandled event type: ${eventType}`);
}
// Anything other than 2xx triggers a retry; 3xx counts as failure.
return NextResponse.json({ received: true });
} # Generated with: claude-managed-agents-webhooks skill
# https://github.com/hookdeck/webhook-skills
import os
import hmac
import hashlib
import json
import base64
import time
from typing import Optional
from dotenv import load_dotenv
from fastapi import FastAPI, Request, HTTPException, Header
load_dotenv()
app = FastAPI(title="Claude Managed Agents Webhook Handler")
def verify_claude_signature(
payload: bytes,
webhook_id: Optional[str],
webhook_timestamp: Optional[str],
webhook_signature: Optional[str],
secret: str,
) -> bool:
"""
Verify Anthropic Claude Managed Agents webhook signature (Standard Webhooks).
Signed content: "{webhook-id}.{webhook-timestamp}.{rawBody}"
Algorithm: HMAC-SHA256, base64-encoded, with the whsec_-prefixed secret
base64-decoded as the HMAC key.
Args:
payload: Raw request body bytes
webhook_id: Value of webhook-id header
webhook_timestamp: Value of webhook-timestamp header
webhook_signature: Value of webhook-signature header
secret: The whsec_-prefixed signing key
Returns:
True if any signature in the header matches the expected one.
"""
if not webhook_id or not webhook_timestamp or not webhook_signature or ',' not in webhook_signature:
return False
# Reject payloads older than 5 minutes to prevent replay attacks
try:
timestamp_diff = int(time.time()) - int(webhook_timestamp)
except ValueError:
return False
if timestamp_diff > 300 or timestamp_diff < -300:
return False
signed_content = f"{webhook_id}.{webhook_timestamp}.{payload.decode('utf-8')}"
# whsec_ prefix wraps a base64-encoded 32-byte key
secret_key = secret[6:] if secret.startswith('whsec_') else secret
try:
secret_bytes = base64.b64decode(secret_key)
except Exception:
return False
expected_signature = base64.b64encode(
hmac.new(secret_bytes, signed_content.encode('utf-8'), hashlib.sha256).digest()
).decode('utf-8')
# The header may carry multiple space-separated "v1,<sig>" pairs (rotation)
for pair in webhook_signature.split(' '):
parts = pair.split(',', 1)
if len(parts) != 2:
continue
version, signature = parts
if version == 'v1' and hmac.compare_digest(signature, expected_signature):
return True
return False
@app.post("/webhooks/claude-managed-agents")
async def claude_webhook(
request: Request,
webhook_id: Optional[str] = Header(None, alias="webhook-id"),
webhook_timestamp: Optional[str] = Header(None, alias="webhook-timestamp"),
webhook_signature: Optional[str] = Header(None, alias="webhook-signature"),
):
"""
Receive and process Anthropic Claude Managed Agents webhooks.
"""
payload = await request.body()
secret = os.environ.get("ANTHROPIC_WEBHOOK_SIGNING_KEY")
if not secret:
print("ERROR: ANTHROPIC_WEBHOOK_SIGNING_KEY is not set")
raise HTTPException(status_code=500, detail="Webhook signing key not configured")
if not verify_claude_signature(payload, webhook_id, webhook_timestamp, webhook_signature, secret):
print("ERROR: Claude Managed Agents webhook signature verification failed")
raise HTTPException(status_code=400, detail="Invalid signature")
try:
event = json.loads(payload.decode('utf-8'))
except json.JSONDecodeError as e:
print(f"ERROR: Failed to parse webhook payload: {e}")
raise HTTPException(status_code=400, detail="Invalid JSON payload")
# CMA payloads carry the event type under data.type; the top-level
# event.type is always "event". Switch on event.data.type.
event_data = event.get("data") or {}
event_type = event_data.get("type")
resource_id = event_data.get("id")
if event_type == "session.status_run_started":
print(f"Session run started: {resource_id}")
elif event_type == "session.status_idled":
print(f"Session idled (awaiting input): {resource_id}")
# Your code: client.beta.sessions.retrieve(resource_id) and notify user
elif event_type == "session.status_rescheduled":
print(f"Session rescheduled (transient error, auto-retrying): {resource_id}")
elif event_type == "session.status_terminated":
print(f"Session terminated: {resource_id}")
# Your code: alert on-call, persist final state
elif event_type == "session.thread_created":
print(f"Multiagent thread created: {resource_id}")
elif event_type == "session.thread_idled":
print(f"Multiagent thread idled: {resource_id}")
elif event_type == "session.thread_terminated":
print(f"Multiagent thread terminated: {resource_id}")
elif event_type == "session.outcome_evaluation_ended":
print(f"Outcome evaluation ended for session: {resource_id}")
elif event_type == "vault.created":
print(f"Vault created: {resource_id}")
elif event_type == "vault.archived":
print(f"Vault archived: {resource_id}")
elif event_type == "vault.deleted":
print(f"Vault deleted: {resource_id}")
elif event_type == "vault_credential.created":
print(f"Vault credential created: {resource_id}")
elif event_type == "vault_credential.archived":
print(f"Vault credential archived: {resource_id}")
elif event_type == "vault_credential.deleted":
print(f"Vault credential deleted: {resource_id}")
elif event_type == "vault_credential.refresh_failed":
print(f"Vault credential refresh failed: {resource_id}")
# Your code: trigger OAuth re-consent flow for the user
else:
print(f"Unhandled event type: {event_type}")
# Anything other than 2xx triggers a retry; 3xx counts as failure.
return {"received": True}
@app.get("/health")
async def health_check():
return {"status": "ok"}
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 8000))
uvicorn.run(app, host="0.0.0.0", port=port) Or install the Claude Managed Agents webhooks skill:
npx skills add hookdeck/webhook-skills --skill claude-managed-agents-webhooks
Common failures
Body parsed before verification
The signature covers the raw bytes, so re-serialized JSON won't match. Anthropic's Express example uses express.raw(), not express.json().
Secret used as a plain string
In Standard Webhooks, the part after whsec_ is base64. If you compute the HMAC yourself, remove the prefix and decode the rest to get the key. unwrap() and Standard Webhooks libraries do this for you.
Verifying behind a queue
unwrap() rejects a webhook-timestamp more than 5 minutes old, so a worker verifying after a backlog rejects real events. Verify when the request arrives. Retries are safe, because Anthropic stamps each attempt afresh.
Another endpoint's secret
Each endpoint has its own secret, including one you add to replace another. ANTHROPIC_WEBHOOK_SIGNING_KEY has to hold the secret of the endpoint that's sending.
Let Event Gateway verify Claude Managed Agents signatures.
Event Gateway verifies the signature on each Claude Managed Agents delivery before it reaches your service, then queues it and retries failures on your schedule.