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

> ## Agent Instructions
> Every page is listed in https://docs.keenable.ai/llms.txt. To pick a product for a job, read https://docs.keenable.ai/choose.md
> Setup steps for agents, covering the SDKs, the MCP server and the CLI: https://docs.keenable.ai/skill.md
> Keenable search and fetch work without an API key. To add them to code, use the official SDK for the project's language: https://docs.keenable.ai/sdks.md
> Without a key, call POST https://api.keenable.ai/v1/search/public or GET https://api.keenable.ai/v1/fetch/public with an X-Keenable-Title header that names your app.
> With a key, send it in the X-API-Key header and read it from the KEENABLE_API_KEY environment variable. Never ask a user to paste a key into chat. Every access method: https://docs.keenable.ai/auth.md
> To get an API key without the console, use device login: https://docs.keenable.ai/authentication.md#device-login
> MCP server: https://api.keenable.ai/mcp (no key, or X-API-Key; keyless Codex uses https://api.keenable.ai/mcp-public), or https://api.keenable.ai/mcp-oauth for OAuth sign-in. These docs are an MCP server at https://docs.keenable.ai/mcp and the OpenAPI spec is at https://docs.keenable.ai/api-reference/openapi.json
> Keenable searches and fetches public web pages. If a question needs no web information, skip the call.
> On 402 with an API key (code insufficient_credits), stop and ask a human to add credits; don't retry. On 429, wait the number of seconds in Retry-After, then retry. Before you ship, follow https://docs.keenable.ai/production.md
> Every error, with its cause and fix, is in https://docs.keenable.ai/errors.md and moving from another search API is covered in https://docs.keenable.ai/migrate.md
> Before you compare Keenable with another search API, read https://docs.keenable.ai/guides/evaluate-search-apis.md

# Receive and verify monitor webhooks

> Get each new monitor result at your endpoint: subscribe to monitor.result.found, verify the Standard Webhooks signature, test locally, debug failed deliveries.

Get each page a monitor accepts at your own endpoint, minutes after Keenable crawls it, with no polling loop. Subscribe the monitor to `monitor.result.found`, check the signature on every delivery, and answer with a `2xx` status. For the body and headers of each event type, see [Webhook payload](https://docs.keenable.ai/api-reference/monitors-webhook-payload.md).

You need an [API key](https://docs.keenable.ai/api-keys.md), a monitor, and an HTTPS endpoint that the public internet can reach. To create a monitor, see [Create a monitor](https://docs.keenable.ai/guides/create-a-monitor.md).

## Subscribe to new results

A monitor with a webhook sends `monitor.result.found` for each new result unless `webhook.events` leaves it out. Set the webhook in the create request. The create response carries the signing secret, `webhook.secret`. This request creates a monitor that sends only new results, changed results and the disabled notice to your endpoint:

```bash theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
curl -X POST https://api.keenable.ai/v1/monitors \
  -H "X-API-Key: $KEENABLE_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: open-weights-llm-releases" \
  -d '{
    "name": "Open-weights LLM releases",
    "search": {"query": "new open-weights LLM releases"},
    "webhook": {
      "url": "https://hooks.example.com/keenable",
      "events": ["monitor.result.found", "monitor.result.changed", "monitor.disabled"]
    }
  }'
```

The response is the new monitor with `webhook.url`, `webhook.events` and `webhook.secret`. Store the secret now, for example as `KEENABLE_WEBHOOK_SECRET` in your secret manager. Once `webhook.events` is set, the monitor sends only the types it lists. If you leave `webhook.events` out, the monitor sends every event type, results included.

To change `webhook.url` or `webhook.events` later, send them to [Update a monitor](https://docs.keenable.ai/api-reference/monitors/update.md). The secret stays the same. If you add a webhook to a monitor that had none, the update response carries `webhook.secret` once. Store it then: no later response returns it.

## Verify the signature

Every delivery is an HTTP `POST` signed under the [Standard Webhooks](https://www.standardwebhooks.com) scheme. The signature is HMAC-SHA256 over `<webhook-id>.<webhook-timestamp>.<raw body>`, keyed with the base64-decoded part of `webhook.secret` after `whsec_`. Check it on the raw request body, before you parse the JSON.

These handlers listen on port 8080, refuse a body over 1 MB, reject a delivery whose signature doesn't match or whose timestamp is more than 5 minutes from now, and print the event's `id` and `type`. The size cap and read timeouts stop an unsigned sender from tying up memory or connections before the signature check. The TypeScript and Python handlers use only the standard library. The Go handler uses `VerifyWebhook` from the SDK:

```typescript TypeScript theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import { createHmac, timingSafeEqual } from "node:crypto";
import { createServer } from "node:http";

const secret = process.env.KEENABLE_WEBHOOK_SECRET ?? "";
if (!secret.startsWith("whsec_")) throw new Error("Set KEENABLE_WEBHOOK_SECRET to the monitor's webhook.secret");
const key = Buffer.from(secret.slice("whsec_".length), "base64");

function verify(body: Buffer, id: string, timestamp: string, signatures: string): boolean {
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;
  const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(body).digest();
  return signatures.split(" ").some((entry) => {
    const [version, signature = ""] = entry.split(",");
    const given = Buffer.from(signature, "base64");
    return version === "v1" && given.length === expected.length && timingSafeEqual(given, expected);
  });
}

const MAX_BODY = 1_000_000;

const server = createServer((req, res) => {
  const chunks: Buffer[] = [];
  let size = 0;
  req.on("data", (chunk: Buffer) => {
    size += chunk.length;
    if (size > MAX_BODY) {
      res.writeHead(413).end();
      req.destroy();
      return;
    }
    chunks.push(chunk);
  });
  req.on("end", () => {
    if (size > MAX_BODY) return;
    const body = Buffer.concat(chunks);
    const header = (name: string) => String(req.headers[name] ?? "");
    if (!verify(body, header("webhook-id"), header("webhook-timestamp"), header("webhook-signature"))) {
      res.writeHead(400).end();
      return;
    }
    const event = JSON.parse(body.toString("utf8"));
    console.log(event.id, event.type);
    res.writeHead(204).end();
  });
});
server.requestTimeout = 10_000;
server.headersTimeout = 5_000;
server.listen(8080);
```

```python Python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import base64
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

MAX_BODY = 1_000_000

SECRET = os.environ.get("KEENABLE_WEBHOOK_SECRET", "")
if not SECRET.startswith("whsec_"):
    raise SystemExit("Set KEENABLE_WEBHOOK_SECRET to the monitor's webhook.secret")
KEY = base64.b64decode(SECRET.removeprefix("whsec_"))


def verify(body: bytes, msg_id: str, timestamp: str, signatures: str) -> bool:
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > 300:
        return False
    mac = hmac.new(KEY, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256)
    expected = base64.b64encode(mac.digest()).decode()
    for entry in signatures.split():
        version, _, signature = entry.partition(",")
        if version == "v1" and hmac.compare_digest(signature, expected):
            return True
    return False


class Handler(BaseHTTPRequestHandler):
    timeout = 10

    def do_POST(self):
        raw = self.headers.get("Content-Length", "")
        if not (raw.isascii() and raw.isdigit()) or int(raw) > MAX_BODY:
            self.send_response(413 if raw.isascii() and raw.isdigit() else 411)
            self.end_headers()
            return
        body = self.rfile.read(int(raw))
        if not verify(
            body,
            self.headers.get("webhook-id", ""),
            self.headers.get("webhook-timestamp", ""),
            self.headers.get("webhook-signature", ""),
        ):
            self.send_response(400)
            self.end_headers()
            return
        event = json.loads(body)
        print(event["id"], event["type"], flush=True)
        self.send_response(204)
        self.end_headers()


ThreadingHTTPServer(("", 8080), Handler).serve_forever()
```

```go Go theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"time"

	"github.com/keenableai/keenable-sdk/go"
)

func main() {
	secret := os.Getenv("KEENABLE_WEBHOOK_SECRET")
	if secret == "" {
		log.Fatal("set KEENABLE_WEBHOOK_SECRET to the monitor's webhook.secret")
	}
	http.HandleFunc("/keenable", func(w http.ResponseWriter, r *http.Request) {
		body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1_000_000))
		if err != nil {
			http.Error(w, "", http.StatusBadRequest)
			return
		}
		event, err := keenable.VerifyWebhook(body, r.Header, secret, nil)
		var refused *keenable.WebhookVerificationError
		if errors.As(err, &refused) {
			http.Error(w, "", http.StatusBadRequest)
			return
		} else if err != nil {
			http.Error(w, "", http.StatusInternalServerError)
			return
		}
		fmt.Println(event.ID, event.Type)
		w.WriteHeader(http.StatusNoContent)
	})
	server := &http.Server{Addr: ":8080", ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second}
	log.Fatal(server.ListenAndServe())
}
```

When a page arrives, your handler prints a line such as `evt_9f2c4e1a7b3d4c5e8f6a0b1c2d3e4f5a monitor.result.found` and answers `204`. A forged delivery, or one whose timestamp is more than 5 minutes off, gets `400`.

## Drop repeated events

These handlers only verify and print. A retry of an event you already handled passes the signature check too, because an event keeps its `id` across retries. Record the `id` and do the event's work in one transaction: if the work fails, the record rolls back too, so the retry runs it again. Skip an event whose `id` is already recorded, and still answer `2xx` so Keenable stops retrying. In Python with SQLite, when the work writes to the same database:

```python theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import sqlite3


def handle_once(event: dict, work) -> None:
    """Runs work(db, event) at most once per event id. Raises if work fails, so nothing is recorded."""
    db = sqlite3.connect("events.db", timeout=30)
    try:
        with db:
            db.execute("CREATE TABLE IF NOT EXISTS seen (id TEXT PRIMARY KEY)")
            if db.execute("INSERT OR IGNORE INTO seen (id) VALUES (?)", (event["id"],)).rowcount == 0:
                return
            work(db, event)
    finally:
        db.close()
```

Call `handle_once(event, work)` after the signature check and answer `204`. Each call opens its own connection, so concurrent deliveries on the threaded handler never share a transaction. If it raises, answer `500`: the transaction rolls back and Keenable delivers the event again. For work outside the database, such as a call to another API, store the event as pending in the same insert, answer `204`, and have a worker mark it done after the call succeeds. The Go handler needs Go SDK 0.2.0 or later.

SDK 0.2.0 adds `verify_webhook` to the Python and Rust SDKs and `verifyWebhook` to the TypeScript SDK. They do the same checks and return a typed event. See [Verify a webhook](https://docs.keenable.ai/products/monitors#verify-a-webhook) for a handler in each language. Any Standard Webhooks library also verifies these deliveries with the monitor's `webhook.secret`.

## Test your handler locally

You don't need a real event to test your handler. This script signs a sample `monitor.result.found` delivery with your secret, the same way Keenable does, and sends it to `localhost:8080`:

```python send_test_event.py theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
import base64
import hashlib
import hmac
import json
import os
import time
import urllib.request

key = base64.b64decode(os.environ["KEENABLE_WEBHOOK_SECRET"].removeprefix("whsec_"))
event = {
    "id": "evt_test_0001",
    "type": "monitor.result.found",
    "created_at": "2026-11-19T09:00:00.000Z",
    "data": {
        "monitor_id": "mon_3kq9z2c8f1a04b7d9e6f5a21",
        "result": {"url": "https://example.com/news/example", "title": "Example headline", "importance": 4},
    },
    "metadata": {"team": "policy"},
}
body = json.dumps(event, separators=(",", ":")).encode()
msg_id, timestamp = event["id"], str(int(time.time()))
mac = hmac.new(key, f"{msg_id}.{timestamp}.".encode() + body, hashlib.sha256)
request = urllib.request.Request(
    "http://localhost:8080/keenable",
    data=body,
    method="POST",
    headers={
        "Content-Type": "application/json",
        "webhook-id": msg_id,
        "webhook-timestamp": timestamp,
        "webhook-signature": "v1," + base64.b64encode(mac.digest()).decode(),
    },
)
with urllib.request.urlopen(request) as response:
    print(response.status)
```

Start your handler, then run the script with the same `KEENABLE_WEBHOOK_SECRET`. The script prints `204` and your handler prints `evt_test_0001 monitor.result.found`. To test without a real secret, set both to a generated one:

```bash theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
export KEENABLE_WEBHOOK_SECRET="whsec_$(python3 -c 'import base64, os; print(base64.b64encode(os.urandom(24)).decode())')"
```

## Answer fast and drop repeats

Keenable delivers events under these rules. Build your handler around them:

| Rule | Value | What your handler does |
| - | - | - |
| Success | Any `2xx` status within 15 seconds | Verify, store the event, answer, then do slow work, such as calling a model, in the background. |
| Redirects | Not followed. A `3xx` counts as a failure | Point `webhook.url` at the final address. |
| Retries | Backoff from 30 seconds, doubling up to 6 hours, up to 12 attempts | Expect the same event more than once. |
| Not retried | A `4xx` other than `408` or `429` | Return `4xx` only for a delivery you never want again, such as a bad signature. Return a `5xx` for a temporary fault. |
| Event `id` | The same on every retry, and equal to the `webhook-id` header | Drop an event whose `id` you've already stored. |
| Order | Events of one monitor arrive in order. A failed event holds back that monitor's later events until it succeeds or runs out of attempts | Don't reorder events of one monitor. |
| Disabling | If no delivery succeeds for 3 days, Keenable disables the monitor and sends `monitor.disabled` | Fix the endpoint, then send `{"status": "active"}` with [Update a monitor](https://docs.keenable.ai/api-reference/monitors/update.md). |

## Debug failed deliveries

[List deliveries](https://docs.keenable.ai/api-reference/monitors/deliveries.md) shows each event of the last 7 days with its attempts, its last error and when the next attempt is due. This request lists the latest 10:

```bash theme={"theme":{"light":"github-light-high-contrast","dark":"dark-plus"}}
curl -G https://api.keenable.ai/v1/monitors/mon_3kq9z2c8f1a04b7d9e6f5a21/deliveries \
  -H "X-API-Key: $KEENABLE_API_KEY" \
  --data-urlencode "limit=10"
```

Each entry carries `type`, `attempts`, `delivered_at`, `last_error` and `next_attempt_at`. With the [CLI](https://docs.keenable.ai/cli.md), `keenable monitors deliveries mon_3kq9z2c8f1a04b7d9e6f5a21 -p` prints the same list. Read `last_error` against this table:

| `last_error` | Why | What to do |
| - | - | - |
| `HTTP 400` or another `4xx` | Your handler refused the delivery. If the code isn't `408` or `429`, Keenable doesn't retry it | Check that your handler verifies the raw body with the `webhook.secret` from the create response, or from the update that added the webhook. |
| `HTTP 301`, `HTTP 302`, `HTTP 307` or `HTTP 308` | Your URL redirects, and Keenable doesn't follow redirects | Set `webhook.url` to the final address. |
| `HTTP 500` or another `5xx` | Your handler failed | Fix the handler. Keenable retries the event with backoff. |
| A timeout or connection error | Your endpoint didn't answer within 15 seconds, or isn't reachable | Answer before you do slow work. Check that the host is public. |
| `bad url: ...` | Keenable can't send to the stored address | Set a valid public HTTPS URL with [Update a monitor](https://docs.keenable.ai/api-reference/monitors/update.md). |

If `data` is empty, the monitor hasn't sent anything. Check that `webhook.events` is empty or lists `monitor.result.found`, and that new results exist with [Read monitor results](https://docs.keenable.ai/guides/read-monitor-results.md).

## Related pages

* [Webhook payload](https://docs.keenable.ai/api-reference/monitors-webhook-payload.md): the headers, the envelope and the `data` of every event type.
* [Create a monitor](https://docs.keenable.ai/guides/create-a-monitor.md): set the webhook in the create request.
* [Monitors](https://docs.keenable.ai/products/monitors#webhook-events): which events a monitor sends by default.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.