ClawShield Documentation

Secure your AI agent and publish it to production in minutes.

ClawShield is a security gateway that sits between your end users and your AI agent. Install the Python SDK, connect your agent, and ClawShield handles everything else — authentication, rate limiting, prompt injection detection, IP filtering, and full audit logging.

Your agent stays behind your firewall. ClawShield gives it a public endpoint with enterprise-grade security, no infrastructure work required.

How it works

Your agent connects outbound to ClawShield via WebSocket (like ngrok). End users hit your agent's public URL. ClawShield runs security checks, forwards the request to your agent, and returns the response. Your agent never needs a public IP.

Quickstart

Get your AI agent secured and published in 3 steps.

1

Create an agent in the Dashboard

Sign up at the ClawShield Dashboard, create an agent, and copy the API key. The key is shown only once.

2

Install the SDK

Install the ClawShield Python SDK in your agent project.

bash
pip install https://clawshield.tech/sdk/clawshield-0.2.0-py3-none-any.whl
3

Connect your agent

Wrap your agent logic in a handler function and connect to ClawShield.

python
import asyncio from clawshield import ClawShieldAgent async def handle_request(request): # Your agent logic here user_msg = request["messages"][-1]["content"] return {"response": f"You said: {user_msg}"} agent = ClawShieldAgent( api_key="csk_your_api_key_here", gateway_url="wss://clawshield.tech/ws", handler=handle_request, ) asyncio.run(agent.start())

That's it. Your agent is now published at its subdomain URL, secured by ClawShield. End users can call it via HTTP POST.

Installation

Requirements

Install via pip

bash
pip install https://clawshield.tech/sdk/clawshield-0.2.0-py3-none-any.whl

This installs the clawshield package with its dependencies (websockets and aiohttp).

Connect Your Agent

The ClawShieldAgent class connects your agent to the ClawShield gateway. It handles authentication, heartbeats, and auto-reconnection automatically.

python
from clawshield import ClawShieldAgent agent = ClawShieldAgent( api_key="csk_your_api_key", # From dashboard gateway_url="wss://clawshield.tech/ws", handler=my_handler, # Your async handler function auto_reconnect=True, # Auto-reconnect on disconnect max_reconnect_attempts=10, # Max retries before giving up heartbeat_interval=25.0, # Heartbeat frequency in seconds ) # Blocks until agent.stop() is called or max retries exceeded await agent.start()

On connect, the SDK authenticates with your API key, then listens for incoming user requests. When a request arrives, your handler is called. The return value is sent back to the end user via ClawShield.

Writing a Handler

The handler is an async function that receives a request dictionary and returns a response dictionary. This is where your agent logic lives — call an LLM, run tools, query a database, anything you need.

Request payload

Your handler receives a dictionary with these fields:

FieldTypeDescription
requestIdstrUnique request correlation ID
sourceIpstrEnd user's IP address
methodstrHTTP method (e.g. "POST")
pathstrRequest path
messageslistChat messages from the end user
metadatadictOptional metadata attached to the request

Response format

Return a dictionary. The entire return value is sent as the HTTP response body to the end user. You can return any JSON-serializable structure.

python
async def handle_request(request): messages = request["messages"] user_message = messages[-1]["content"] # Your logic here... result = await call_my_llm(user_message) # Return any JSON-serializable dict return { "response": result, "model": "my-agent-v1", }
Error handling

If your handler raises an exception, ClawShield returns a 500 to the end user with the error message. Make sure to handle errors gracefully inside your handler for a better user experience.

Full Example: OpenAI Agent

Here's a complete example of an agent that uses OpenAI's GPT to respond to user messages:

python — agent.py
import asyncio import os from openai import AsyncOpenAI from clawshield import ClawShieldAgent client = AsyncOpenAI(api_key=os.getenv("OPENAI_API_KEY")) async def handle_request(request): # Forward messages to OpenAI completion = await client.chat.completions.create( model="gpt-4o", messages=request["messages"], ) return { "response": completion.choices[0].message.content, "model": completion.model, "usage": { "prompt_tokens": completion.usage.prompt_tokens, "completion_tokens": completion.usage.completion_tokens, }, } agent = ClawShieldAgent( api_key=os.getenv("CLAWSHIELD_API_KEY"), gateway_url=os.getenv("CLAWSHIELD_GATEWAY_URL", "wss://clawshield.tech/ws"), handler=handle_request, ) asyncio.run(agent.start())
bash
# Set your keys and run export OPENAI_API_KEY="sk-..." export CLAWSHIELD_API_KEY="csk_..." python agent.py

Your agent is now live. End users can send messages through ClawShield and get GPT-4o responses, with all requests protected by your security policy.

Agent Lifecycle

  1. Connect — SDK opens a WebSocket to ClawShield and authenticates with your API key
  2. Listen — Agent waits for incoming user_request messages
  3. Handle — Each request is passed to your handler function
  4. Respond — Handler return value is sent back as user_response
  5. Heartbeat — SDK sends keepalive pings every 25 seconds automatically
  6. Reconnect — On disconnect, SDK reconnects with exponential backoff (2s, 4s, 8s... up to 30s)
Graceful shutdown

Call await agent.stop() to cleanly disconnect. This cancels heartbeats and closes the WebSocket connection.

Constructor Reference

python
ClawShieldAgent( api_key: str, handler: Callable[[dict], Awaitable[dict]], gateway_url: str = "wss://clawshield.tech/ws", auto_reconnect: bool = True, max_reconnect_attempts: int = 10, heartbeat_interval: float = 25.0, )
ParameterTypeDescription
api_keystrRequired. Your agent's API key from the dashboard (starts with csk_)
handlerasync callableRequired. Async function that takes a request dict and returns a response dict
gateway_urlstrWebSocket URL of your ClawShield gateway
auto_reconnectboolAutomatically reconnect on disconnection (default: True)
max_reconnect_attemptsintMaximum reconnection attempts before stopping (default: 10)
heartbeat_intervalfloatSeconds between heartbeat pings (default: 25.0)

Methods

await agent.start()

Connects to the gateway, authenticates, and starts listening for requests. Blocks until stop() is called or the maximum reconnection attempts are exceeded.

await agent.stop()

Gracefully stops the agent. Cancels heartbeats, closes the WebSocket connection, and unblocks start().

Properties

PropertyTypeDescription
agent.agent_idOptional[str]Agent ID assigned by the gateway after authentication. None before connecting.
agent.is_connectedboolWhether the agent is currently connected and authenticated.
agent.request_countintTotal number of requests handled since connecting.

Exceptions

All exceptions inherit from ClawShieldError.

ExceptionWhen
ClawShieldErrorBase exception for all SDK errors
AuthenticationErrorAPI key is invalid, expired, or authentication timed out
ConnectionErrorCannot connect to the ClawShield gateway
SecurityBlockedErrorRequest blocked by security policy (has a .code attribute)
RateLimitErrorRate limit exceeded (subclass of SecurityBlockedError, .code = "RATE_LIMITED")
python
from clawshield import ClawShieldAgent from clawshield.exceptions import AuthenticationError, ConnectionError try: await agent.start() except AuthenticationError: print("Invalid API key. Check your dashboard.") except ConnectionError: print("Cannot reach the gateway. Check your gateway_url.")

Calling Your Agent

Once your agent is connected, end users can reach it through the ClawShield gateway via HTTP POST:

bash — curl
curl -X POST http://your-clawshield-instance/v1/agents/your-subdomain/chat \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "Hello, agent!"} ] }'
python — requests
import requests response = requests.post( "http://your-clawshield-instance/v1/agents/your-subdomain/chat", json={ "messages": [ {"role": "user", "content": "Hello, agent!"} ] }, ) print(response.json())
javascript — fetch
const response = await fetch( "http://your-clawshield-instance/v1/agents/your-subdomain/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: [{ role: "user", content: "Hello, agent!" }], }), } ); const data = await response.json();

The your-subdomain is assigned when you create an agent in the dashboard. You can find it on the agent detail page.

Response Format

The HTTP response body is exactly what your handler returns. ClawShield does not modify or wrap it — it's forwarded as-is.

StatusMeaning
200Agent handled the request successfully
403Request blocked by security policy (IP filter, prompt injection)
429Rate limit exceeded
500Agent handler threw an exception
502Agent is not connected
504Agent didn't respond within 120 seconds

Security Policies

Configure security policies per agent in the dashboard. Every request passes through the security engine before reaching your agent.

IP Filtering

Whitelist or blacklist IP addresses and CIDR ranges. Requests from blocked IPs get a 403 before reaching your agent.

Rate Limiting

Set requests-per-minute limits per source IP. Uses a sliding window algorithm. Excess requests get a 429 response.

Prompt Injection Detection

Built-in scanner checks incoming messages for 12 common prompt injection patterns — "ignore previous instructions", DAN-style jailbreaks, system prompt overrides, and more. Matches are blocked with a 403.

Request Logging

Every request is logged with full security evaluation results. Optionally log request/response bodies for audit. Configure per-agent in the dashboard.

How It Works

Here's what happens when an end user sends a request to your agent:

flow
End User → POST /v1/agents/:subdomain/chat ClawShield → Lookup agent by subdomain ClawShield → Verify agent is connected ClawShield → Security Engine ├― IP Filter (whitelist/blacklist) ├― Rate Limiter (sliding window per IP) └― Prompt Scanner (12 injection patterns) ClawShield → user_request (→ your agent over WebSocket) Your Agent → Handler runs (call LLM, tools, etc.) Your Agent → user_response (→ ClawShield over WebSocket) ClawShield → HTTP 200 (→ end user) ClawShield → Request logged to audit trail
Timeout

ClawShield waits up to 120 seconds for your agent to respond. If your handler takes longer, the end user gets a 504 Gateway Timeout.

Ready to secure your agent?

Create an account and connect your first agent in under 5 minutes.

Open Dashboard →