# Build a custom integration

Expose your own tools through a signed HTTP endpoint, test them, and enable them in a world.

## Configure from your backend

Use the [custom integration API](https://smallworld.sh/docs/create-custom-integration.md) to create, edit, rename, test, rotate signing secrets, or delete integrations with a workspace API key. For setup before saving, obtain [draft credentials](https://smallworld.sh/docs/create-custom-integration-draft.md), configure the secret in your endpoint, and run a draft terminal test. Creation can reuse that draft secret. Saved header values and signing secrets are never returned by configuration reads.

Services that speak MCP can use [MCP detection](https://smallworld.sh/docs/detect-mcp-integration.md) and [setup verification](https://smallworld.sh/docs/verify-mcp-setup.md)before [registration](https://smallworld.sh/docs/create-mcp-integration.md). Verification can contact the server and register an OAuth client; direct tests can change remote data.

## Start with a greeting

This example runs a small Express server with one tool. You need Node.js 22 or later. If your service already speaks MCP, use [an MCP server](https://app.smallworld.sh/app/integrations/mcp/new) instead.

- Save [server.mjs](https://smallworld.sh/docs-assets/examples/custom-integration.mjs) in a new folder, then install Express.

- Open [Create integration](https://app.smallworld.sh/app/integrations/custom/new). Use `hello` as the command and `http://localhost:4318/tools` as the endpoint for local development.

- Copy the signing secret from the endpoint step into a local `.env` file. Keep it on your server, outside source control.

Install

```bash
npm init -y
npm install express
```

.env

```bash
SMALLWORLD_SIGNING_SECRET=whsec_replace_with_the_signing_secret
```

Run

```bash
node --env-file=.env server.mjs
```

The server listens on port 4318. Set `PORT` to use another port, and change the endpoint to match.

Express server

server.mjs

```javascript
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
import { pathToFileURL } from "node:url";

export function createApp(signingSecret) {
  if (!signingSecret?.startsWith("whsec_")) throw new Error("Set SMALLWORLD_SIGNING_SECRET from the integration setup.");
  const key = Buffer.from(signingSecret.slice(6), "base64");
  if (key.length !== 32) throw new Error("The signing secret must contain a 32-byte key.");
  const app = express();

  // Keep this route before any express.json() middleware.
  app.post("/tools", express.raw({ type: "application/json", limit: "1mb" }), (req, res) => {
    const id = req.get("webhook-id");
    const timestamp = req.get("webhook-timestamp");
    const signatures = req.get("webhook-signature") ?? "";
    const fresh = /^\d+$/.test(timestamp ?? "") && Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
    if (!id || !fresh || !Buffer.isBuffer(req.body)) return res.status(401).json({ error: { code: "invalid_signature", message: "Request verification failed." } });

    const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(req.body).digest();
    const verified = signatures.split(" ").some((signature) => {
      if (!signature.startsWith("v1,")) return false;
      const received = Buffer.from(signature.slice(3), "base64");
      return received.length === expected.length && timingSafeEqual(received, expected);
    });
    if (!verified) return res.status(401).json({ error: { code: "invalid_signature", message: "Request verification failed." } });

    let call;
    try {
      call = JSON.parse(req.body.toString("utf8"));
    } catch {
      return res.status(400).json({ error: { code: "invalid_json", message: "Expected a JSON request." } });
    }
    if (call?.type !== "tool_call" || call.id !== id || typeof call.user?.id !== "string" || !call.user.id)
      return res.status(400).json({ error: { code: "invalid_call", message: "Expected a tool call with a user." } });
    if (call.name !== "greet") return res.status(404).json({ error: { code: "unknown_tool", message: "This endpoint only handles greet." } });
    if (typeof call.arguments?.name !== "string" || !call.arguments.name.trim() || call.arguments.name.length > 100)
      return res.status(400).json({ error: { code: "invalid_name", message: "Use a name from 1 to 100 characters." } });

    // Direct tests have null worldId, sessionId, and executionId.
    // For a real backend operation, authorize call.user.id before accessing its data.
    return res.json({ greeting: `Hello, ${call.arguments.name}!` });
  });
  return app;
}

if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
  const port = Number(process.env.PORT ?? 4318);
  createApp(process.env.SMALLWORLD_SIGNING_SECRET).listen(port, "127.0.0.1", () => console.log(`Listening on http://localhost:${port}/tools`));
}

```

## Add the tool

Paste this definition in the tools step. OpenAI, Anthropic, and MCP tool definitions are accepted. The example becomes `hello greet`.

Tool definition

```json
[
  {
    "type": "function",
    "function": {
      "name": "greet",
      "description": "Return a greeting for a name.",
      "parameters": {
        "type": "object",
        "properties": {
          "name": {
            "type": "string",
            "minLength": 1,
            "maxLength": 100
          }
        },
        "required": [
          "name"
        ],
        "additionalProperties": false
      }
    }
  }
]
```

Run this in the setup terminal, or use the saved integration's Test tab with tool `greet` and arguments `{"name":"Ada"}`.

Try the command

```bash
hello greet --json '{"name":"Ada"}'
```

The result is `{"greeting":"Hello, Ada!"}`. After saving, enable the integration in a World and select that World in Playground to try its normal permissions and approval flow.

## Names and limits

- The command is 2–32 lowercase letters, digits, or hyphens, starting with a letter. It can’t be a terminal command (such as `ls` or `jq`), a shell builtin, a built-in integration’s command, or one of `smallworld`, `tools`, `custom`, `mcp`, `integration`, `integrations`, and `executor`.

- An integration has at most 100 tools, and each definition is at most 64 KB. Tool names use letters, digits, `_`, `-`, and single dots, start with a letter, digit, or `_`, and have at most 128 characters.

- In the terminal, a tool name becomes kebab-case without a leading `<command>_` or `<command>-`: `get_order` and `acme_getOrder` both run as `acme get-order`.

- The name has at most 60 characters, the description at most 500, and the endpoint can send up to 10 static headers.

## What the endpoint receives

Each tool call sends one signed POST to your endpoint. `user.id` is your application's user identifier. Look up and authorize that user before accessing their data. `user.group` is the [group](https://smallworld.sh/docs/guides/connect-group.md) the session acts for, with your `id` and its `name`, or `null` in a groupless session.

Request fields

```typescript
type ToolCall = {
  type: "tool_call";
  id: string; // Also sent in webhook-id.
  integration: string; // Your integration's command.
  name: string; // The original tool name from its definition.
  arguments: Record<string, unknown>;
  user: { id: string; test: boolean; group: { id: string; name: string | null } | null };
  worldId: string | null;
  sessionId: string | null;
  executionId: string | null;
  approved: boolean;
  context?: Record<string, unknown>;
};
```

World calls include World, session, and execution IDs. Playground runs also have these IDs, with `user.test` set to `true`.

World call example

World request

```json
{
  "type": "tool_call",
  "id": "b5212df0-ea8b-4eb8-a7b1-057ff45b3044",
  "integration": "hello",
  "name": "greet",
  "arguments": {
    "name": "example"
  },
  "user": {
    "id": "customer_123",
    "test": false,
    "group": {
      "id": "team_42",
      "name": "Support team"
    }
  },
  "worldId": "01995e56-e2d4-7f19-b691-7bf9af6abdc8",
  "sessionId": "01995e57-0501-76b8-b797-5b24df5b307f",
  "executionId": "01995e57-3027-7557-a233-009ea3dcd8fc",
  "approved": true,
  "context": {
    "orderSource": "your-app"
  }
}
```

Direct tests use the Playground user, set all three IDs to `null`, and set `approved` to `true`. No execution `context` is supplied.

Direct test example

Test request

```json
{
  "type": "tool_call",
  "id": "b5212df0-ea8b-4eb8-a7b1-057ff45b3044",
  "integration": "hello",
  "name": "greet",
  "arguments": {
    "name": "example"
  },
  "user": {
    "id": "playground_example",
    "test": true,
    "group": {
      "id": "playground-group_example",
      "name": "Playground Group"
    }
  },
  "worldId": null,
  "sessionId": null,
  "executionId": null,
  "approved": true
}
```

Direct tests make real calls. Smallworld leaves them out of integration activity, but your endpoint can still create or change data. `user.test` identifies the Playground user; it does not make a call a dry run.

For World calls, `approved` is true when approval was granted. It can be false for a tool that is allowed without asking. Optional `context` is the JSON object supplied to [the execution request](https://smallworld.sh/docs/execute-command.md).

## Verify the signature

Smallworld uses Standard Webhooks signing. Verify the unmodified request bytes before parsing JSON. An `express.json()` middleware before this handler would lose those bytes.

Request headers

```http
content-type: application/json
user-agent: Smallworld/0.1.0
webhook-id: b5212df0-ea8b-4eb8-a7b1-057ff45b3044
webhook-timestamp: 1791460800
webhook-signature: v1,[signature]
```

Decode the part after `whsec_` as base64. Use it as the HMAC-SHA256 key for `webhook-id + "." + webhook-timestamp + "." + rawBody`. The signature is `v1,` followed by the base64 digest. The timestamp is Unix seconds.

The example checks the timestamp within five minutes and compares signatures in constant time. A Standard Webhooks library can do this for you. Keep a record of call `id` values before making changes if your endpoint needs to reject duplicate requests.

Rotating the secret replaces it immediately, with no overlap. Choose **Rotate secret** on the integration's Settings tab and copy the new secret, which is shown once. Update `SMALLWORLD_SIGNING_SECRET` and restart your endpoint. Calls made in between fail your signature check and are not retried, so rotate while your agents are idle.

## Return a result

Return `2xx` with JSON and `content-type: application/json`. That body becomes the tool's output. A `2xx` body without a JSON content type, or that isn't valid JSON, becomes the output as plain text, and the command still succeeds. For a failure, use a non-`2xx` status and this error shape.

Error response

```json
{
  "error": {
    "code": "order_not_found",
    "message": "No order belongs to this user."
  }
}
```

The agent sees a failure on stderr as `<command>: <tool>: <code>: <message>`, and the tool command exits with 1. In `js-exec`, the call rejects with the message `<code>: <message>`. Without this shape, the code is `http_<status>` and the message is the start of the response body, without HTML markup.

stderr

```plaintext
acme: order-refund: refund_window_closed: Order o_1 is older than 30 days
```

Smallworld sends each call once and does not retry it. If the connection times out or drops after dispatch, the call is `unknown`: the endpoint may have acted. Check your records before repeating the operation. The Test tab and the setup terminal report a timeout the same way.

The default timeout is 30 seconds and the response limit is 1 MB. The timeout can be changed from 1 to 60 seconds in the integration's endpoint settings.

## Reach your endpoint

The Smallworld server calls your endpoint. Opening the URL in your browser only checks access from your computer.

Local Smallworld development accepts HTTP on `localhost`, `127.0.0.1`, or `[::1]`. The example binds to `127.0.0.1` on the same machine. If Smallworld runs in a container, its localhost belongs to that container.

Production requires a public HTTPS endpoint. Private and loopback addresses are blocked. Redirects are not followed: a redirect fails the call with the code `http_<status>` and a message naming where it pointed. For a hosted instance, deploy the handler to a public HTTPS address before testing it.

Use the tester's request, response, and timing to distinguish a connection failure from an error returned by your handler. A signature failure usually means the signing secret or raw body does not match.

## Use the integration in your application

Follow the [Quick start](https://smallworld.sh/docs/guides/quick-start.md) with the world where you enabled your integration, then replace `echo hello` with `hello greet --json '{"name":"Ada"}'`. Your signed endpoint receives the application user's ID and returns the greeting as tool output.

To ask a user before running a tool, set its permission to **Ask before running** and follow [Approve a tool call](https://smallworld.sh/docs/guides/approve-tool-call.md).
