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.
Links: Website · Documentation · API reference · Developer Console (free plan, 1 gate) · Live demos · Feedback & roadmap
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.
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
The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add botshield-sdkpnpm add botshield-sdkbun add botshield-sdkyarn add botshield-sdkNote
This package is published with CommonJS and ES Modules (ESM) support.
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-serverIf 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 --helpFor supported JavaScript runtimes, please consult RUNTIMES.md.
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();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();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 methods
- verifyResolution - Check a Proof of Resolution (works once)
- proposeAction - Propose an action for human confirmation
- checkActionStatus - Check action proposal status
- cancelAction - Cancel a queued action proposal
- createSession - Create a grant token
- createVerificationLink - Create a verification request
- verifyToken - Validate a verification token
- storeSignal - Store a Signal Pixel bot score
- validateSignal - Validate a signal token
- getPartnerConfig - Get partner configuration
- revokeVerification - Revoke a pending verification
- logout - Revoke a grant token
- confirmLink - Confirm a pending link
- sendByNumber - Send a request to verify by phone number
- create - Place a gate
- activate - Activate a gate
- close - Close a gate
- extend - Extend a gate's window
- cancel - Cancel a gate
- get - Get a gate
- list - List gates
- 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
- exchange - Redeem a recovery code
- otherRoute - Report another sign-in reset
- list - List Secured Accounts
- revoke - Revoke a Secured Account
- getStatus - Get Secured Account status
- getStatus - Check verification status
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
actionsCancelAction- Cancel a queued action proposalactionsCheckActionStatus- Check action proposal statusactionsProposeAction- Propose an action for human confirmationactionsVerifyResolution- Check a Proof of Resolution (works once)censusConfirmLink- Confirm a pending linkcensusCreateSession- Create a grant tokencensusCreateVerificationLink- Create a verification requestcensusGetPartnerConfig- Get partner configurationcensusLogout- Revoke a grant tokencensusRevokeVerification- Revoke a pending verificationcensusSendByNumber- Send a request to verify by phone numbercensusStoreSignal- Store a Signal Pixel bot scorecensusValidateSignal- Validate a signal tokencensusVerifyToken- Validate a verification tokengatesActionsCreate- Place a BotShield ActiongatesActionsList- List BotShield ActionsgatesActionsRequest- Ask a linked person to confirm an actiongatesActionsRequestCancel- Withdraw an action requestgatesActionsRequestStatus- Where an action request standsgatesActionsSetState- Turn a BotShield Action on or offgatesActionsUpdate- Rename a BotShield Action, or mark it staff can sendgatesActivate- Activate a gategatesCancel- Cancel a gategatesClose- Close a gategatesCreate- Place a gategatesExtend- Extend a gate's windowgatesGet- Get a gategatesList- List gatesinlinePasskeyComplete- Finish the inline passkey for one requestinlinePasskeyGetOptions- Start the inline passkey for one requestrecoveryExchange- Redeem a recovery coderecoveryOtherRoute- Report another sign-in resetsecuredAccountsGetStatus- Get Secured Account statussecuredAccountsList- List Secured AccountssecuredAccountsRevoke- Revoke a Secured AccountsignInConfirm- Redeem a passkey sign-insignInRequest- Ask for a passkey sign-inverificationGetStatus- Check verification status
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();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. |
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();Primary errors:
BotShieldError: The base class for HTTP error responses.ErrorResponse: Internal server error. Status code500. *InvalidInputError: Invalid input. Status code400. *
Less common errors (6)
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from BotShieldError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
* Check the method documentation to see if the error is applicable.
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 |
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();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();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 });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 });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.
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.