Skip to content

About

Official TypeScript SDK for BotShield — privacy-first human verification (passkeys, no PII) and Agents Ask approvals

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

botshield-sdk

Official TypeScript SDK for BotShield — privacy-first human verification. A visitor proves a real person is present with the passkey already on their phone; your site learns only that the check passed. No PII, no CAPTCHA, no birthdates.

npm Docs License: MIT Built by Speakeasy

Links: Website · Documentation · API reference · Developer Console (free plan, 1 gate) · Live demos · Feedback & roadmap

Quickstart

Most integrations need only the browser widget. Get a site key in the Console, then:

<script src="https://cdn.botshield.ai/sdk.js"></script>

<botshield-verify
  site-key="pk_live_…"
  scope="checkout"
  checkout-label="Complete purchase">
</botshield-verify>

<script>
  document.querySelector('botshield-verify')
    .addEventListener('botshield:success', (e) => {
      // e.detail.token — hand it to your server and confirm it there
    });
</script>

On your server, confirm the token with this SDK (census.verifyToken) before trusting it. Gates, age checks, Trusted Accounts and Agents Ask are configured in the Console and documented at docs.botshield.ai: BotShield Gate · Trusted Accounts · Agents Ask.

Note

The SDK is generated from the BotShield OpenAPI spec by Speakeasy. Everything below this line is the generated reference.

Summary

BotShield API: Human presence verification protocol.

BotShield Human Verification — a BotShield Gate (checkout, sign-up, any action moment) asks whether a live human is present. The client pre-check returns the two-result-state contract result_state: human_verified | unavailable; when presence is required the person confirms with their passkey in the BotShield app and the gate receives an ES256 attestation JWT, verifiable against the public JWKS at /.well-known/jwks.json. No identity crosses the boundary.

Agents Ask — an agent proposes an action; the human confirms in the BotShield app and BotShield signs a Proof of Resolution JWT.

Frontend: load the BotShield client script from https://cdn.botshield.ai/sdk.js and place the botshield-verify element.

Backend SDK: install botshield-sdk from npm and use client.census.*, client.verification.*, client.actions.*.

Response envelope: every operation answers HTTP 200 with { data: ... }. Most carry the result one level deeper (data.data); logout and verification/status carry it directly. Handler errors are also HTTP 200 — data.error = { message, statusCode } — so check data.error before reading a result. HTTP 400 is reserved for input validation (InvalidInputError), 500 for unhandled failures.

Alias window (2026-10-15 → 2027-01-15): renamed wire symbols are dual-served — old names accepted on input and emitted beside the new until the sunset; any response where an alias was used carries Deprecation, Sunset and Link headers and data._deprecation. Changelog: https://docs.botshield.ai/changelog/alias-window

Table of Contents

SDK Installation

The SDK can be installed with either npm, pnpm, bun or yarn package managers.

NPM

npm add botshield-sdk

PNPM

pnpm add botshield-sdk

Bun

bun add botshield-sdk

Yarn

yarn add botshield-sdk

Note

This package is published with CommonJS and ES Modules (ESM) support.

Model Context Protocol (MCP) Server

This SDK is also an installable MCP server where the various SDK methods are exposed as tools that can be invoked by AI applications.

Node.js v20 or greater is required to run the MCP server from npm.

Claude installation steps

Add the following server definition to your claude_desktop_config.json file:

{
  "mcpServers": {
    "BotShield": {
      "command": "npx",
      "args": [
        "-y", "--package", "botshield-sdk",
        "--",
        "mcp", "start",
        "--agent-key-auth", "...",
        "--agent-key-auth1", "..."
      ]
    }
  }
}
Cursor installation steps

Create a .cursor/mcp.json file in your project root with the following content:

{
  "mcpServers": {
    "BotShield": {
      "command": "npx",
      "args": [
        "-y", "--package", "botshield-sdk",
        "--",
        "mcp", "start",
        "--agent-key-auth", "...",
        "--agent-key-auth1", "..."
      ]
    }
  }
}

You can also run MCP servers as a standalone binary with no additional dependencies. You must pull these binaries from available Github releases:

curl -L -o mcp-server \
    https://github.com/{org}/{repo}/releases/download/{tag}/mcp-server-bun-darwin-arm64 && \
chmod +x mcp-server

If the repo is a private repo you must add your Github PAT to download a release -H "Authorization: Bearer {GITHUB_PAT}".

{
  "mcpServers": {
    "Todos": {
      "command": "./DOWNLOAD/PATH/mcp-server",
      "args": [
        "start"
      ]
    }
  }
}

For a full list of server arguments, run:

npx -y --package botshield-sdk -- mcp start --help

Requirements

For supported JavaScript runtimes, please consult RUNTIMES.md.

SDK Example Usage

Example

import { BotShield } from "botshield-sdk";

const botShield = new BotShield();

async function run() {
  const result = await botShield.census.createSession({
    apiKeyAuth: "<YOUR_API_KEY_HERE>",
  }, {});

  console.log(result);
}

run();

Authentication

Per-Client Security Schemes

This SDK supports the following security schemes globally:

Name Type Scheme
agentKeyAuth apiKey API key
agentKeyAuth1 apiKey API key

You can set the security parameters through the security optional parameter when initializing the SDK client instance. The selected scheme will be used by default to authenticate with the API for all operations that support it. For example:

import { BotShield } from "botshield-sdk";

const botShield = new BotShield({
  security: {
    agentKeyAuth: "<YOUR_API_KEY_HERE>",
  },
});

async function run() {
  const result = await botShield.census.storeSignal({
    siteKey: "<value>",
    score: 229498,
  });

  console.log(result);
}

run();

Per-Operation Security Schemes

Some operations in this SDK require the security scheme to be specified at the request level. For example:

import { BotShield } from "botshield-sdk";

const botShield = new BotShield();

async function run() {
  const result = await botShield.census.createSession({
    apiKeyAuth: "<YOUR_API_KEY_HERE>",
  }, {});

  console.log(result);
}

run();

Available Resources and Operations

Available methods
  • create - Place a BotShield Action
  • list - List BotShield Actions
  • setState - Turn a BotShield Action on or off
  • update - Rename a BotShield Action, or mark it staff can send
  • request - Ask a linked person to confirm an action
  • requestStatus - Where an action request stands
  • requestCancel - Withdraw an action request
  • getOptions - Start the inline passkey for one request
  • complete - Finish the inline passkey for one request
  • list - List Secured Accounts
  • revoke - Revoke a Secured Account
  • getStatus - Get Secured Account status
  • request - Ask for a passkey sign-in
  • confirm - Redeem a passkey sign-in

Standalone functions

All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.

To read more about standalone functions, check FUNCTIONS.md.

Available standalone functions

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:

import { BotShield } from "botshield-sdk";

const botShield = new BotShield();

async function run() {
  const result = await botShield.census.createSession(
    {
      apiKeyAuth: "<YOUR_API_KEY_HERE>",
    },
    {},
    {
      retries: {
        strategy: "backoff",
        backoff: {
          initialInterval: 1,
          maxInterval: 50,
          exponent: 1.1,
          maxElapsedTime: 100,
        },
        retryConnectionErrors: false,
      },
    },
  );

  console.log(result);
}

run();

If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:

import { BotShield } from "botshield-sdk";

const botShield = new BotShield({
  retryConfig: {
    strategy: "backoff",
    backoff: {
      initialInterval: 1,
      maxInterval: 50,
      exponent: 1.1,
      maxElapsedTime: 100,
    },
    retryConnectionErrors: false,
  },
});

async function run() {
  const result = await botShield.census.createSession({
    apiKeyAuth: "<YOUR_API_KEY_HERE>",
  }, {});

  console.log(result);
}

run();

Error Handling

BotShieldError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
error.message string Error message
error.statusCode number HTTP response status code eg 404
error.headers Headers HTTP response headers
error.body string HTTP body. Can be empty string if no body is returned.
error.rawResponse Response Raw HTTP response
error.data$ Optional. Some errors may contain structured data. See Error Classes.

Example

import { BotShield } from "botshield-sdk";
import * as errors from "botshield-sdk/models/errors";

const botShield = new BotShield();

async function run() {
  try {
    const result = await botShield.census.createSession({
      apiKeyAuth: "<YOUR_API_KEY_HERE>",
    }, {});

    console.log(result);
  } catch (error) {
    // The base class for HTTP error responses
    if (error instanceof errors.BotShieldError) {
      console.log(error.message);
      console.log(error.statusCode);
      console.log(error.body);
      console.log(error.headers);

      // Depending on the method different errors may be thrown
      if (error instanceof errors.InvalidInputError) {
        console.log(error.data$.message); // string
        console.log(error.data$.input); // { [k: string]: any }
        console.log(error.data$.errors); // InvalidInputErrorError[]
      }
    }
  }
}

run();

Error Classes

Primary errors:

Less common errors (6)

Network errors:

Inherit from BotShieldError:

  • ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. See error.rawValue for the raw value and error.pretty() for a nicely formatted multi-line string.

* Check the method documentation to see if the error is applicable.

Server Selection

Select Server by Name

You can override the default server globally by passing a server name to the server: keyof typeof ServerList optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
production https://api.botshield.ai/operations Production (default)
staging https://wg-staging.botshield.ai/operations Staging
local http://localhost:9991/operations Local development

Example

import { BotShield } from "botshield-sdk";

const botShield = new BotShield({
  server: "production",
});

async function run() {
  const result = await botShield.census.createSession({
    apiKeyAuth: "<YOUR_API_KEY_HERE>",
  }, {});

  console.log(result);
}

run();

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverURL: string optional parameter when initializing the SDK client instance. For example:

import { BotShield } from "botshield-sdk";

const botShield = new BotShield({
  serverURL: "https://api.botshield.ai/operations",
});

async function run() {
  const result = await botShield.census.createSession({
    apiKeyAuth: "<YOUR_API_KEY_HERE>",
  }, {});

  console.log(result);
}

run();

Custom HTTP Client

The TypeScript SDK makes API calls using an HTTPClient that wraps the native Fetch API. This client is a thin wrapper around fetch and provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The HTTPClient constructor takes an optional fetcher argument that can be used to integrate a third-party HTTP client or when writing tests to mock out the HTTP client and feed in fixtures.

The following example shows how to:

  • route requests through a proxy server using undici's ProxyAgent
  • use the "beforeRequest" hook to add a custom header and a timeout to requests
  • use the "requestError" hook to log errors
import { BotShield } from "botshield-sdk";
import { ProxyAgent } from "undici";
import { HTTPClient } from "botshield-sdk/lib/http";

const dispatcher = new ProxyAgent("http://proxy.example.com:8080");

const httpClient = new HTTPClient({
  // 'fetcher' takes a function that has the same signature as native 'fetch'.
  fetcher: (input, init) =>
    // 'dispatcher' is specific to undici and not part of the standard Fetch API.
    fetch(input, { ...init, dispatcher } as RequestInit),
});

httpClient.addHook("beforeRequest", (request) => {
  const nextRequest = new Request(request, {
    signal: request.signal || AbortSignal.timeout(5000)
  });

  nextRequest.headers.set("x-custom-header", "custom value");

  return nextRequest;
});

httpClient.addHook("requestError", (error, request) => {
  console.group("Request Error");
  console.log("Reason:", `${error}`);
  console.log("Endpoint:", `${request.method} ${request.url}`);
  console.groupEnd();
});

const sdk = new BotShield({ httpClient: httpClient });

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass a logger that matches console's interface as an SDK option.

Warning

Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.

import { BotShield } from "botshield-sdk";

const sdk = new BotShield({ debugLogger: console });

Development

Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.

Contributions

While we value open-source contributions to this SDK, this library is generated programmatically. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with a proof of concept and we'll do our best to include it in a future release.

SDK Created by Speakeasy

About

Official TypeScript SDK for BotShield — privacy-first human verification (passkeys, no PII) and Agents Ask approvals

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages