Cookbook: Webhook-triggered agent
Agent fires on an inbound HMAC-verified POST from an external system — Stripe payment events, GitHub PR events, Shopify order webhooks, Zendesk ticket webhooks. The platform verifies HMAC server-side using a tenant credential; the agent just handles the already-verified payload.
Reads: webhook body via req.payload.
Writes: typically triggers downstream work (notifications, HiL
approvals, state updates).
Idempotency: external systems retry — your handler must be safe to
run twice on the same payload.
manifest.json#
The webhooks[] entry declares the HMAC credential + signature header.
The platform exposes the webhook at
https://api.konstera.ai/wh/<tenant>/webhooks/stripe-events.
{
"$schema": "https://schemas.konstera.ai/agent-manifest.v3.json",
"id": "io.konstera.stripe-events",
"version": "0.1.0",
"name": "Stripe Event Processor",
"description": "Processes Stripe webhook events (payment_intent.succeeded, charge.refunded).",
"icon": "💳",
"autonomy": "autonomous",
"runtime": {
"kind": "container",
"image": "ghcr.io/your-org/stripe-events:0.1.0",
"port": 8080,
"timeoutSeconds": 15,
"memoryMi": 256,
"cpuMillis": 300
},
"input": {
"type": "object",
"properties": {
"mode": { "type": "string", "default": "webhook" }
}
},
"webhooks": [
{
"name": "stripe-events",
"path": "/webhooks/stripe-events",
"hmac_secret_credential": "stripe-webhook-secret",
"signature_header": "Stripe-Signature"
}
],
"capabilities": {
"needs": [
{
"name": "orders.update_fields",
"required": false,
"reason": "Mark the order as paid when payment_intent.succeeded arrives"
}
]
}
}
main.py#
Three key patterns inline:
from konstera_sdk import Agent, AgentContext, AgentRequest, AgentResponse, run
class StripeEventAgent(Agent):
"""Processes Stripe webhook events. HMAC is already verified by the kernel."""
async def handle(
self, req: AgentRequest, ctx: AgentContext
) -> AgentResponse:
# req.payload is the webhook body VERBATIM — the kernel has already
# verified the HMAC against the stripe-webhook-secret credential.
# We don't re-verify.
event = req.payload or {}
event_type = event.get("type", "")
event_id = event.get("id", "")
if not event_id:
# Malformed event — Stripe always sends 'id'. Return 200 so Stripe
# doesn't retry an unparseable payload forever.
await ctx.log.warn("stripe.malformed", keys=list(event.keys()))
return AgentResponse(content="", structured={"ignored": "no id"})
# IDEMPOTENCY: external systems retry on 5xx. Track processed event IDs
# in state so a retry of the same event is a no-op.
if await ctx.state.get(f"processed:{event_id}"):
await ctx.log.info("stripe.replay", event_id=event_id)
return AgentResponse(content="", structured={"status": "replay"})
await ctx.log.info("stripe.start", event_id=event_id, type=event_type)
# Dispatch on event type
if event_type == "payment_intent.succeeded":
await self._on_payment_succeeded(event, ctx)
elif event_type == "charge.refunded":
await self._on_charge_refunded(event, ctx)
else:
await ctx.log.info("stripe.ignored", type=event_type)
# Mark processed AFTER successful handling (if we crash, retry re-runs)
await ctx.state.set(f"processed:{event_id}", {"at": event.get("created")})
return AgentResponse(
content="",
structured={"event_id": event_id, "type": event_type, "status": "ok"},
)
async def _on_payment_succeeded(self, event, ctx: AgentContext):
order_id = event.get("data", {}).get("object", {}).get("metadata", {}).get("order_id")
if not order_id:
await ctx.log.warn("stripe.no_order_metadata")
return
# Optionally update the order via a bound capability
if await ctx.capability.available("orders.update_fields"):
await ctx.capability.call(
"orders.update_fields",
id=order_id,
fields={"status": "paid", "paid_at": event.get("created")},
)
await ctx.log.info("stripe.order_updated", order_id=order_id)
async def _on_charge_refunded(self, event, ctx: AgentContext):
charge_id = event.get("data", {}).get("object", {}).get("id")
await ctx.log.info("stripe.refund_recorded", charge_id=charge_id)
if __name__ == "__main__":
run(StripeEventAgent())
Dockerfile#
FROM python:3.13-slim
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir konstera-sdk==0.6.0
EXPOSE 8080
HEALTHCHECK --interval=10s --timeout=3s --start-period=5s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health', timeout=2)"
ENTRYPOINT ["python", "-u", "main.py"]
Setting up the HMAC credential#
In the portal (or via CLI):
konstera credential set stripe-webhook-secret 'whsec_1a2b3c4d...'
# The agent instance now has access via ctx.credentials.get("stripe-webhook-secret")
# — but you don't need to call that; HMAC verification is kernel-side.
Testing locally#
Direct-run mode bypasses HMAC verification (there's no kernel to verify against). POST a Stripe-shaped payload directly:
curl -X POST http://localhost:8080/invoke \
-H content-type:application/json \
-d '{
"invocationId": "local-1",
"input": "",
"payload": {
"id": "evt_test_1",
"type": "payment_intent.succeeded",
"created": 1734528000,
"data": {"object": {"metadata": {"order_id": "o-123"}}}
},
"config": {}
}'
For integration testing against the real HMAC path, Stripe provides
stripe listen which forwards verified events to a URL — point it at
http://localhost:4500/wh/<tenant>/webhooks/stripe-events against the
local kernel.
Common extensions#
- Multiple webhooks per agent: declare multiple entries in
webhooks[]. All route to the samehandle()— the agent branches onreq.payload.get("type")or whatever the external system uses. - Signature header for non-standard systems: GitHub uses
X-Hub-Signature-256, Shopify usesX-Shopify-Hmac-SHA256. Thesignature_headerfield in the manifest accepts any header name. - Fast-path acknowledgement: for high-volume webhooks, return
immediately and dispatch the real work to
ctx.agents.invoke()as a child workflow. Keeps the response time under Stripe's / GitHub's 10s timeout. - Dead-letter queue: wrap the dispatch in try/except; on failure, write
to
ctx.statewith afailed:prefix so a nightly cleanup agent can retry or alert.
Pitfalls#
- Re-verifying HMAC: don't. The kernel has already done it with a credential your agent doesn't need to see. If you re-verify, you need the secret in the agent container — defeats the purpose.
- Idempotency key placement: mark events as processed after the side effects succeed. If you mark first and then crash, the retry sees "already processed" and skips the real work.
- Signature header case: HTTP headers are case-insensitive, but the
manifest
signature_headerstring must match what the external system actually sends. Check their docs; most use the canonical capitalisation.
See also#
- Invocation modes — webhook — the mechanics
- Error catalog — what happens on HMAC failure or malformed body
- Credentials — ctx.credentials — how the kernel loads the HMAC secret