imrobot
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
๐ค imrobot
Reverse-CAPTCHA for AI agents โ verify bots, not humans.
Live Demo ยท npm ยท Dev.to Article
Why?
Traditional CAPTCHAs prove you're human. But what about the opposite?
As AI agents become first-class web citizens โ browsing, booking, purchasing, automating โ some systems need to verify their visitors are legitimate AI agents, not humans trying to bypass agent-only access. Think agent-facing APIs, AI-only platforms, or multi-agent authentication.
imrobot flips the CAPTCHA model: it generates deterministic challenge pipelines that are trivial for any LLM or programmatic agent to solve (< 1 second), but impractical for humans to work through manually.
Related MCP server: mechanical-turk
How it works
imrobot generates a pipeline of deterministic operations (string transforms, byte operations, hashing, and more) applied to a random seed. AI agents parse the structured challenge data, execute the pipeline, and submit the result. Humans would need to manually compute multi-step transformations โ practically impossible without tools.
seed: "a7f3b2c1d4e5f609"
1. reverse()
2. caesar(7)
3. xor_encode(42)
4. fnv1a_hash()
5. to_upper()The challenge data is embedded in the DOM via data-imrobot-challenge attribute as structured JSON, making it trivially parseable by any agent.
Install
npm install imrobot # JS/TS SDK (Node, Bun, Deno, Cloudflare Workers, browsers)
pip install imrobot # Python SDK โ LangChain / CrewAI / AutoGPT / FastAPI
pip install "imrobot[fastapi]" # + FastAPI middlewareQuick start
React
import { ImRobot } from 'imrobot/react'
function App() {
return (
<ImRobot
difficulty="medium"
theme="light"
onVerified={(token) => {
console.log('Robot verified!', token)
}}
/>
)
}Vue
<script setup>
import { ImRobot } from 'imrobot/vue'
function handleVerified(token) {
console.log('Robot verified!', token)
}
</script>
<template>
<ImRobot difficulty="medium" theme="light" @verified="handleVerified" />
</template>Svelte
Needs Svelte 5 or later (the component uses runes).
<script>
import ImRobot from 'imrobot/svelte'
</script>
<ImRobot
difficulty="medium"
theme="light"
onVerified={(token) => console.log('Robot verified!', token)}
/>Web Component (Angular, vanilla JS, anything)
<script type="module">
import { register } from 'imrobot/web-component'
register() // registers <imrobot-widget>
</script>
<imrobot-widget difficulty="medium" theme="light"></imrobot-widget>
<script>
document.querySelector('imrobot-widget').addEventListener('imrobot-verified', (e) => {
console.log('Robot verified!', e.detail)
})
</script>The widget renders inside an open shadow root, so document.querySelector('[data-imrobot-challenge]') does not see it. Agents reach it through the element: document.querySelector('imrobot-widget').shadowRoot.querySelector('[data-imrobot-challenge]') (see How agents interact with it).
Core API (headless)
import { generateChallenge, solveChallenge, verifyAnswer } from 'imrobot/core'
const challenge = generateChallenge({ difficulty: 'medium' })
const answer = solveChallenge(challenge)
const isValid = verifyAnswer(challenge, answer) // trueServer SDK (HMAC-signed verification)
For production use, the server SDK provides tamper-proof, stateless challenge verification using HMAC-SHA256. No database required โ the cryptographic signature ensures integrity.
import { createVerifier } from 'imrobot/server'
const verifier = createVerifier({
secret: process.env.IMROBOT_SECRET!, // min 16 chars
difficulty: 'medium',
})
// API route: generate a signed challenge
app.get('/api/challenge', async (req, res) => {
const challenge = await verifier.generate()
res.json(challenge) // includes HMAC signature
})
// API route: verify agent's answer (stateless)
app.post('/api/verify', async (req, res) => {
const { challenge, answer } = req.body
const result = await verifier.verify(challenge, answer)
// result: { valid: true, elapsed: 42, suspicious: false }
// or: { valid: false, reason: 'wrong_answer' | 'expired' | 'invalid_hmac' | 'tampered' | 'replay' }
res.json(result)
})The server verifier checks in order: HMAC signature validity (challenge and pipeline not tampered), expiration (challenge not expired), answer correctness (pipeline re-executed), and replay detection (duplicate challenge IDs are rejected when a replay guard is configured). A different secret on a different server will reject the challenge โ preventing cross-site replay attacks.
Middleware & Proof-of-Agent tokens
Protect your API endpoints with framework-agnostic middleware. Verified agents receive a JWT-like Proof-of-Agent token (HMAC-SHA256 signed) that they pass via X-Agent-Proof header on subsequent requests.
import { requireAgent, createAgentRouter } from 'imrobot/server'
// Mount challenge/verify endpoints with rate limiting
const router = createAgentRouter({
secret: process.env.IMROBOT_SECRET!,
rateLimit: { windowMs: 60_000, maxRequests: 30 },
})
app.get('/imrobot/challenge', router.challenge)
app.post('/imrobot/verify', router.verify)
// Protect routes โ only verified agents can access
const agentOnly = requireAgent({
secret: process.env.IMROBOT_SECRET!,
rateLimit: { windowMs: 60_000, maxRequests: 30 },
})
app.get('/api/data', agentOnly, (req, res) => {
res.json({ agent: req.agentProof })
})trustProxy option
Both requireAgent and createAgentRouter accept a trustProxy option that controls how client IPs are resolved for rate limiting. When running behind a reverse proxy (nginx, Cloudflare, etc.), set trustProxy: true to read the real client IP from X-Forwarded-For / X-Real-IP headers instead of req.ip.
import { requireAgent, createAgentRouter } from 'imrobot/server'
// Behind a trusted reverse proxy
const agentOnly = requireAgent({
secret: process.env.IMROBOT_SECRET!,
trustProxy: true, // reads X-Forwarded-For for accurate IP-based rate limiting
rateLimit: { windowMs: 60_000, maxRequests: 30 },
})
const router = createAgentRouter({
secret: process.env.IMROBOT_SECRET!,
trustProxy: true,
})Warning: Only enable
trustProxywhen your server is behind a trusted proxy. Enabling it on a public-facing server allows clients to spoof their IP and bypass rate limiting.
Combined handler
Alternatively, use the combined .handler property to route both GET and POST requests to a single path:
import { createAgentRouter } from 'imrobot/server'
const router = createAgentRouter({ secret: process.env.IMROBOT_SECRET! })
// Routes GET โ /challenge and POST โ /verify under one path
app.use('/imrobot', router.handler)The handler automatically routes based on HTTP method:
GET โ challenge endpoint (returns a signed challenge)
POST โ verify endpoint (verifies answer, returns proof token)
Other methods โ
next()when the framework passes one (so under Express an unmatchedPUTfalls through to your other routes, usually ending in 404); 405 Method Not Allowed when it is called withoutnext, e.g.server.on('request', (req, res) => router.handler(req, res))
Hono / Bun
For Hono (Bun, Cloudflare Workers, Deno, Node), use the dedicated imrobot/hono adapter โ it wraps the same verifier + JWT issuer as Express but exposes Hono-native handler shapes.
import { Hono } from "hono";
import { createHonoAgentRouter, requireAgentHono } from "imrobot/hono";
import type { AgentProofToken } from "imrobot/server";
// Declare the variable requireAgentHono sets, so c.get("agentProof") type-checks
const app = new Hono<{ Variables: { agentProof: AgentProofToken } }>();
const secret = process.env.IMROBOT_SECRET!;
// Mount /imrobot/challenge (GET) and /imrobot/verify (POST) in one call
createHonoAgentRouter({ secret }).mount(app, "/imrobot");
// Protect a route โ only agents with a valid X-Agent-Proof pass through
app.get("/api/agent-data", requireAgentHono({ secret }), (c) => {
const proof = c.get("agentProof");
return c.json({ secret: "only bots see this", agent: proof });
});Under the hood it uses the same ImRobotVerifier and ProofTokenIssuer โ so JWTs issued by the Hono router verify against the Express requireAgent, and vice-versa. Rotate secrets across both without breaking anything.
Next.js
The imrobot/next subpath ships two adapters โ one for the App Router (Edge or Node.js middleware) and one for the Pages Router (API routes). Both wrap the same ImRobotVerifier and ProofTokenIssuer as the Express and Hono adapters, so proof tokens are cross-verifiable across all four runtimes.
App Router โ middleware.ts at the repo root:
import { createNextMiddleware } from 'imrobot/next'
export const middleware = createNextMiddleware({
secret: process.env.IMROBOT_SECRET!,
protectedPaths: ['/api/agent'],
// Optional: rateLimit, difficulty, ttl, imrobotPath, proofHeaderName, tokenTTL
})
export const config = {
matcher: ['/api/agent/:path*', '/imrobot/:path*'],
}The middleware auto-mounts GET /imrobot/challenge and POST /imrobot/verify, then guards any path in protectedPaths by requiring a valid X-Agent-Proof header. Requests without a token get 401; invalid tokens get 403. The adapter intentionally avoids importing from next/server so the package remains installable in non-Next.js projects โ it accepts any object matching the NextRequest shape and returns a plain Response (or null to fall through).
Pages Router โ pages/api/imrobot.ts:
import { createNextApiHandler } from 'imrobot/next'
export default createNextApiHandler({
secret: process.env.IMROBOT_SECRET!,
difficulty: 'medium',
// Optional: issuer, tokenTTL, ttl
})A single handler routes both GET (challenge) and POST (verify) on the same route. Use requireAgent from imrobot/server in your other API routes to gate them behind the issued proof token โ the JWTs are the same format across both routers.
Rate limiting
Both createAgentRouter and requireAgent support built-in rate limiting to protect against brute-force attacks and request flooding. The rate limiter is in-memory with zero external dependencies.
import { createAgentRouter } from 'imrobot/server'
const router = createAgentRouter({
secret: process.env.IMROBOT_SECRET!,
rateLimit: {
windowMs: 60_000, // 1-minute sliding window
maxRequests: 30, // max 30 requests per window per IP
onLimitReached: (key) => console.warn(`Rate limited: ${key}`),
},
})When a client exceeds the limit, they receive a 429 Too Many Requests response with standard headers:
HTTP/1.1 429 Too Many Requests
X-RateLimit-Limit: 30
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1711540860
Retry-After: 45The RateLimiter class can also be used standalone:
import { RateLimiter } from 'imrobot/server'
const limiter = new RateLimiter({ windowMs: 60_000, maxRequests: 10 })
if (!limiter.isAllowed(clientIp)) {
// Handle rate limit exceeded
}
const status = limiter.getStatus(clientIp)
// { remaining: 7, resetAt: 1711540860000 }Option | Type | Default | Description |
|
|
| Sliding window duration in ms |
|
|
| Max requests per window per key |
|
| โ | Callback when a client exceeds the limit |
Expired entries are automatically cleaned up to prevent memory leaks in long-running servers.
Invisible verification (zero-UI)
For agents that need to verify themselves programmatically without any UI:
import { invisibleVerify } from 'imrobot/core'
const result = await invisibleVerify({
challengeUrl: 'https://api.example.com/imrobot/challenge',
verifyUrl: 'https://api.example.com/imrobot/verify',
agentId: 'my-bot-v1',
maxRetries: 3,
})
if (result.success) {
// Use result.proofToken in X-Agent-Proof header
fetch('/api/protected', {
headers: { 'X-Agent-Proof': result.proofToken! },
})
}CLI
Built-in CLI for testing, benchmarking, and inspecting challenges:
npx imrobot challenge --difficulty hard
npx imrobot solve --difficulty medium
npx imrobot benchmark --count 1000
npx imrobot info
# Probe any URL to check if it accepts AI agents via imrobot
npx imrobot test-agent https://example.com
npx imrobot test-agent example.com --json # machine-readable output
# Run the MCP server over stdio (tools for Claude Code, Claude Desktop, Cursor, ...)
npx -y imrobot mcptest-agent looks for (in order of confidence):
<origin>/.well-known/imrobot.jsonโ the strongest signal (protocol declared)A
data-imrobot-challengeattribute in the HTML (embedded challenge)<script>tags referencingimrobot, or a<meta name="imrobot">tag
Exit codes: 0 = accepts agents (yes/likely), 1 = no signals found, 2 = network/usage error. Useful in CI scripts.
Agent discovery (.well-known/imrobot.json)
Inspired by the A2A Agent Card pattern, imrobot supports a discovery endpoint that lets AI agents automatically find and interact with your imrobot-protected service.
import { createDiscoveryHandler, createAgentRouter, requireAgent } from 'imrobot/server'
// Mount the discovery endpoint
const discovery = createDiscoveryHandler({
challengePath: '/imrobot',
name: 'My Agent API',
description: 'Agent-verified data service',
})
app.get('/.well-known/imrobot.json', discovery)
// Mount challenge/verify as usual
const router = createAgentRouter({ secret: process.env.IMROBOT_SECRET! })
app.get('/imrobot/challenge', router.challenge)
app.post('/imrobot/verify', router.verify)Agents fetch /.well-known/imrobot.json and receive a structured document describing the protocol, endpoint paths, supported difficulty levels, and step-by-step instructions for completing verification:
{
"protocol": "imrobot",
"version": "1.0",
"endpoints": {
"challenge": "/imrobot/challenge",
"verify": "/imrobot/verify",
"proofHeader": "X-Agent-Proof"
},
"difficulties": ["easy", "medium", "hard"],
"instructions": "1. GET the challenge endpoint..."
}For framework-agnostic usage (Hono, Koa, Fastify, etc.), use buildDiscoveryDocument() directly:
import { buildDiscoveryDocument } from 'imrobot/server'
const doc = buildDiscoveryDocument({ challengePath: '/imrobot' })
// Serve `doc` as JSON at /.well-known/imrobot.jsonWeb Bot Auth: signed agents skip the challenge
imrobot verifies Web Bot Auth signatures (draft-ietf-webbotauth-httpsig-protocol-01, on RFC 9421 HTTP Message Signatures). An agent that signs its requests with an Ed25519 key published in a key directory is recognised cryptographically, so the challenge is skipped for it. Everything else is challenged as before.
What the verifier checks:
Signature-Agentnames the agent's key directory. It must be covered by the signature and use https.createdandexpiresare required.keyidmust be the key's RFC 7638 thumbprint,tagmust beweb-bot-auth, and@authoritymust be covered.A
noncethat was already seen is refused (in-memory store by default; plug in a shared one across workers).Key directories are fetched without following redirects, with a 5 s timeout and a 64 kB size cap. They are cached for the server's
Cache-Controlmax-age, clamped to 60 s .. 24 h. A failed refetch keeps the cached keys.The RFC 9421 test keys are refused by default.
Choose which agents you trust. An allow-list is the safe default:
import { requireAgent } from 'imrobot/server'
app.use('/api/agent', requireAgent({
secret: process.env.IMROBOT_SECRET!,
webBotAuth: {
trustedSignatureAgents: ['https://agent.example'],
authorities: ['api.your-site.example'], // your own host(s): stops cross-site replay
},
}))
// req.webBotAuth -> { verified: true, keyid, agent, ... } for a signed agentSet authorities. Without it, a signature an agent made for another site can be replayed to
you with a spoofed Host header, and the adapters log a warning. A signature over @authority
alone still replays to any path on your host until it is 5 minutes old (maxAgeSeconds) or its
nonce is seen. requireComponents: ['@method', '@path'] binds it to one request, and
requireNonce: true makes it single-use.
The same option exists on requireAgentHono (c.get('webBotAuth')) and on createNextMiddleware
(for protectedPaths). A refused request gets a 401 with an Accept-Signature header describing the
signature we expect.
Other key sources:
directoryUrl: pin one directory.allowAnySignatureAgent: true: accept any public https agent. Private and loopback hosts are refused. This is risky on a server that can reach internal services: a public name that RESOLVES to a private address is not detected (DNS is not resolved). Prefer an allow-list there, or an egress firewall. At most 2 directories are fetched per request.
accept(result) can still veto a verified agent.
Signing as an agent (imrobot/agent):
import { generateAgentKey, createSignedFetch, createKeyDirectoryHandler } from 'imrobot/agent'
const key = await generateAgentKey() // store key.privateJwk as a secret
// Publish your directory at https://agent.example/.well-known/http-message-signatures-directory
export const GET = createKeyDirectoryHandler({ privateJwks: [key.privateJwk] })
const signedFetch = createSignedFetch({
privateJwk: key.privateJwk,
signatureAgent: 'https://agent.example',
})
await signedFetch('https://site.example/api/agent/data')Python has the same pieces: imrobot.web_bot_auth.WebBotAuthVerifier,
imrobot.fastapi.require_agent(..., web_bot_auth=verifier) and imrobot.agent.sign_request.
Install them with pip install "imrobot[wba]".
Screenshot protection
The challenge text is blurred by default and only revealed when the user hovers over it. This defeats screenshot-based attacks (screen capture tools, CDP screenshots, PrintScreen) since the captured image shows only blurred content.
An additional JavaScript shield detects screenshot shortcuts (PrintScreen, Cmd+Shift+3/4/5, Ctrl+Shift+S) and window blur/visibility changes, applying an extra blur layer that overrides even the hover state.
Combined with the hidden nonce (not displayed visually) and TTL expiry, this makes screenshot+OCR workflows ineffective โ even if the blur were bypassed, the nonce is missing from the visual output.
Note: AI agents are unaffected โ they read challenge data from the DOM, not from the screen.
Using the shield in vanilla JS
The screenshot shield is exported for use outside the bundled components:
import { setupScreenshotShield } from 'imrobot'
const cleanup = setupScreenshotShield((shielded) => {
// shielded: true when a screenshot attempt is detected
// automatically resets to false after 1.2s
})
// Call cleanup() to remove event listenersHow agents interact with it
AI agents read the challenge data directly from the DOM via the data-imrobot-challenge attribute โ they never need to "see" the visual text, so blur has no effect on them.
Read the challenge from
data-imrobot-challengeattribute (JSON)Execute the pipeline โ each operation is a deterministic transform
Submit the answer via the input field or programmatically
// Agent reads challenge from DOM (unaffected by blur). For the Web Component
// the widget lives in its open shadow root:
// document.querySelector('imrobot-widget').shadowRoot.querySelector('[data-imrobot-challenge]')
const el = document.querySelector('[data-imrobot-challenge]')
const challenge = JSON.parse(el.dataset.imrobotChallenge)
// Agent solves it (or implement the pipeline yourself)
import { solveChallenge } from 'imrobot/core'
const answer = solveChallenge(challenge)
// Agent fills in the answer and clicks verify
const input = el.querySelector('input')
input.value = answer
input.dispatchEvent(new Event('input', { bubbles: true }))
el.querySelector('button').click()Natural-language challenge formatting
By default, challenges display operations in programmatic syntax (reverse(), caesar(7)). For deployments where you want to make regex-based scraping of the display text harder, use the natural-language formatting functions:
import { formatOperationNL, formatPipelineNL } from 'imrobot/core'
const challenge = generateChallenge({ difficulty: 'hard' })
// Each call produces randomised phrasing:
console.log(formatPipelineNL(challenge.visibleSeed, challenge.pipeline))
// "Begin with the text: "a7f3..."
// Step 1: Flip the string backwards
// Then 2: Shift every letter 7 positions in the alphabet
// Next 3: Bitwise-XOR every character with the value 42
// ..."Every operation has 3โ4 distinct phrasings that are randomly selected on each call, so the display text varies unpredictably. Agents must parse the JSON pipeline (unaffected), while regex scraping of the visual text becomes unreliable.
Tip: The original programmatic functions
formatOperation/formatPipelineremain unchanged โ use them when you need a stable, deterministic format.
Operations reference
String operations
Operation | Description | Example |
| Reverse the string |
|
| Convert to uppercase |
|
| Convert to lowercase |
|
| Base64 encode |
|
| ROT13 cipher |
|
| Hex encode each char |
|
| Sort characters |
|
| Sum of char codes |
|
| Extract substring |
|
| Repeat string n times |
|
| Replace all occurrences |
|
| Pad start to length |
|
| Count vowels |
|
| Extract consonants only |
|
| Run-length encode |
|
| Atbash cipher (aโz) |
|
Byte & cipher operations
Operation | Description | Example |
| Caesar cipher with configurable shift |
|
| XOR each byte with key |
|
| Count occurrences of a char |
|
| Keep every other character |
|
| FNV-1a hash of the string |
|
| String length as string |
|
| Deprecated name: cascaded FNV-1a, NOT SHA-256 (256-bit output) | deterministic 64-char hex |
| Real SHA-256 of the UTF-8 bytes (opt-in, |
|
| XOR each byte with key array | byte-level encryption |
| Iterated FNV-1a hash | cascaded hashing |
| Swap high/low nibbles per byte |
|
| Rotate bits left within byte | bitwise rotation |
Configuration
Prop | Type | Default | Description |
|
|
| Number and complexity of operations |
|
|
| Color theme |
|
|
| Widget size โ |
|
| per-difficulty | Challenge time-to-live in ms (easy: 30s, medium: 20s, hard: 15s) |
|
| โ | Callback on successful verification |
|
| โ | Callback on failed verification |
Difficulty levels
easy: 2-3 simple operations (reverse, case, sort, length, slice_alternate, vowel_count, atbash)
medium: 3-5 operations including encoding, extraction, caesar, char counting, consonant_extract, run_length_encode
hard: 5-7 operations including XOR encoding, hashing, replacement, padding, cascaded FNV-1a (256-bit), byte XOR, hash chains, nibble swap, and bit rotate
Server verification
For production deployments, use the server SDK (imrobot/server) instead of client-side-only verification. The server SDK uses HMAC-SHA256 to sign challenges, providing tamper-proof, stateless, replay-resistant verification with zero database overhead.
import { createVerifier } from 'imrobot/server'
const verifier = createVerifier({
secret: process.env.IMROBOT_SECRET!, // HMAC secret (min 16 chars)
difficulty: 'hard',
ttl: 10_000, // optional: override default TTL
})
// Generate โ send to client โ client solves โ verify answer
const challenge = await verifier.generate()
const result = await verifier.verify(challenge, agentAnswer)Replay protection
To prevent the same challenge from being verified more than once, pass a ChallengeReplayGuard instance to createVerifier():
import { createVerifier, ChallengeReplayGuard } from 'imrobot/server'
const replayGuard = new ChallengeReplayGuard({
maxAge: 5 * 60 * 1000, // track IDs for 5 minutes
cleanupInterval: 60_000, // purge expired entries every minute
})
const verifier = createVerifier({
secret: process.env.IMROBOT_SECRET!,
difficulty: 'medium',
replayGuard, // enables replay detection
})
// First verify() succeeds; second verify() with the same challenge
// returns { valid: false, reason: 'replay' }The replay guard is in-memory with automatic expiry cleanup and unref()'d timers, so it won't keep the process alive. Call replayGuard.destroy() on shutdown to clear the cleanup interval.
Timing gate and real SHA-256 (0.9)
const verifier = createVerifier({
secret: process.env.IMROBOT_SECRET!,
minSolveMs: 50, // answers faster than this: { valid: false, reason: 'too_fast' }
maxSolveMs: 8_000, // slower than this: { valid: false, reason: 'too_slow' }
sha256: true, // put one real SHA-256 step in every pipeline
})The solve time is measured on the server clock, from the issue time that the HMAC signs, so a client cannot back-date it. Both bounds are off by default (minSolveMs: 0, no maxSolveMs). maxSolveMs is a tighter window than the TTL: a person copying the challenge into a script and pasting the answer back usually takes longer than a bot does. It does not stop someone who automates that whole round trip. docs/THREAT_MODEL.md says plainly what these checks do and do not prove.
sha256: true adds an operation that an LLM cannot do without a code tool, so it shuts out agents that only reason in text. Solvers older than 0.9 do not know the sha256 op, so turn it on once your agents run imrobot 0.9 or later. With several instances, keep minSolveMs well above the clock skew between them (it is measured across two clocks).
Python has the same options: create_verifier(secret, min_solve_ms=50, max_solve_ms=8000, sha256=True).
ChallengeAnalytics
ChallengeAnalytics (exported from imrobot/server) is a lightweight, in-memory metrics tracker for monitoring challenge activity โ generation rates, verification rates, solve-time percentiles, and failure-reason distributions. Zero external dependencies, memory-bounded (sliding window of configurable size).
import { ChallengeAnalytics } from 'imrobot/server'
const analytics = new ChallengeAnalytics({
maxSamples: 1000, // solve-time samples kept per difficulty (default: 1000)
trackFailureReasons: true, // track per-reason failure counts (default: true)
})
// Record events as they happen
analytics.recordGenerated('medium')
analytics.recordVerified('medium', 142, false) // 142ms, not suspicious
analytics.recordFailed('hard', 'wrong_answer')
// Get a full snapshot
const stats = analytics.getStats()
console.log(stats.summary.verificationRate) // 0.5 (50%)
console.log(stats.byDifficulty.medium.avgSolveTimeMs) // 142
console.log(stats.byDifficulty.hard.failureReasons) // { wrong_answer: 1 }
// Export for dashboards / structured logging
console.log(JSON.stringify(analytics.toJSON(), null, 2))
// Periodic rotation โ reset all counters
analytics.reset()getStats() returns an AnalyticsSnapshot with:
summaryโ aggregate totals:totalGenerated,totalVerified,totalFailed,totalExpired,totalSuspicious,verificationRate,avgSolveTimeMs,uptimeMsbyDifficultyโ per-difficultyDifficultyStatswith min/max/p95 solve times and per-reason failure countscollectedAtโ Unix timestamp of the snapshot
VerifyResult
The verify() method returns a VerifyResult:
interface VerifyResult {
valid: boolean
reason?:
| 'expired'
| 'invalid_hmac'
| 'wrong_answer'
| 'tampered'
| 'replay'
| 'too_fast' // solved faster than minSolveMs
| 'too_slow' // solved slower than maxSolveMs
elapsed?: number // ms since challenge was created
suspicious?: boolean // true if response was unusually slow
}Token
On successful verification, onVerified receives an ImRobotToken:
interface ImRobotToken {
challengeId: string // Unique challenge identifier
answer: string // The correct answer
timestamp: number // Verification timestamp
elapsed: number // Time taken to solve (ms)
suspicious: boolean // true if elapsed > 5s (possible human relay)
signature: string // Verification signature
}Adaptive difficulty
The adaptive difficulty engine auto-adjusts challenge difficulty per agent based on behavioral patterns โ inspired by Arkose Labs (FunCaptcha) progressive difficulty and reCAPTCHA v3 risk scoring.
import { AdaptiveDifficulty } from 'imrobot/core'
const adaptive = new AdaptiveDifficulty({
initialDifficulty: 'medium',
escalateAfterFailures: 2, // escalate after 2 consecutive failures
relaxAfterSuccesses: 5, // relax after 5 consecutive successes
})
// Record outcomes as agents solve challenges
adaptive.recordAttempt('agent_123', { success: true, solveTimeMs: 42 })
// Get recommended difficulty for next challenge
const diff = adaptive.getDifficulty('agent_123') // 'medium' | 'easy' | 'hard'
// Get risk assessment (0-1 score with breakdown)
const risk = adaptive.getRiskAssessment('agent_123')
// { score: 0.15, level: 'low', factors: { failureRate, abnormalTiming, rapidAttempts, inconsistentTiming } }
// Get just the numeric score (shorthand)
const score = adaptive.getRiskScore('agent_123') // 0.15The risk score weighs four factors: failure rate (35%), abnormal timing (25%), rapid-fire attempts (25%), and inconsistent solve times (15%). Risk levels: low | medium | high | critical.
AI image challenges (experimental)
Foundation for AI-generated image verification challenges. Pre-generate pools of images with known ground truth, then serve them as additional challenge layers.
import { ImageChallengePool } from 'imrobot/core'
// Option 1: Static provider (pre-generated images, no API needed)
const pool = new ImageChallengePool({
provider: {
type: 'static',
images: [
{ imageUrl: '/img/kitchen-3-apples.png', type: 'object_count', question: 'How many red apples?', answer: '3' },
{ imageUrl: '/img/park-bench.png', type: 'spatial_reasoning', question: 'What is to the left of the bench?', answer: 'tree' },
],
},
})
// Option 2: Custom provider (bring your own AI image generator)
const pool2 = new ImageChallengePool({
provider: {
type: 'custom',
generate: async (prompt) => {
const result = await myImageGenerator(prompt)
return { imageUrl: result.url }
},
},
poolSize: 100,
challengeTypes: ['object_count', 'spatial_reasoning', 'color_identification'],
rotationIntervalMs: 3_600_000, // rotate pool every hour
})
await pool.initialize()
const challenge = pool.getChallenge()
const isCorrect = pool.verifyAnswer(challenge.id, userAnswer)Six challenge types are supported: object_count, spatial_reasoning, color_identification, scene_description, text_recognition, and odd_one_out. Each type includes built-in prompt templates that generate prompts with known ground truth.
Warning: The
openaiandstabilityproviders are not yet implemented and will throw at runtime. Usecustomorstaticproviders instead. (Direct integration with these SaaS APIs is planned for a future release.)
OpenTelemetry metrics
ChallengeOTelExporter (exported from imrobot/server) bridges the in-memory ChallengeAnalytics tracker to any OpenTelemetry-compatible backend โ Datadog, Grafana, Prometheus, or any OTLP endpoint.
Install the optional peer dependencies:
npm install @opentelemetry/api @opentelemetry/sdk-metrics @opentelemetry/exporter-metrics-otlp-httpimport { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
import { ChallengeAnalytics, ChallengeOTelExporter, createVerifier } from 'imrobot/server'
const analytics = new ChallengeAnalytics()
const meterProvider = new MeterProvider({
readers: [
new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter({ url: 'http://localhost:4318/v1/metrics' }),
exportIntervalMillis: 30_000,
}),
],
})
const otelExporter = new ChallengeOTelExporter(analytics, meterProvider, {
scopeName: 'imrobot',
exportIntervalMs: 15_000,
})
otelExporter.start()
// Wire analytics into your verifier
const verifier = createVerifier({ secret: process.env.IMROBOT_SECRET!, analytics })
// On shutdown
process.on('SIGTERM', () => otelExporter.stop())Exported metrics
Metric | Type | Attributes | Description |
| Counter |
| Challenges generated |
| Counter |
| Successfully verified challenges |
| Counter |
| Failed verification attempts |
| Histogram |
| P95 solve time in ms |
| ObservableGauge | โ | Generated minus verified/failed |
| ObservableGauge | โ | Verified / total attempts (0.0โ1.0) |
@opentelemetry/api is an optional peer dependency โ the exporter uses the interface types only and does not hard-import the SDK.
Agent frameworks (Claude Agent SDK, LangChain, CrewAI)
The agent side in one call: give it a site, get a proof token back. It reads the site's
/.well-known/imrobot.json (or uses the default /imrobot/challenge mount), solves the challenge in
code and posts the answer.
import { passGate } from 'imrobot/agent'
const { proofToken, proofHeader } = await passGate('https://site.example', { agentId: 'my-agent' })
await fetch('https://site.example/api/data', { headers: { [proofHeader]: proofToken } })from imrobot.gate import pass_gate # standard library only
gate = pass_gate("https://site.example", agent_id="my-agent")
httpx.get("https://site.example/api/data", headers={gate.proof_header: gate.proof_token})The same thing as model tools, imrobot_pass_gate(url) and imrobot_solve_challenge(challenge).
They return JSON strings and never throw, so a model can read what went wrong:
Framework | Use | Example |
Claude Agent SDK |
| |
Claude Code, Claude Desktop, Cursor (any MCP client) |
| |
LangChain / LangGraph (Python) |
| |
CrewAI |
| |
Anything else (Vercel AI SDK, LangChain.js, OpenAI tools, ...) |
| - |
Defaults that matter when a model picks the URL:
Private, loopback and link-local hosts are refused (an LLM can be talked into calling internal services).
allowPrivateHosts/allow_private_hosts=True/--allow-private-hostslifts that for local development.Only http(s). Endpoints from the discovery document must be paths on the same origin. Redirects are not followed.
Each request times out after 10 s (headers and body) and a response is capped at 256 kB.
The challenge comes from the site, so it is solved under
SOLVE_LIMITS(at most 32 operations, 256 k characters per value, 10 000hash_chainrounds). A hostile pipeline is refused withunsupported_challengeinstead of hanging the agent.Host names are not resolved: a public name that points (or rebinds) to a private address gets through. In production, run agents behind an egress filter or an allow-list of sites.
Errors carry a stable code:
invalid_url,private_host,network,timeout,bad_response,unsupported_challenge,rejected(with the server'sreason).
To also send Web Bot Auth signatures, pass a signed fetch: passGate(url, { fetch: createSignedFetch(...) }).
A custom fetch must honour redirect: 'manual' (not follow redirects), or the same-origin checks no
longer hold.
Try it locally: npx tsx examples/demo-site.ts, then
npx tsx examples/pass-gate.ts http://127.0.0.1:8787 --allow-private-hosts.
MCP server (Model Context Protocol)
imrobot ships a native MCP server that lets AI agents auto-discover and complete verification challenges without any custom integration code. Agents call the tools directly; no HTTP endpoints required.
import { createMCPServer } from 'imrobot/mcp'
// Start a stdio MCP server (use in Claude Desktop, Cursor, etc.)
createMCPServer({ defaultDifficulty: 'medium' }).start()Or run it from the CLI, no code: npx -y imrobot mcp. Claude Code:
claude mcp add imrobot -- npx -y imrobot mcpClaude Desktop, Cursor and other MCP clients (claude_desktop_config.json and similar):
{
"mcpServers": {
"imrobot": {
"command": "npx",
"args": ["-y", "imrobot", "mcp"]
}
}
}pass-gate refuses private, loopback and link-local hosts. For a site on your own machine, add
--allow-private-hosts to the args.
Available MCP tools
Tool | Description |
| Generate a new verification challenge |
| Auto-solve a challenge (returns answer + proof token) |
| Check if a computed answer is correct |
| Create a proof token after solving |
| Fetch the imrobot discovery document |
| Pass a real site's gate: discover its endpoints, solve, return the proof token ( |
Programmatic usage (no stdio)
import { createMCPServer } from 'imrobot/mcp'
const server = createMCPServer()
// Generate + auto-solve in one step
const challengeResp = await server.handleMessage(JSON.stringify({
jsonrpc: '2.0', id: 1, method: 'tools/call',
params: { name: 'generate-challenge', arguments: { difficulty: 'easy' } }
}))
const { result } = JSON.parse(challengeResp)
const { challenge } = JSON.parse(result.content[0].text)
const solveResp = await server.handleMessage(JSON.stringify({
jsonrpc: '2.0', id: 2, method: 'tools/call',
params: { name: 'solve-challenge', arguments: { challenge } }
}))
const { result: solveResult } = JSON.parse(solveResp)
const { answer, token } = JSON.parse(solveResult.content[0].text)
// `token` is a client-side solve receipt, NOT an X-Agent-Proof value: a server
// guarded by requireAgent rejects it (403). To call a protected API, solve the
// server's own signed challenge and trade it for a proof token:
// const signed = await (await fetch('https://site/imrobot/challenge')).json()
// ...solve-challenge with { challenge: signed } -> answer
// const { proofToken } = await (await fetch('https://site/imrobot/verify', {
// method: 'POST', headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ challenge: signed, answer }),
// })).json()
// fetch('https://site/api/agent', { headers: { 'X-Agent-Proof': proofToken } })The MCP server has zero runtime dependencies โ it implements JSON-RPC 2.0 directly and calls the same core API that agents use.
Python SDK (pip install imrobot)
A companion Python package lives in ./python/ โ designed for LangChain / CrewAI / AutoGPT / any Python-based AI agent on the client side, and FastAPI / Starlette on the server side. Byte-identical wire format with the JS SDK, so a Python client can solve JS-issued challenges (and vice-versa) without any glue code.
Agent-side (client)
import httpx
from imrobot import solve_challenge
challenge = httpx.get("https://example.com/imrobot/challenge").json()
answer = solve_challenge(challenge)
proof = httpx.post(
"https://example.com/imrobot/verify",
json={"challenge": challenge, "answer": answer},
).json()["proofToken"]
# Use the proof on protected routes
httpx.get(
"https://example.com/api/agent-data",
headers={"X-Agent-Proof": proof},
)Server-side (FastAPI)
from fastapi import Depends, FastAPI
from imrobot.fastapi import create_imrobot_router, require_agent
app = FastAPI()
secret = os.environ["IMROBOT_SECRET"]
app.include_router(create_imrobot_router(secret=secret), prefix="/imrobot")
@app.get("/api/agent-data", dependencies=[Depends(require_agent(secret=secret))])
async def agent_only():
return {"secret": "only bots see this"}Highlights:
Zero deps for
solve_challenge,ImRobotVerifier,ProofTokenIssuer. FastAPI is an optional[fastapi]extra.Cross-runtime interop โ
test_interop.pypins JS reference outputs (FNV-1a, HMAC-SHA256, base64url) so any drift breaks CI.RFC 7519 JWTs (HS256) โ proof tokens verify with
PyJWT,python-jose, or any RFC-compliant library. (Tokens issued by 0.9.0 and earlier carried a non-standard signature segment; imrobot itself still verifies them, third-party JWT libraries do not.)Python 3.9 โ 3.13 supported.
PyPI auto-publish on
py-v*tags via.github/workflows/publish-python.yml(OIDC trusted publishing, no long-lived tokens).
Full API reference and development instructions: ./python/README.md.
Ecosystem
imrobot is designed to integrate with the broader AI agent ecosystem:
Integration | Description |
Cloudflare Turnstile | Layer human-verification alongside the proof-of-work challenge. |
Web Bot Auth (IETF) | Verify Ed25519-signed agents (OpenAI Operator, Cloudflare signed bots) directly. Skip the challenge for trusted known agents. |
Picsum | Free, no-auth placeholder photos for lighter-weight image challenges. Set |
A2A Agent Card |
|
Any JWT library | Proof tokens are standard HS256 JWTs โ verify with |
Blog posts & articles
Why I built a CAPTCHA that only bots can solve โ Dev.to article introducing imrobot: the motivation, design decisions, and how it works under the hood
FAQ โ How does imrobot compare to Turnstile / ALTCHA / reCAPTCHA?
imrobot solves the opposite problem from traditional CAPTCHA systems.
imrobot | Cloudflare Turnstile | ALTCHA | reCAPTCHA / hCaptcha | Friendly Captcha | |
Goal | Verify the visitor is a bot / AI agent | Verify the visitor is human | Verify the visitor is human | Verify the visitor is human | Verify the visitor is human |
Who should pass? | AI agents, bots, automated scripts | Humans only | Humans only | Humans only | Humans only |
Who should fail? | Humans (hard to solve manually) | Bots | Bots | Bots | Bots |
Challenge type | Deterministic pipeline (string transforms, hashing) | Browser fingerprint + JS proof-of-work | Server-side SHA-256 PoW | Image/audio recognition | SHA-256 PoW |
AI-solvable? | Yes, by design (< 1 second for any LLM) | Not applicable | Yes, unintentionally | Yes (AI vision can solve) | Yes, unintentionally |
Use case | Agent-only APIs, multi-agent auth, AI platforms | Public web forms | Public web forms | Public web forms | Public web forms |
Privacy | Zero tracking, no fingerprinting | Privacy-preserving | Open-source, self-hosted | Google/third-party tracking | No tracking |
Self-hosted | Yes (zero dependencies) | No (Cloudflare CDN) | Yes | No | Yes |
Open source | Yes (MIT) | No | Yes (MIT) | No | Yes |
When to use imrobot
Use imrobot when you want to grant access to AI agents and deny access to humans:
Agent-only data APIs (price feeds, knowledge graphs, structured data exports)
Multi-agent authentication (prove your caller is a legitimate AI client)
AI platform gating (only LLM-powered clients may access a route)
Testing / CI pipelines that simulate agent access
When to use Turnstile / reCAPTCHA / ALTCHA
Use those when you want the opposite: protect your service from bots and allow only human users.
Can I use both? Yes โ some services authenticate agents via imrobot and gate human-facing forms with Turnstile on the same backend.
FAQ โ How does imrobot compare to BOTCHA, Turingate, HATCHA and Web Bot Auth?
These are the other ways to let agents in, not humans. Each column comes from that project's own
README or npm page, checked 2026-11-24: BOTCHA (@dupecom/botcha
0.24.0), Turingate (turingate 0.3.0),
HATCHA and
Web Bot Auth (IETF draft
-01). "Not documented" means the README says nothing, not that the feature is missing.
imrobot | BOTCHA | Turingate | HATCHA | Web Bot Auth | |
What it is | Library: you run the challenge and verify on your own server | Hosted API (botcha.ai); the service code is MIT and runs locally on the Workers runtime | Hosted service generates the challenges; agent tools, widget and verifiers are MIT | Library: React component + server package | IETF draft: agents sign their HTTP requests, sites verify the signature |
Needs a third-party service | No | Yes for the hosted API (tokens verified via its JWKS) | Yes (free plan: 50 passes a month) | No | No (Cloudflare and others verify it at the edge) |
Proof | Randomised pipeline of string, byte and hash operations; optional real SHA-256 step and solve-time window | Default "hybrid": 5 SHA-256 hashes in 500 ms plus 3 reasoning questions | 20 tasks in 60 s, at least 17 right, some hidden in images | One of five puzzle kinds, 30 s | Ed25519 signature (RFC 9421) with a published key directory; no puzzle |
Token after success | HS256 JWT you issue and verify yourself | JWT access token (1 h) + refresh token, revocation | Pass bound to the agent's Ed25519 key, about 10 min, one site | Opaque HMAC-signed token | None: every request is signed |
Who is behind the agent | Not covered (agent id claim only); pair with Web Bot Auth for identity | Agent registry, reputation scores, Visa TAP | Owner identity, signed delegation limits, trust tiers, shared reputation | Not documented | The key directory of the agent's operator |
Payments | No | x402: pay $0.001 USDC instead of solving | x402 paywall for verified agents | Not documented | No (payment protocols build on it) |
Agent side |
| SDK that solves and refreshes tokens; docs MCP at botcha.ai/mcp | CLI + | Not documented | Signing libraries ( |
Languages | npm + PyPI ( | npm + PyPI ( | npm; Python and Go verifiers | npm (JS only) | Many implementations |
License | MIT | MIT | MIT (client side); hosted service closed | MIT | Open standard |
Where imrobot stands. It is the option with no service to sign up for. The whole flow runs in your process, on npm and PyPI, with React, Vue and Svelte components, a Web Component, and adapters for Express, Next.js, Hono and FastAPI. It also speaks Web Bot Auth both ways: signed agents skip the challenge, and agents can sign their own requests.
Where it is behind. BOTCHA and Turingate run hosted reputation and identity networks and take x402 payments; imrobot does neither. Its challenge only proves that the caller ran code. A person who runs the open-source solver passes, the same as with every other puzzle here. The timing gate narrows that gap but does not close it; docs/THREAT_MODEL.md spells out what it does and does not prove. When you need to know who is behind an agent, verify Web Bot Auth signatures.
FAQ โ How does imrobot compare to HATCHA (monday.com)?
HATCHA is monday.com's open-source reverse CAPTCHA ("CAPTCHA proves you're human. HATCHA proves you're not."). It is the closest direct competitor to imrobot. The row for HATCHA comes from its public README (checked 2026-11-24); where that README says nothing, the cell says so.
imrobot | HATCHA | |
License / hosting | MIT, self-hosted | MIT, self-hosted (npm packages, no hosted service required) |
Packages |
|
|
Server verification | HMAC-SHA256 signed, stateless | HMAC signed, stateless (no database) |
Challenge type | Randomised pipeline of 25+ string, byte and hash operations (optional real SHA-256 step) | Five built-in kinds (big multiplication, string reverse, character count, sort, binary to ASCII); custom kinds can be registered |
Time limit | Per-difficulty TTL plus an optional solve-time window ( | 30 s |
Frontends | React, Vue, Svelte, Web Component, headless core | React component |
Server adapters | Express, Next.js, Hono, FastAPI | Next.js App Router, Express |
Token after success | Standard JWT (RFC 7519, HS256) | Opaque HMAC-signed token (format not specified for downstream use) |
Replay protection |
| Not documented |
Web Bot Auth (signed agents skip the challenge) | Yes, verifier + signing client | Not documented |
CLI / MCP |
| Not documented |
Key difference: both are free and self-hosted. HATCHA is a small, focused React + server pair with five built-in puzzle kinds. imrobot covers more stacks (Python, Vue, Svelte, Hono, FastAPI), randomises the pipeline per challenge, and adds JWTs, replay stores, Web Bot Auth and a timing gate. Neither one can stop a human who runs an open-source solver; see docs/THREAT_MODEL.md.
Contributing
Contributions are welcome! Feel free to open issues for bug reports or feature requests, or submit pull requests.
git clone https://github.com/leopechnicki/im_robot.git
cd im_robot
npm install
npm testLicense
MIT
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
This server cannot be deployed
Maintenance
Related MCP Connectors
Reverse CAPTCHA for AI agents: prove you're an agent and get a verified, scoped, signed pass.
MCP server teaching AI agents to implement TideCloak: auth, E2EE, IGA, security analysis
Reverse CAPTCHA: prove a language model is on the other end and get a signed attestation.
AI memory governance & hallucination-blocking MCP server with verifiable knowledge cells.
Related MCP Servers
- AlicenseBqualityDmaintenanceA zero-cost MCP server that forces AI to self-correct code using prompt injection and context isolation.411MIT
- AlicenseNot gradedqualityCmaintenanceAn MCP server that inverts AI-human interaction: AI agents can ask humans questions via a browser console, blocking until answered.MIT
- AlicenseNot gradedqualityDmaintenanceAutomated red-teaming and reliability-auditing for AI agents, exposed as an MCP server. It attacks and scores agents for prompt injection, tool misuse, exfiltration, and unreliable behavior.2MIT
- AlicenseNot gradedqualityCmaintenanceA sandbox-first MCP server that enables AI agents to safely perform reverse-engineering tasks in fully isolated Docker containers, featuring zero-trust security, declarative YAML-based skills, and white-hat ethical safeguards.MIT