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

# Connector functions

> The contract of the inbound and deliver functions: what your Node.js or Python code receives, what it answers, and the limits it runs within.

Each side of a [connector](https://docs.paddockai.dev/guides/connectors.md) runs one function: one file of your Node.js or Python, or a [preset](https://docs.paddockai.dev/guides/connectors.md#presets)'s code. The **inbound** function runs on every request to the connector's URL and decides whether it is genuine and which agents hear of it. The **deliver** function runs on every attempt of every message an agent [sends](https://docs.paddockai.dev/guides/outbox.md) through the connector and posts it to its destination. Both get the connector's secrets; neither touches sessions or messages itself.

## Set a function

```go Go theme={null}
code, err := os.ReadFile("function.py")
if err != nil {
	return err
}
fn, err := connector.Functions.Set(ctx, paddock.SideInbound, paddock.FunctionSet{
	Runtime: paddock.RuntimePython,
	Code:    string(code),
	Params:  map[string]string{"agent": agent.ID},
})
if err != nil {
	return err
}
fmt.Println(fn.Version)
```

```python Python theme={null}
from pathlib import Path

fn = connector.functions.set(
    "inbound",
    runtime="python3.14",
    code=Path("function.py").read_text(),
    params={"agent": agent.id},
)
print(fn.version)
```

```ts TypeScript theme={null}
import { readFile } from "node:fs/promises";

const fn = await connector.functions.set("inbound", {
  runtime: "python3.14",
  code: await readFile("function.py", "utf8"),
  params: { agent: agent.id },
});
console.log(fn.version);
```

`set` takes `code`, or a `preset` whose code for the side and runtime it copies, with its default params when you give none. It answers once the new version is published, so the next request or attempt runs it; every set raises the side's `version`. `functions.get(side)` returns the code, the runtime, and the params, and `functions.delete(side)` removes the function: the inbound side then answers every request `503`, and the outbound side refuses every send. The two sides are separate code with separate versions.

| Field | Meaning |
| - | - |
| `runtime` | `nodejs24.x` or `python3.14` |
| `code` | One UTF-8 file of at most 256 KiB; only the runtime's standard library is available |
| `params` | At most 20 values that are not secret, such as an agent's ID; keys of 1 to 64 of `[A-Za-z0-9_]`, values at most 1 KiB |

## Inbound contract

The code exports `handle(req, ctx)`, which may be async in Node.js:

```js Node.js theme={null}
// runtime nodejs24.x
export default async function handle(req, ctx) {
  const event = JSON.parse(req.body.toString("utf8"));
  if (event.type === "challenge") {
    return { respond: { status: 200, headers: { "content-type": "text/plain" }, body: event.challenge } };
  }
  return { accept: true, deliver: [{ agent: ctx.params.agent, sessionKey: null, message: event.text }] };
}
```

```python Python theme={null}
# runtime python3.14
import json

def handle(req, ctx):
    event = json.loads(req["body"])
    if event.get("type") == "challenge":
        return {"respond": {"status": 200, "headers": {"content-type": "text/plain"}, "body": event["challenge"]}}
    return {"accept": True, "deliver": [{"agent": ctx["params"]["agent"], "sessionKey": None, "message": event["text"]}]}
```

| Input | Holds |
| - | - |
| `req.method` | `POST` |
| `req.url` | The URL the sender called, with the query string exactly as received, so a scheme that signs the URL, such as HubSpot's, can be checked |
| `req.query` | The query parameters; one given more than once has its values joined with `,` |
| `req.headers` | Every header, its name in lowercase; one sent more than once has its values joined with `, ` |
| `req.body` | The bytes received, at most 1 MiB: a `Buffer` in Node.js, `bytes` in Python |
| `ctx.connectorId`, `ctx.connectorName` | The connector's ID and name; build reply keys from the name |
| `ctx.secret`, `ctx.secrets` | The `default` secret, and every secret by name, as they are now |
| `ctx.params` | The function's params |
| `ctx.replay` | `{ receivedAt }`, the first delivery's receipt time, when the request is a [replay](https://docs.paddockai.dev/guides/connectors.md#replay); `null` otherwise |

| Answer | Meaning | The sender gets |
| - | - | - |
| `{ accept: true, dedupeKey?, deliver }` | Accepted. `deliver` lists up to 20 [routes](https://docs.paddockai.dev/guides/connectors.md#routes); `dedupeKey`, 1 to 500 bytes, names the event for deduplication, and without one the body's hash does | `202`, or `200` for a duplicate |
| `{ respond: { status, headers?, body? } }` | A handshake: `status` from 200 to 299, `body` a string of at most 64 KiB, at most 20 headers. Recorded as a `handshake`, with no route | The answer as given |
| `{ accept: false, reason? }` | Rejected; `reason`, at most 1 KiB, says why | `401`, recorded as `function_rejected` |
| A thrown error, an answer of none of these shapes or over a bound, or a failed invocation | The function failed | `503`, recorded as `function_error`, so the sender retries |
| No answer within 2 seconds | The function failed | `503`, recorded as `function_timeout` |

### What the signature presets check

| Preset | Checks | Dedupe key |
| - | - | - |
| `github` | `X-Hub-Signature-256`: `sha256=` and the hex HMAC-SHA256 of the body | `X-GitHub-Delivery` |
| `slack` | `X-Slack-Signature`: `v0=` and the hex HMAC-SHA256 of `v0:{timestamp}:{body}`, the timestamp within `toleranceSeconds` (default 300); answers `url_verification` | `event_id` |
| `stripe` | `Stripe-Signature`: any `v1` matching the hex HMAC-SHA256 of `{t}.{body}`, within 300 seconds | The event's `id` |
| `hubspot-v2` | `X-HubSpot-Signature`: the hex SHA-256 of the secret, the method, the URL, and the body. Workflow webhooks send it | None: the body's hash |
| `hubspot-v3` | `X-HubSpot-Signature-v3`: the base64 HMAC-SHA256 of the method, the URL, the body, and `X-HubSpot-Request-Timestamp`, within 300 seconds | None: the body's hash |
| `shopify` | `X-Shopify-Hmac-SHA256`: the base64 HMAC-SHA256 of the body | `X-Shopify-Webhook-Id` |
| `linear` | `Linear-Signature`: the hex HMAC-SHA256 of the body; `Linear-Timestamp` within 60 seconds | `Linear-Delivery` |
| `standard-webhooks` | `webhook-signature`: any `v1,` entry matching the base64 HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{body}`, keyed with the `whsec_` secret, within 300 seconds. Clerk, Resend, and Svix use it | `webhook-id` |

Each also accepts the secret `previous` during a rotation, and measures a replay's timestamp against `ctx.replay.receivedAt`.

## Deliver contract

The code exports `deliver(msg, ctx)`, which may be async in Node.js:

```js Node.js theme={null}
// runtime nodejs24.x
export async function deliver(msg, ctx) {
  let res;
  try {
    res = await fetch(ctx.params.url, {
      method: "POST",
      headers: {
        "content-type": "application/json",
        "idempotency-key": msg.id,
        authorization: `Bearer ${ctx.secrets.api_token}`,
      },
      body: JSON.stringify({ to: msg.address, markdown: msg.text }),
      signal: AbortSignal.timeout(20_000),
    });
  } catch (e) {
    return { ok: false, retryable: true, reason: String(e) };
  }
  if (res.ok) return { ok: true, externalId: (await res.json()).id };
  if (res.status === 429) return { ok: false, retryable: true, retryAfter: Number(res.headers.get("retry-after") ?? 30) };
  if (res.status >= 500) return { ok: false, retryable: true, reason: `HTTP ${res.status}` };
  if (res.status === 401 || res.status === 403) return { ok: false, retryable: false, code: "auth", reason: await res.text() };
  return { ok: false, retryable: false, code: res.status === 404 ? "not_found" : null, reason: await res.text() };
}
```

```python Python theme={null}
# runtime python3.14
import json, urllib.error, urllib.request

def deliver(msg, ctx):
    req = urllib.request.Request(
        ctx["params"]["url"],
        data=json.dumps({"to": msg["address"], "markdown": msg["text"]}).encode(),
        headers={"content-type": "application/json", "idempotency-key": msg["id"],
                 "authorization": "Bearer " + ctx["secrets"]["api_token"]},
        method="POST")
    try:
        with urllib.request.urlopen(req, timeout=20) as res:
            return {"ok": True, "externalId": json.load(res)["id"]}
    except urllib.error.HTTPError as e:
        if e.code == 429:
            return {"ok": False, "retryable": True, "retryAfter": int(e.headers.get("retry-after", "30"))}
        if e.code >= 500:
            return {"ok": False, "retryable": True, "reason": f"HTTP {e.code}"}
        code = "auth" if e.code in (401, 403) else "not_found" if e.code == 404 else None
        return {"ok": False, "retryable": False, "code": code, "reason": e.read().decode()}
    except OSError as e:
        return {"ok": False, "retryable": True, "reason": str(e)}
```

| Input | Holds |
| - | - |
| `msg.id` | The message's `obx_...` ID, the same on every attempt: the idempotency key to give a destination that takes one |
| `msg.key`, `msg.address` | The key, and its part after the connector's name and the first `:` |
| `msg.text` | The text, Markdown, as the agent sent it |
| `msg.attachments` | `[{ name, contentType, size, url }]`, each `url` a download link valid one hour; empty when there are none |
| `msg.session`, `msg.agent` | `{ id, metadata }` of the session that sent it, and `{ id }` of its agent |
| `msg.origin` | `{ connectorId, deliveryId, position }`: the inbound route whose message started the turn that sent it; `null` otherwise |
| `msg.attempt` | 1 for the first attempt, then the count so far |
| `ctx.connectorId`, `ctx.secret`, `ctx.secrets`, `ctx.params` | As for the inbound function |
| `ctx.progress` | What the previous attempt answered as `progress`; `null` on the first attempt |

| Answer | Meaning |
| - | - |
| `{ ok: true, externalId? }` | Delivered. `externalId`, at most 500 bytes, names what was posted, so a reply to it can find the session ([reply routing](https://docs.paddockai.dev/guides/outbox.md#reply-routing)) |
| `{ ok: false, retryable: true, retryAfter?, reason?, progress? }` | Not delivered, and may be later: tried again. `retryAfter`, 1 to 3,600 seconds, is the destination's rate limit and holds the whole connector |
| `{ ok: false, retryable: false, code?, reason?, progress? }` | Never deliverable: the message fails. `code` is yours, `[a-z_]`; `auth` marks the connector's credential as broken, `not_found` a destination that is gone |

A thrown error, a timeout, or an answer outside these shapes counts as retryable. Delivery is at least once: an attempt whose answer is lost is tried again with the same `msg.id`. A deliver function that posts in several steps, such as a long message split in parts, answers its `progress` with a retryable error, and the next attempt resumes from `ctx.progress` instead of posting twice.

## Test before you save

`connector.functions.test(side, request)` runs the saved version, or `draft: { runtime, code, params }`, and returns the result with the last 4 KiB the code logged. An inbound test runs on `event: { headers, query, body }` or on a recorded `deliveryId`, records nothing, and delivers nothing. An outbound test runs on `message: { address, text, attachments? }` and **delivers for real**, to the address given, without recording an outbox message.

```go Go theme={null}
res, err := connector.Functions.Test(ctx, paddock.SideOutbound, paddock.FunctionTestRequest{
	Message: &paddock.DeliverTestMessage{Address: "C0123ABCD", Text: "Hello from paddock"},
})
if err != nil {
	return err
}
fmt.Println(res.Result, res.ExternalID, res.Logs)
```

```python Python theme={null}
res = connector.functions.test("outbound", message={"address": "C0123ABCD", "text": "Hello from paddock"})
print(res.result, res.external_id, res.logs)
```

```ts TypeScript theme={null}
const res = await connector.functions.test("outbound", {
  message: { address: "C0123ABCD", text: "Hello from paddock" },
});
console.log(res.result, res.externalId, res.logs);
```

## Where functions run

Functions run on AWS Lambda, one per side, with no AWS permissions and no environment variables; they may open outbound connections. What they print reaches you only through a test. Nothing kept in memory survives from one request to the next.

| Limit | Inbound | Deliver |
| - | - | - |
| Time | 2 seconds to run; paddock waits at most 2.5 seconds, cold start included | 30 seconds; paddock waits at most 35 |
| Memory | 128 MB | 256 MB |
| Input | A body of at most 1 MiB | A message of at most 100 KB, with attachment links |
| Logs | The last 4 KiB, shown only by a test | The same |


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