---
title: "Webhook Dispatcher Tools: Sending Outbound Events from Agent Actions"
date: "2026-11-28T11:25:00+07:00"
description: "Build an ADK tool that fires outbound webhooks safely: signed HMAC payloads, endpoint allow-lists, idempotency keys, bounded retries, and a delivery status the model can act on."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/webhook-dispatcher-tools-adk.jpg"
alt: "Abstract outgoing signal waves radiating from a server icon on a dark gradient background"
tags: ['google-adk', 'adk-tools', 'webhooks', 'hmac', 'reliability']
---

The moment an agent can notify the outside world, its failure modes become other people's incidents: a duplicated dispatch charges a customer twice, an unsigned payload gets forged, a hung POST holds the agent run open for 30 seconds. A webhook tool is small code wrapped in a large contract — identity, signing, retry, dedupe, and a status the model understands.

This tutorial covers the full contract for an outbound dispatcher tool in ADK: the event envelope, HMAC signing with a timestamp, an endpoint allow-list so the model cannot aim your traffic anywhere, retries with idempotency, and how to report delivery state back to the agent.

## The event envelope comes first

Every dispatch — whatever the downstream service — should carry the same header, because that is what makes retries and dedupe possible:

```python
import json, time, uuid

def make_event(event_type: str, source: str, payload: dict) -> dict:
    return {"event_id": str(uuid.uuid4()),   # stable across retries
            "event_type": event_type,        # e.g. "order.state_changed"
            "source": source, "schema_version": 1, "payload": payload,
            "occurred_at": int(time.time())} # generation time, not send time
```

`event_id` is the idempotency key: generate it *before* the first attempt and reuse it on every retry, so the receiver can store processed IDs and drop duplicates. Regenerating it per attempt turns your retry loop into a duplicate-delivery machine.

## Never let the model choose the URL

An agent-influenced dispatcher that takes a free-form `url` parameter is an SSRF primitive — the model can be talked into posting your internal payloads to an attacker's host. Register channels in code and resolve names to URLs yourself:

```python
CHANNELS = {"billing":  {"url": "https://hooks.acme.io/billing",  "secret_env": "HOOK_BILLING_SECRET"},
            "logistics": {"url": "https://hooks.acme.io/logistics", "secret_env": "HOOK_LOGISTICS_SECRET"}}
```

An ADK `before_tool_callback` is the right place to enforce this: it runs after the model produces a function call but before `run_async` executes the tool, and returning a `dict` skips the tool entirely, using that dict as the tool result. Rejecting `channel="https://evil.example"` there means the bad call never touches the network.

## Sign the payload: HMAC over timestamp + body

Sign `"{timestamp}.{body}"` so the receiver can verify both integrity and freshness. Stripe's scheme is the canonical shape: an HMAC-SHA256 over a signed payload that includes a timestamp, comparison with `hmac.compare_digest` (never `==`, which leaks timing), and a tolerance window — their libraries default to five minutes — that rejects old replays.

```python
import hashlib, hmac, os

def sign(body: str, secret: str, timestamp: int | None = None) -> str:
    ts = timestamp if timestamp is not None else int(time.time())
    mac = hmac.new(secret.encode(), f"{ts}.{body}".encode(), hashlib.sha256)
    return f"t={ts},v1={mac.hexdigest()}"

def dispatch(channel: str, event: dict) -> dict:
    cfg = CHANNELS[channel]
    secret = os.environ[cfg["secret_env"]]
    body = json.dumps(event, separators=(",", ":"), sort_keys=True)
    headers = {"Content-Type": "application/json", "X-Event-Id": event["event_id"],
               "Idempotency-Key": event["event_id"], "X-Signature": sign(body, secret)}
    return {"url": cfg["url"], "body": body, "headers": headers}
```

`sort_keys=True` matters: the receiver re-serialises the raw body when verifying, so byte-for-byte reproducibility is part of the contract. Sign the *raw* bytes you send, never a re-parsed dict.

## Retry hard, but bounded

```python
import asyncio, random
import httpx

async def deliver(url: str, body: str, headers: dict, max_attempts: int = 4) -> dict:
    delay = 0.5
    async with httpx.AsyncClient(timeout=8) as client:
        for attempt in range(1, max_attempts + 1):
            try:
                resp = await client.post(url, content=body, headers=headers)
                if 200 <= resp.status_code < 300:
                    return {"status": "accepted", "http_status": resp.status_code, "attempts": attempt}
                if resp.status_code not in (429, 500, 502, 503, 504):
                    return {"status": "error", "attempts": attempt,     # 4xx won't improve
                            "error_message": f"Rejected with HTTP {resp.status_code}."}
            except (httpx.TimeoutException, httpx.TransportError):
                pass
            if attempt == max_attempts:
                break
            await asyncio.sleep(delay + random.uniform(0, delay))   # full jitter
            delay *= 2
    return {"status": "error", "attempts": max_attempts,
            "error_message": "Delivery failed after 4 attempts; event kept for replay."}
```

Respect `Retry-After` when a `429` or `503` carries it, and treat redirects as failures rather than following them to an unexpected host. Stripe's model is instructive for the receiver side too: deliveries are retried with exponential backoff over days, and the receiver dedupes on event IDs because *retries get new signatures and new timestamps*.

## Decide what the tool tells the model

Do not block an agent turn on a slow endpoint. Three delivery semantics, and the model should be told which one it is getting via the docstring:

| Semantics | Tool returns | Use when |
|---|---|---|
| Synchronous accept | `status: accepted` + HTTP code | Endpoint answers fast; agent must know now |
| Queue and acknowledge | `status: queued` + `delivery_id` | Outbox/queue does the retrying; agent continues |
| Long-running | `status: pending` + operation id | Fan-out to many endpoints or manual approval |

For the third, ADK's `LongRunningFunctionTool` — a `FunctionTool` subclass — starts the work, returns an initial result, and pauses the run so the agent client can report progress later; the docs are explicit that the tool *manages* long tasks rather than *performing* them, so heavy delivery belongs in a queue or worker service. For a single HTTP POST, an async tool with a bounded retry loop (see [synchronous vs asynchronous tools](/blog/sync-vs-async-tools-adk)) is the simpler choice.

```python
async def notify_billing(event_type: str, summary: str) -> dict:
    """Send a signed event to the billing webhook channel.

    Args:
        event_type (str): Event name, e.g. 'order.state_changed'.
        summary (str): One-line human summary included in the payload.

    Returns:
        dict: status, event_id, attempts, summary.
    """
    event = make_event(event_type, source="sales_agent", payload={"summary": summary})
    req = dispatch("billing", event)
    result = await deliver(req["url"], req["body"], req["headers"])
    result.update({"event_id": event["event_id"],
                   "summary": f"Event {event['event_id']} {result['status']} "
                              f"after {result.get('attempts', 1)} attempt(s)."})
    return result
```

The `attempts` number is worth its tokens: when the user asks "did the invoice go out?", the model answers from the tool result instead of guessing. Log `event_id`, channel, attempt count, and HTTP status on every outcome — that is the triple a support engineer greps for. Failures come back as `status: error` with a human-readable `error_message`, and a retry must reuse the *same* `event_id` rather than mint a new one, per the contract in [tool errors and recoverable exceptions](/blog/adk-tool-errors-recoverable-exceptions).

## Takeaways

- Generate `event_id` before the first attempt and reuse it on every retry — that single field is your idempotency key on both sides.
- Resolve channel names to URLs in code; never accept a model-supplied URL, and gate the argument with `before_tool_callback`.
- Sign `timestamp.body` with HMAC-SHA256, compare in constant time, and reject timestamps outside a small tolerance window.
- Retry with exponential backoff plus jitter, stop on non-retryable `4xx`, and cap attempts so an agent turn stays bounded.
- Choose one delivery semantic — accepted, queued, or long-running — and state it in the docstring so the model reports honestly.

## Further reading

- [Registry automation: webhooks, tokens, and access scopes](/blog/registry-automation-webhooks-tokens-access-scopes)
- [Synchronous vs asynchronous tool implementations](/blog/sync-vs-async-tools-adk)
- [Tool errors and recoverable exceptions](/blog/adk-tool-errors-recoverable-exceptions)
- [Tool output formatting: Markdown vs structured dictionaries](/blog/tool-output-formatting-markdown-vs-json)
- [Stripe: receiving webhook events and verifying signatures](https://docs.stripe.com/webhooks)
- [OWASP Webhook Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Webhook_Security_Cheat_Sheet.html)
