# For AI Agents Source: https://docs.tracectrl.ai/agents Copy-paste instructions to give any AI assistant full context on TraceCtrl. # For AI Agents Paste one of these blocks into your AI assistant — Claude Code, Cursor, Copilot, or OpenClaw — to give it full context about TraceCtrl. *** ## Setup & Operations Assistant Use this when you want an AI agent to help you install, run scans, fix findings, or debug TraceCtrl. ``` You are helping the user operate TraceCtrl — a security observability platform for agentic AI built on OpenClaw. WHAT TRACECTRL DOES - Static scan: analyses an OpenClaw gateway config and reports misconfigurations (38 checks, 6 auto-fixable) - Runtime telemetry: receives OpenTelemetry spans from instrumented agents, stores in ClickHouse, surfaces in a React dashboard STACK FastAPI engine (port 8000) · ClickHouse (9000) · OTel Collector (4317 gRPC / 4318 HTTP) · React/Vite dashboard (3000) · Python CLI INSTALL python3 -m venv .venv && source .venv/bin/activate pip install tracectrl tracectrl-scanner # both on PyPI # Then clone the repo (only needed for docker-compose + OpenClaw plugin source): git clone https://github.com/tracectrl/tracectrl.git && cd tracectrl tracectrl setup # interactive wizard, starts Docker containers tracectrl doctor # verify all services are up tracectrl install-plugin --configure # install OpenClaw plugin (optional) KEY COMMANDS tracectrl setup # interactive TUI setup wizard tracectrl version # print SDK version tracectrl doctor # check service health + plugin install tracectrl scan /absolute/path/to/.openclaw/ # run security scan, auto-uploads to dashboard tracectrl fix /absolute/path/to/.openclaw/ --auto # apply safe auto-fixes tracectrl monitor # verify OpenClaw diagnostics-otel is configured tracectrl install-plugin [--configure] # install the OpenClaw TraceCtrl plugin FLAGS scan: --json output machine-readable JSON --profile L1|L2 scan profile (L1 = default, L2 = extended) --engine-url URL override engine URL (default auto-discovers http://localhost:8000) --no-upload skip uploading results to engine fix: --auto automatically apply all safe remediations --dry-run show fixes without applying --engine-url URL override engine URL for re-scan upload --no-upload skip uploading re-scan results install-plugin: --configure auto-update openclaw.json to enable the plugin --endpoint URL OTEL endpoint for the plugin (default: http://localhost:4318) CRITICAL PATH WARNING Never run tracectrl as sudo or via sudo su. When elevated, ~ resolves to /root/ not the user home — so ~/.openclaw silently becomes /root/.openclaw (doesn't exist). Always get the absolute path first: run `openclaw configure` as the normal user. The first line of output is the workspace path (e.g. /home/user/.openclaw). AUTO-FIXABLE CHECKS (6 of 38) OC-NET-001 gateway.bind set to "loopback" OC-ING-001 channel dmPolicy changed from "open" to "pairing" OC-TOOL-001 "bash" and "exec" removed from tools.allow OC-TOOL-002 "*" wildcard removed from tools.allow OC-PERS-001 cron.enabled set to false OC-LOG-002 logging.level set to "info" (was "debug") VALID OPENCLAW ENUM VALUES (important — raw IPs break OpenClaw's Zod validation) gateway.bind: "loopback" | "lan" | "tailnet" | "auto" | "custom" — NOT "127.0.0.1" logging.level: "trace" | "debug" | "info" | "warn" | "error" sandbox.mode: "off" | "non-main" | "all" channels.*.dmPolicy: "open" | "pairing" | "allowlist" ENABLE RUNTIME TELEMETRY (add to openclaw.json, then `openclaw gateway restart`) "plugins": { "allow": ["diagnostics-otel"] }, "diagnostics": { "enabled": true, "otel": { "enabled": true, "endpoint": "http://localhost:4318", "protocol": "http/protobuf", "serviceName": "openclaw-gateway", "traces": true, "metrics": false, "logs": false, "sampleRate": 1.0, "flushIntervalMs": 5000 } } DASHBOARD http://localhost:3000/agents agent inventory (default landing page) http://localhost:3000/sessions trace viewer http://localhost:3000/alerts runtime alerts + violations feed http://localhost:3000/guardrails guardrail policies (Protector Plus) http://localhost:3000/risk TAGAAI risk dashboard http://localhost:3000/attacks attack-graph paths http://localhost:3000/scan scan results + topology http://localhost:3000/settings workspace + project settings GUARDRAILS / PROTECTOR PLUS TraceCtrl ships runtime guardrails via `tracectrl.protector`: from tracectrl import check_input, check_output, guard, GuardrailVerdict - `check_input(text)` / `check_output(text)` return a `GuardrailVerdict` (allow / block / redact) for prompt-injection, PII, and policy violations. - `@guard` decorates an agent/tool callable to enforce policies automatically and emit a violation span to the engine. - Violations surface at /guardrails (policy view) and /alerts (live feed), and are queryable via the Engine API guardrails/violations endpoints. DOCKER SOCKET If `tracectrl setup` fails with "permission denied on docker socket": run `newgrp docker` or log out and back in (user needs to be in docker group). ``` *** ## Developer Assistant Use this when you want an AI agent to help you modify or extend the TraceCtrl codebase. ``` You are helping a developer work on the TraceCtrl codebase. Repo: https://github.com/tracectrl/tracectrl REPO LAYOUT engine/api/routes/ FastAPI route handlers (scan.py, sessions.py, topology.py, risk.py) engine/db/ ClickHouse queries (scan_results.py, sessions.py, client.py) scanner/src/tracectrl_scanner/benchmark/checks/ One file per check section (38 total) scanner/src/tracectrl_scanner/fix.py 6 auto-fix functions scanner/src/tracectrl_scanner/topology/builder.py Static topology from OpenClaw config sdk/tracectrl/src/tracectrl/cli.py All CLI commands sdk/tracectrl/src/tracectrl/instrumentors/ Framework instrumentors (strands, langchain, etc.) plugins/openclaw-tracectrl/src/ Node.js OpenClaw plugin (TypeScript) ui/src/pages/ React pages (Agents, Sessions, Alerts, Guardrails, Risk, Attacks, ScanReport, Settings) ui/src/components/ Shared components (ScanTopologyCanvas, TraceTreeView, ScanNodePanel) ui/src/api/ API clients (scan.ts, sessions.ts, config.ts) setup/tui.py Textual TUI setup wizard TECH STACK Backend: Python 3.12, FastAPI, ClickHouse (ReplacingMergeTree), Pydantic v2 Frontend: React 18, TypeScript, Vite, Cytoscape.js + dagre layout CLI: Typer, Rich, Textual (TUI) Plugin: Node.js 22, TypeScript, OpenTelemetry SDK ENGINE API BASE: http://localhost:8000 POST /api/v1/scans upload scan results GET /api/v1/scans/latest get most recent scan + topology GET /api/v1/scans/{id} get scan by ID GET /api/v1/sessions list sessions GET /api/v1/sessions/{id}/spans get spans for a trace GET /api/v1/health health check SCAN RESULT SHAPE { scan_id, scanned_at, openclaw_path, profile, check_id, section, title, severity ("CRITICAL"|"HIGH"|"MEDIUM"|"LOW"), passed (0|1), finding, remediation, config_path } DESIGN TOKENS (CSS variables) --risk-critical: #FF4D4D --risk-high: #FF6B35 --risk-medium: #FFBB00 --risk-low: #22C55E --dark-card: #161616 --dark-border: #222222 --dark-surface: #0A0A0A BRANCH: main (default working branch) KNOWN CONSTRAINTS - OpenClaw plugin cannot receive model.usage / message.processed events from external plugins due to module isolation (OpenClaw bug #45096). Use built-in diagnostics-otel plugin instead. - Fix functions must never create config sections that don't already exist (Zod strict validation). - gateway.bind only accepts enum values — never raw IPs. - Engine schema is created on startup via ensure_schema() in engine/db/client.py. ``` *** ## OpenClaw Agent Context Use this block in your OpenClaw agent's `SOUL.md` or system prompt to give it awareness of TraceCtrl. ``` You are an AI agent running inside OpenClaw, monitored by TraceCtrl. TraceCtrl is the security observability layer for this deployment. It: - Scans this gateway's configuration for security misconfigurations - Receives and analyses all spans you produce via OpenTelemetry - Surfaces findings and risk signals to the operator's dashboard What this means for your behaviour: - All tool calls, model requests, and session events are traced and stored - Security findings about this gateway's configuration are visible to the operator - Your actions are part of a broader security posture review If a user asks about TraceCtrl, security scans, or findings: be transparent and helpful. If asked to help run a scan: instruct the user to run `tracectrl scan ` in their terminal. If asked about a specific finding: refer to the check ID (e.g. OC-SEC-002) and the remediation in the scan report at http://localhost:3000/scan. ``` # Guardrails For Agent Source: https://docs.tracectrl.ai/api-reference/agent-guardrails GET http://localhost:8000/api/v1/agents/{agent_id}/guardrails Guardrails registered against a specific agent Convenience endpoint that returns the same shape as [`GET /guardrails?agent_id=...`](/api-reference/guardrails-list). ### Path Parameters The agent identifier. ### Response Array of `GuardrailRegistration` objects — see [List Guardrails](/api-reference/guardrails-list) for field documentation. # Agent Risk Scores Source: https://docs.tracectrl.ai/api-reference/agent-scores GET http://localhost:8000/api/v1/risk/agent-scores Per-agent risk scores Returns risk scores for all agents with detected vulnerabilities. ### Query Parameters Filter by service name ### Response Array of `AgentRisk` objects: Agent identifier Agent's highest risk score Critical, High, Medium, or Low Number of attack paths involving this agent Rule producing the highest score ISO-8601 timestamp of last computation # Get Agent Tools Source: https://docs.tracectrl.ai/api-reference/agent-tools GET http://localhost:8000/api/v1/agents/{agent_id}/tools Tools used by a specific agent Returns each tool an agent has invoked, with call/error counts and first/last seen timestamps. ### Path Parameters The unique agent identifier. ### Response Array of `AgentTool` objects: Tool name Tool category (e.g., `memory_read`, `http`, `code_exec`) Total invocations Number of erroring invocations ISO-8601 timestamp ISO-8601 timestamp # List Agents (Inventory) Source: https://docs.tracectrl.ai/api-reference/agents GET http://localhost:8000/api/v1/agents Full agent inventory with tool counts and prompt metadata Returns every agent in the inventory as an `AgentSummary`. Compared to [`/risk/agents`](/api-reference/risk-agents), this endpoint also exposes `tool_call_counts`, `total_tool_calls`, and the raw `system_prompt`. ### Query Parameters Filter agents by service name. ### Response Array of agent objects: Unique identifier Human-readable name Detected framework Agent role/purpose LLM model in use Tool names invoked by this agent Map of `tool_name` to invocation count Sum of all tool calls System prompt text (may be empty) SHA-256 hash of the system prompt (first 16 hex chars) Number of distinct runs Total spans observed `LEARNING` or `MATURE` ISO-8601 timestamp ISO-8601 timestamp # Attack Graph Overlay Source: https://docs.tracectrl.ai/api-reference/attack-graph-overlay GET http://localhost:8000/api/v1/attack-graph/overlay Compromised nodes and attack edges overlayed on the topology Builds the overlay data consumed by the dashboard's **Attack Surface** topology mode: every node and edge that participates in at least one attack path, tagged with the highest severity seen. ### Response Array of compromised agent nodes (tool and ingress nodes are excluded): Agent ID Highest severity across paths involving this node Highest risk score across paths involving this node Deduplicated edges that appear in at least one attack path: Source node ID Target node ID Always `attack_path` Highest severity along this edge # Attack Graph Paths Source: https://docs.tracectrl.ai/api-reference/attack-graph-paths GET http://localhost:8000/api/v1/attack-graph/paths Detailed attack paths for the findings panel Returns detailed attack-path rows from the `attack_paths` table, ordered by `risk_score` descending. Unlike [`/risk/attack-paths`](/api-reference/attack-paths), this endpoint exposes the raw node/edge lists and the rule metadata used to render the findings panel. ### Response Array of path objects: Unique path identifier Rule identifier `Critical`, `High`, `Medium`, or `Low` OWASP ASI tag Rule title Description / explanation Primary agent involved Node IDs along the path (agents, `tool:*`, `ingress:*`) Topology edge IDs traversed by the path Computed risk score ISO-8601 timestamp, or `null` # Attack Paths Source: https://docs.tracectrl.ai/api-reference/attack-paths GET http://localhost:8000/api/v1/risk/attack-paths Ranked attack paths from TAGAAI rules Returns all detected attack paths ordered by risk score descending. ### Query Parameters Filter by service name ### Response Array of attack path objects: Unique path identifier TAGAAI rule that fired (e.g., `vulnerableToExcessiveAgency`) OWASP ASI category tag (e.g., `ASI01`) Agent IDs in the attack chain Step-by-step attack chain. Each step has: Node identifier Type of node (agent, tool, ingress) Vulnerability label Human-readable description Computed risk score Critical, High, Medium, or Low ISO-8601 timestamp when this path was detected # Guardrail Invocations Source: https://docs.tracectrl.ai/api-reference/guardrail-invocations GET http://localhost:8000/api/v1/guardrails/invocations Recent guardrail evaluation spans Recent `tracectrl.guardrail.evaluation` spans for a specific `(agent_id, guardrail_name)` pair, ordered newest first. Reads directly from `otel_traces` and does not depend on the analytics pipeline tick. ### Query Parameters The agent that owns the guardrail. The guardrail to query. Maximum rows to return. Returns `400` if `agent_id` or `guardrail_name` is missing. ### Response Array of `GuardrailInvocation` objects: Trace ID of the evaluation span Span ID of the evaluation span ISO-8601 timestamp `pass`, `fail`, or `error` `pre_input` or `post_output` Judge's reasoning Evidence captured at evaluation time Severity level `judge_llm` or `protector_plus` Model used for the decision Structured response payload (Protector Plus only; empty for legacy judge\_llm spans) # List Guardrails Source: https://docs.tracectrl.ai/api-reference/guardrails-list GET http://localhost:8000/api/v1/guardrails Registered guardrails across the system Returns every guardrail in the registry. Optionally filter to a single agent. ### Query Parameters Filter to guardrails registered for a specific agent. ### Response Array of `GuardrailRegistration` objects: Agent the guardrail is attached to Guardrail identifier `low`, `medium`, `high`, or `critical` `monitoring` or `blocking` `pre_input` or `post_output` Model used for evaluation Human-readable description Custom judge prompt (may be empty) `active`, `error`, or `disabled` Explanation when health is not active ISO-8601 timestamp ISO-8601 timestamp Invocations in the last 24h `judge_llm` or `protector_plus` # Health Check Source: https://docs.tracectrl.ai/api-reference/health GET http://localhost:8000/api/v1/health Check if the engine is running Returns the engine status and version. ```json 200 theme={"dark"} { "status": "ok", "version": "0.1.0" } ``` # API Overview Source: https://docs.tracectrl.ai/api-reference/overview TraceCtrl Engine REST API reference ## Base URL All endpoints are prefixed with `/api/v1`. ``` http://localhost:8000/api/v1 ``` ## Authentication The Engine API currently does not require authentication. In production deployments, secure the API behind a reverse proxy or API gateway. ## Endpoints ### System | Method | Endpoint | Description | | ------ | -------------------------------------- | --------------------------------------------- | | `GET` | [`/health`](/api-reference/health) | Health check | | `GET` | [`/projects`](/api-reference/projects) | List all service names (for project selector) | ### Topology | Method | Endpoint | Description | | ------ | -------------------------------------------------------------- | ------------------------------------------ | | `GET` | [`/topology/graph`](/api-reference/topology-graph) | Full topology graph (supports `?service=`) | | `GET` | [`/topology/agents/{agent_id}`](/api-reference/topology-agent) | Single agent detail | ### Agents | Method | Endpoint | Description | | ------ | ------------------------------------------------------------------ | -------------------------------------- | | `GET` | [`/agents`](/api-reference/agents) | Agent inventory (supports `?service=`) | | `GET` | [`/agents/{agent_id}/tools`](/api-reference/agent-tools) | Tools used by an agent | | `GET` | [`/agents/{agent_id}/guardrails`](/api-reference/agent-guardrails) | Guardrails for an agent | ### Sessions | Method | Endpoint | Description | | ------ | ---------------------------------------------------------------- | -------------------------------------- | | `GET` | [`/sessions`](/api-reference/sessions) | Session list (supports `?service=`) | | `GET` | [`/sessions/latest-spans`](/api-reference/sessions-latest-spans) | Spans from the most recent trace | | `GET` | [`/sessions/{trace_id}/spans`](/api-reference/sessions-spans) | Spans for a trace (supports `?extra=`) | ### Guardrails | Method | Endpoint | Description | | ------ | --------------------------------------------------------------------- | ------------------------------------------ | | `GET` | [`/guardrails`](/api-reference/guardrails-list) | Guardrail registry (supports `?agent_id=`) | | `GET` | [`/guardrails/invocations`](/api-reference/guardrail-invocations) | Recent evaluation spans | | `GET` | [`/guardrails/protector-config`](/api-reference/protector-config) | Protector Plus config (redacted) | | `PUT` | [`/guardrails/protector-config`](/api-reference/protector-config) | Upsert Protector Plus config | | `POST` | [`/guardrails/protector-test`](/api-reference/protector-config) | Health-check the Protector Plus endpoint | | `GET` | [`/guardrails/protector-config/sdk`](/api-reference/protector-config) | Full config for the SDK | ### Violations | Method | Endpoint | Description | | ------ | -------------------------------------------------------- | ------------------------------------------------- | | `GET` | [`/violations`](/api-reference/violations) | List violations (`limit`, `agent_id`, `severity`) | | `GET` | [`/violations/recent`](/api-reference/violations-recent) | Recent violations (`limit`) | | `GET` | [`/violations/stream`](/api-reference/violations-stream) | SSE stream of new violations | ### Scans | Method | Endpoint | Description | | ------ | ---------------------------------------------------------- | ----------------------------------- | | `POST` | [`/scans`](/api-reference/scans-upload) | Upload scan results from a CLI | | `GET` | [`/scans`](/api-reference/scans-list) | List all stored scans | | `GET` | [`/scans/latest`](/api-reference/scans-latest) | Latest scan with drift detection | | `GET` | [`/scans/{scan_id}`](/api-reference/scans-detail) | Results for a specific scan | | `POST` | [`/scan/validate-path`](/api-reference/scan-validate-path) | Validate an OpenClaw workspace path | | `POST` | [`/scan/trigger`](/api-reference/scan-trigger) | Trigger an engine-side scan | | `GET` | [`/scan/status/{scan_id}`](/api-reference/scan-status) | Poll a triggered scan | | `POST` | [`/scan/fix`](/api-reference/scan-fix) | Apply automated remediations | ### Risk | Method | Endpoint | Description | | ------ | --------------------------------------------------- | ------------------------------------- | | `GET` | [`/risk/agents`](/api-reference/risk-agents) | All agents with inventory data | | `GET` | [`/risk/summary`](/api-reference/risk-summary) | System-wide risk summary | | `GET` | [`/risk/attack-paths`](/api-reference/attack-paths) | Ranked attack paths from TAGAAI rules | | `GET` | [`/risk/agent-scores`](/api-reference/agent-scores) | Per-agent risk scores | ### Attack Graph | Method | Endpoint | Description | | ------ | -------------------------------------------------------------- | ------------------------------------------- | | `GET` | [`/attack-graph/paths`](/api-reference/attack-graph-paths) | Detailed paths for the findings panel | | `GET` | [`/attack-graph/overlay`](/api-reference/attack-graph-overlay) | Compromised nodes and edges for the overlay | ## Response Format All endpoints return JSON. Errors return: ```json theme={"dark"} { "detail": "Error description" } ``` with the appropriate HTTP status code (400, 404, 409, 500, or 503 where applicable). # List Projects Source: https://docs.tracectrl.ai/api-reference/projects GET http://localhost:8000/api/v1/projects Returns distinct service names seen in trace data Returns an array of distinct `ServiceName` values from the `otel_traces` table, sorted alphabetically. Used by the project / service selector in the dashboard. ### Response A JSON array of strings. ```json 200 theme={"dark"} ["billing-agent", "researcher", "support-bot"] ``` # Protector Plus Config Source: https://docs.tracectrl.ai/api-reference/protector-config Read, update, and test the TraceCtrl Guards (Protector Plus) configuration These endpoints manage the global TraceCtrl Guards configuration used to call the Protector Plus service. ## Get config (redacted) ```http theme={"dark"} GET http://localhost:8000/api/v1/guardrails/protector-config ``` Returns the stored config with `api_key` redacted (e.g. `hOjm***vY2`) so it can be safely surfaced in the Settings UI. If no config is set, returns an empty object with empty strings and an empty `enabled_guardrails` array. ### Response — `ProtectorConfig` Protector Plus endpoint URL Redacted API key (first 4 chars + `***` + last 3) List of enabled Protector Plus guardrails ISO-8601 timestamp, or `null` if never set ## Upsert config ```http theme={"dark"} PUT http://localhost:8000/api/v1/guardrails/protector-config ``` Upserts the global config. The full `api_key` must be provided in the body. The response is returned in **redacted** form so the UI does not see its freshly-sent key echoed back. ### Request body — `ProtectorConfigUpsert` Protector Plus base URL (`http` or `https`). Trailing slash is stripped before storage. Full API key. List of guardrail names. Each must be a known Protector Plus guardrail. ### Errors * `400` — `endpoint_url is required` * `400` — `api_key is required` * `400` — URL fails SSRF validation (private/loopback/reserved IP, bad scheme, DNS failure) * `400` — `unknown guardrails: [...]` if a name is not in `PROTECTOR_GUARDRAILS` ### Response Same `ProtectorConfig` shape as the GET above (redacted). ## Test config ```http theme={"dark"} POST http://localhost:8000/api/v1/guardrails/protector-test ``` Server-side health check against the stored endpoint. Issues a GET to `{endpoint_url}/api/protectorplus/v1/health` with a 5s timeout. Rejects non-public targets so the test cannot be turned into an SSRF probe. ### Response — `ProtectorTestResult` `true` if the upstream returned a 2xx Round-trip time in milliseconds HTTP status code from the upstream, or `null` Error description when `ok` is false, otherwise `null` ## SDK config fetch ```http theme={"dark"} GET http://localhost:8000/api/v1/guardrails/protector-config/sdk ``` Returns the **unredacted** config for the SDK. Called once per agent process during `with tracectrl.guardrails():` setup. There is **no authentication** in v1 — the deployment is expected to bind the port to loopback or front it with an authenticated proxy. Returns an empty config (rather than 404) if none is set so the SDK can no-op cleanly. ### Response — `ProtectorConfigUpsert` Protector Plus endpoint URL Full API key Enabled guardrails # List Agents Source: https://docs.tracectrl.ai/api-reference/risk-agents GET http://localhost:8000/api/v1/risk/agents Returns all discovered agents with inventory data Returns every agent in the inventory with their observation counts, tools, maturity status, and framework detection. ### Response Array of agent objects with the same fields as the [Get Agent Detail](/api-reference/topology-agent) endpoint. ```json 200 theme={"dark"} [ { "agent_id": "researcher-agent", "name": "Researcher", "framework": "langchain", "role": "Research and analysis", "model": "gpt-4o", "tools_observed": ["search_documents", "fetch_url"], "system_prompt_hash": "a1b2c3d4e5f67890", "run_count": 15, "observation_count": 234, "maturity": "MATURE", "first_seen": "2026-03-15T10:30:00Z", "last_seen": "2026-03-17T14:22:00Z" } ] ``` # Risk Summary Source: https://docs.tracectrl.ai/api-reference/risk-summary GET http://localhost:8000/api/v1/risk/summary System-wide risk summary Returns the overall system risk score, severity, and aggregate counts. Returns `null` if no risk computation has run yet. System-wide risk score (0-10) Critical, High, Medium, or Low Number of Critical/High severity paths Number of agents with detected vulnerabilities Agents with \< 10 observations Last computation timestamp (ISO-8601) # Apply Scan Fixes Source: https://docs.tracectrl.ai/api-reference/scan-fix POST http://localhost:8000/api/v1/scan/fix Apply automated remediations to openclaw.json Runs the scanner's automated-fix functions against `openclaw.json` in the given workspace. A `.json.bak` backup is written before any change. The config file is rewritten only if at least one fix applied successfully. ### Request body — `ScanFixPayload` Path to the OpenClaw workspace (must contain `openclaw.json`). List of check IDs to attempt to fix. ### Errors * `400` — `openclaw.json not found at workspace path` * `400` — Failed to parse `openclaw.json` * `503` — Scanner not installed (`pip install tracectrl-scanner`) ### Response Check IDs whose fix ran successfully Check IDs with no registered automated fix Map of `check_id` to error message for fixes that raised # Scan Job Status Source: https://docs.tracectrl.ai/api-reference/scan-status GET http://localhost:8000/api/v1/scan/status/{scan_id} Poll for the status of a triggered scan Polls the in-memory job table populated by [`/scan/trigger`](/api-reference/scan-trigger). Job entries are pruned 30 minutes after they start; a poll on an expired job returns `404`. ### Path Parameters Job ID returned by `/scan/trigger`. ### Errors * `404` — Scan job not found (may have expired) ### Response Echo of the requested job ID `running`, `complete`, or `failed` ISO-8601 timestamp ISO-8601 timestamp once the job has finished, otherwise `null` Error message when `status` is `failed`, otherwise `null` ID of the persisted scan when complete — fetch results via [`/scans/{scan_id}`](/api-reference/scans-detail) # Trigger Scan Source: https://docs.tracectrl.ai/api-reference/scan-trigger POST http://localhost:8000/api/v1/scan/trigger Start a scan job and poll for completion Triggers a scan from the UI. The endpoint returns immediately; clients should poll [`/scan/status/{scan_id}`](/api-reference/scan-status) for completion. Only one scan can run at a time. A second concurrent trigger returns `409 A scan is already running`. Stale job records (>30 min old) are pruned on each trigger. ### Request body — `ScanTriggerPayload` Absolute path to the OpenClaw workspace (must contain `openclaw.json`). Benchmark profile. ### Errors * `400` — Path is not a valid OpenClaw workspace * `409` — A scan is already running ### Response Job ID for status polling (12-char hex) Always `running` on a successful trigger ISO-8601 timestamp # Validate Workspace Path Source: https://docs.tracectrl.ai/api-reference/scan-validate-path POST http://localhost:8000/api/v1/scan/validate-path Check whether a filesystem path is a valid OpenClaw workspace Used by the dashboard before kicking off a scan. The path is validated server-side because the dashboard runs in a browser that cannot inspect the engine host's filesystem. ### Request body — `ValidatePathPayload` Absolute filesystem path (whitespace is trimmed). ### Response `true` if the path exists and contains `openclaw.json` Whether `openclaw.json` was found Echo of the resolved path Reason for failure when `valid` is false (e.g. `Path does not exist`, `Not an OpenClaw workspace (no openclaw.json found)`) # Get Scan Source: https://docs.tracectrl.ai/api-reference/scans-detail GET http://localhost:8000/api/v1/scans/{scan_id} Results and topology for a specific scan ### Path Parameters Hex-encoded scan ID (1-12 chars, `[0-9a-f]`). Other inputs return `400 Invalid scan ID format`. ### Errors * `400` — Invalid scan ID format * `404` — Scan not found ### Response Echo of the requested ID Check rows stored for the scan Topology snapshot, or `null` # Latest Scan Source: https://docs.tracectrl.ai/api-reference/scans-latest GET http://localhost:8000/api/v1/scans/latest Most recent scan results with config drift detection Returns the most recent scan plus drift metadata that lets the dashboard warn when the `openclaw.json` on disk has changed since the scan ran. ### Response Identifier of the latest scan, or `null` if none Check rows for that scan Topology snapshot stored with the scan, or `null` `true` if the current `openclaw.json` hash differs from the hash recorded at scan time SHA-256\[:16] of `openclaw.json` when the scan ran SHA-256\[:16] of `openclaw.json` right now Whole days since the scan was recorded, or `null` if unknown When no scans have been recorded: ```json 200 theme={"dark"} { "scan_id": null, "results": [], "topology": null, "config_changed": false, "days_since_scan": null } ``` # List Scans Source: https://docs.tracectrl.ai/api-reference/scans-list GET http://localhost:8000/api/v1/scans All stored scans with summary counts Returns a list of stored scans with summary counts. Shape is whatever `engine.db.scan_results.list_scans()` returns — see the database layer for the exact columns. Typically includes `scan_id`, `scanned_at`, `profile`, `scan_path`, and aggregate counts per severity. # Upload Scan Results Source: https://docs.tracectrl.ai/api-reference/scans-upload POST http://localhost:8000/api/v1/scans Store scan results produced by a remote TraceCtrl CLI Receive scan results from a remote CLI run and store them. The CLI ships its own check list and (optionally) a derived topology snapshot for the workspace. ### Request body — `ScanUploadPayload` Workspace path the scan was run against. Benchmark profile. Array of check results. Each entry has: Defaults to empty string. Defaults to empty string. Defaults to empty string. Optional topology snapshot (`{nodes, edges}`) as produced by the scanner's topology builder. ### Response Identifier of the stored scan Number of check rows stored # List Sessions Source: https://docs.tracectrl.ai/api-reference/sessions GET http://localhost:8000/api/v1/sessions Returns recent traces grouped as sessions Returns the most recent 200 traces, each summarized with root span info, agent name, span count, duration, and error status. ### Query Parameters Filter sessions by service name. ### Response Array of session summary objects: OpenTelemetry trace ID ISO-8601 timestamp of first span ISO-8601 timestamp of last span end Wall-clock trace duration in nanoseconds Number of spans in this trace Name of the root span (entry point) Span ID of the root span Primary agent name (first agent seen in trace) `true` if any span in the trace has an error status ```json 200 theme={"dark"} [ { "trace_id": "abc123def456789012345678", "start_time": "2026-03-17T14:20:00Z", "end_time": "2026-03-17T14:20:03.5Z", "total_duration_ns": 3500000000, "span_count": 12, "root_span_name": "AgentExecutor", "root_span_id": "span123", "agent_name": "Researcher", "has_error": false } ] ``` # Latest Trace Spans Source: https://docs.tracectrl.ai/api-reference/sessions-latest-spans GET http://localhost:8000/api/v1/sessions/latest-spans Spans from the most recent trace Returns the spans belonging to the single most recent trace. Shape matches [Get Trace Spans](/api-reference/sessions-spans). ### Query Parameters Restrict the search to a specific service. ### Response Array of `SpanDetail` objects — see [Get Trace Spans](/api-reference/sessions-spans) for field documentation. # Get Trace Spans Source: https://docs.tracectrl.ai/api-reference/sessions-spans GET http://localhost:8000/api/v1/sessions/{trace_id}/spans Returns all spans for a specific trace Returns the flat list of spans for a trace, ordered by timestamp. The frontend builds the parent-child tree from `parent_span_id`. ### Path Parameters The OpenTelemetry trace ID. ### Query Parameters Comma-separated list of additional trace IDs to merge in (used for OpenClaw multi-trace sessions). All spans are returned sorted by `start_ns`. ### Response Array of span detail objects: Unique span identifier Parent span ID. Empty string for root spans. Operation name OTel span kind: `INTERNAL`, `SERVER`, `CLIENT`, etc. Service that emitted this span Start time as Unix nanoseconds Duration in nanoseconds `STATUS_CODE_OK`, `STATUS_CODE_ERROR`, or `STATUS_CODE_UNSET` Error message if status is ERROR Full `SpanAttributes` map — all `tracectrl.*`, `openinference.*`, `input.*`, `output.*` attributes Resource-level attributes (service name, SDK version, etc.) ```json 200 theme={"dark"} [ { "span_id": "abc123", "parent_span_id": "", "span_name": "AgentExecutor", "span_kind": "INTERNAL", "service_name": "my-agent-service", "start_ns": 1742222400000000000, "duration_ns": 3500000000, "status_code": "STATUS_CODE_OK", "status_message": "", "attributes": { "openinference.span.kind": "AGENT", "tracectrl.agent.id": "researcher-agent", "tracectrl.agent.name": "Researcher", "tracectrl.session_id": "a1b2c3d4-e5f6-7890", "tracectrl.tool.category": "", "input.value": "Summarize my latest emails" }, "resource_attributes": { "service.name": "my-agent-service" } } ] ``` # Get Agent Detail Source: https://docs.tracectrl.ai/api-reference/topology-agent GET http://localhost:8000/api/v1/topology/agents/{agent_id} Returns details for a specific agent ### Path Parameters The unique agent identifier (e.g., `researcher-agent`). ### Response Unique identifier Human-readable name Detected framework Agent role/purpose LLM model used List of tool names this agent has used SHA-256 hash of the system prompt (first 16 hex chars) Number of distinct runs Total spans observed `LEARNING` (\< 10 observations) or `MATURE` (>= 10) ISO-8601 timestamp ISO-8601 timestamp ```json 200 theme={"dark"} { "agent_id": "researcher-agent", "name": "Researcher", "framework": "langchain", "role": "Research and analysis", "model": "gpt-4o", "tools_observed": ["search_documents", "fetch_url", "write_file"], "system_prompt_hash": "a1b2c3d4e5f67890", "run_count": 15, "observation_count": 234, "maturity": "MATURE", "first_seen": "2026-03-15T10:30:00Z", "last_seen": "2026-03-17T14:22:00Z" } ``` # Get Topology Graph Source: https://docs.tracectrl.ai/api-reference/topology-graph GET http://localhost:8000/api/v1/topology/graph Returns the full agent-tool topology graph Returns all agent nodes, tool nodes, and their edges. Used by the dashboard's Topology page. ### Query Parameters Filter the graph to a single service name. ### Response Array of node objects. Unique node identifier `agent` or `tool` Display name For agents: `framework`, `role`, `model`, `tools_observed`, `maturity`. For tools: `category`. Array of edge objects. Edge identifier Source node ID Target node ID `agent_to_agent` or `agent_to_tool` For agent-to-agent: `function_call` or `team_member` Times this connection was observed For tool edges: total call count `LOW`, `MEDIUM`, or `HIGH` ```json 200 theme={"dark"} { "nodes": [ { "id": "researcher-agent", "type": "agent", "label": "Researcher", "metadata": { "framework": "langchain", "role": "Research and analysis", "model": "gpt-4o", "tools_observed": ["search_documents", "fetch_url"], "maturity": "MATURE" } }, { "id": "tool:search_documents", "type": "tool", "label": "search_documents", "metadata": { "category": "memory_read" } } ], "edges": [ { "id": "abc123", "source": "researcher-agent", "target": "tool:search_documents", "type": "agent_to_tool", "call_count": 42, "tool_category": "memory_read" } ] } ``` # List Violations Source: https://docs.tracectrl.ai/api-reference/violations GET http://localhost:8000/api/v1/violations Guardrail violations with optional filtering Returns guardrail violations ordered newest first. ### Query Parameters Maximum rows to return. Filter by agent. Filter by severity (`critical`, `high`, `medium`, `low`). ### Response Array of `Violation` objects: Unique violation identifier Trace that produced the violation Span being evaluated Span ID of the evaluation itself Agent that produced the offending output / received the offending input Guardrail that fired Model that produced the decision `pass`, `fail`, or `error` Judge's reasoning Evidence captured at evaluation time `critical`, `high`, `medium`, or `low` ISO-8601 timestamp `judge_llm` or `protector_plus` # Recent Violations Source: https://docs.tracectrl.ai/api-reference/violations-recent GET http://localhost:8000/api/v1/violations/recent Convenience endpoint for the most recent violations Returns the most recent violations. Equivalent to [`GET /violations`](/api-reference/violations) with no filter and a default `limit` of 20. ### Query Parameters Maximum rows to return. ### Response Array of `Violation` objects — see [List Violations](/api-reference/violations) for field documentation. # Stream Violations (SSE) Source: https://docs.tracectrl.ai/api-reference/violations-stream GET http://localhost:8000/api/v1/violations/stream Server-Sent Events stream of guardrail violations A **Server-Sent Events** (SSE) endpoint that pushes guardrail violations to a long-lived HTTP connection. Used by the dashboard's live violations feed. Response `Content-Type` is `text/event-stream`. Use the browser `EventSource` API (or any SSE-aware client) to consume it. ### Protocol On connect, the server emits: * `event: init` — `data` is a JSON array of the most recent 20 violations. Then every 2 seconds it polls for newly inserted rows and emits each one: * `event: violation` — `data` is a single violation JSON object. A `: heartbeat` comment is emitted every 15 seconds to keep the connection open through proxies. Each violation payload has the same fields as the [List Violations](/api-reference/violations) response. The init payload is read **before** the watermark, which means a row inserted between the two reads can appear both in `init` and in the first poll. Clients must de-duplicate on `violation_id`. ### Example ```js theme={"dark"} const es = new EventSource("http://localhost:8000/api/v1/violations/stream"); const seen = new Set(); es.addEventListener("init", (e) => { for (const v of JSON.parse(e.data)) { seen.add(v.violation_id); render(v); } }); es.addEventListener("violation", (e) => { const v = JSON.parse(e.data); if (!seen.has(v.violation_id)) { seen.add(v.violation_id); render(v); } }); ``` # Architecture Source: https://docs.tracectrl.ai/architecture How TraceCtrl's components fit together ## System Overview TraceCtrl has five layers: 1. **Python SDK** (in your agent) — emits OpenTelemetry spans enriched with `tracectrl.*` security attributes, plus optional in-process guardrails. 2. **Protector Plus** (optional external HTTP firewall) — called from `tracectrl.protector`, emits guardrail evaluation spans. 3. **OTel Collector** — receives OTLP spans and writes them to ClickHouse. 4. **Intelligence Engine** — FastAPI service that runs the pipeline and serves the REST API. 5. **Dashboard** — React SPA that visualizes agents, traces, alerts, guardrails, and attack paths. TraceCtrl architecture: a Python agent process runs the SDK (Framework Instrumentor + TraceCtrl SDK core + Guardrails), exports OTLP spans on :4317/:4318 to the OTel Collector. The Collector forwards to ClickHouse (:8123/:9000) which holds otel_traces, agent_inventory, topology edges, attack paths, guardrail registry + violations, scan results, and the protector_plus_config. The Intelligence Engine (FastAPI :8000) runs a 60-second pipeline that builds inventory + topology, ingests guardrail spans, and computes the attack graph; it serves /api/v1/* REST + SSE. The React Dashboard (:3000) renders Monitor (agents/sessions/topology), Security (alerts/guardrails/scan/risk/attacks), and Configure (settings). The Guardrails block also talks HTTP to an external Protector Plus firewall (optional); both SDK and Protector Plus violations flow to the same engine pipeline. ## Component Details ### Python SDK The SDK wraps [OpenInference](https://github.com/Arize-ai/openinference) framework instrumentors with a `TraceCtrlSpanProcessor` that enriches every span with security attributes. It uses OpenTelemetry as the transport — no custom protocols, no vendor lock-in. **Key modules:** * `tracectrl.config` — `configure()` sets up the TracerProvider with OTLP gRPC exporter. * `tracectrl.processor` — `TraceCtrlSpanProcessor` adds agent identity, tool categories, session IDs, ingress markers. * `tracectrl.inference` — Classifies tools into risk categories. * `tracectrl.session` — Session ID management via Python `contextvars`. * `tracectrl.context` — W3C traceparent propagation for cross-service agents. * `tracectrl.guardrails` — In-process LLM-judge guardrails. Emits `tracectrl.guardrail.registered` (on registration) and `tracectrl.guardrail.evaluation` (per evaluation) spans. * `tracectrl.protector` — TraceCtrl Guards integration with external Protector Plus HTTP firewall. Emits the same guardrail span types, tagged with `tracectrl.guardrail.provider = "protector_plus"`. ### Protector Plus (optional) An external HTTP firewall called from `tracectrl.protector`. Exposes seven sub-guardrails (`llm`, `keyword`, `regex`, `pii`, `vector`, `content_moderation`, `system_prompt_protection`) via `/apikey/api/protectorplus/v1/input-check` and `.../output-check`. The SDK calls it fire-and-forget; flagged sub-guardrails are emitted as `tracectrl.guardrail.evaluation` spans (`decision=fail`) for the engine to ingest. Config (endpoint URL, API key, enabled guardrails) is persisted in `protector_plus_config` and configured from the Settings page. ### OTel Collector A standard OpenTelemetry Collector configured to receive OTLP spans on gRPC (`:4317`) and HTTP (`:4318`), then export them to ClickHouse via the `clickhouseexporter`. Configuration lives in `config/otel-collector.yaml`. ### Intelligence Engine A FastAPI application that: 1. **Runs the pipeline** every `PIPELINE_INTERVAL_SECONDS` (default 60). Each tick re-reads all spans, refreshes the agent inventory, topology, guardrail registry, guardrail violations, and the attack-graph analysis. Idempotency comes from ClickHouse `ReplacingMergeTree` rather than a watermark. 2. **Serves a REST API** under `/api/v1` — system, topology, sessions, agents, risk, scan, violations, guardrails. 3. **Owns the ClickHouse schema** — `ensure_schema()` runs the CREATE/ALTER statements at startup. ### Dashboard A React + Vite + TypeScript SPA. The sidebar groups pages into three sections (**Monitor**, **Security**, **Configure**) and the route table lives in `ui/src/App.tsx:145-158`. See the [Dashboard page](/platform/dashboard) for the per-page reference. ## Data Pipeline (one tick) Read all spans from `otel_traces`. Upsert agents with cumulative observation/run counts and tool lists. Upsert agent-to-agent and agent-to-tool edges with confidence scoring. Ingest `tracectrl.guardrail.evaluation` spans with `decision in ('fail','error')` into `guardrail_violations`. Ingest `tracectrl.guardrail.registered` spans into `guardrail_registry`; flip health to `error` when the last hour shows error-decision violations. Evaluate TAGAAI rules, generate attack paths, score risk, write `attack_paths` / `agent_risk_scores` / `system_risk`. ## ClickHouse Tables | Table | Engine | Purpose | | ---------------------------------------------- | ------------------------------ | ---------------------------------------------------------- | | `otel_traces` | Auto-created by Collector | Raw OpenTelemetry spans | | `agent_inventory` | ReplacingMergeTree | Deduplicated agent records | | `topology_agent_edges` | ReplacingMergeTree | Agent-to-agent connections | | `topology_tool_edges` | ReplacingMergeTree | Agent-to-tool connections | | `pipeline_state` | ReplacingMergeTree | Pipeline state (legacy watermark key) | | `attack_paths` | ReplacingMergeTree | TAGAAI-detected attack paths | | `agent_risk_scores` | ReplacingMergeTree | Per-agent risk | | `system_risk` | ReplacingMergeTree | System-wide risk summary | | `scan_results` / `scan_topology` / `scan_runs` | MergeTree / ReplacingMergeTree | Static OpenClaw scan output | | `guardrail_violations` | ReplacingMergeTree | Guardrail evaluation failures (judge-LLM + Protector Plus) | | `guardrail_registry` | ReplacingMergeTree | Registered guardrails (per agent) | | `protector_plus_config` | ReplacingMergeTree | Single-row Protector Plus config | ReplacingMergeTree deduplicates rows during background merges. Always query with `FINAL` for correct results: `SELECT * FROM agent_inventory FINAL`. # TraceCtrl Bootcamp (Openclaw) Source: https://docs.tracectrl.ai/bootcamp/guide A hands-on workshop — from zero to full security observability for AI agents in 2 hours **Duration**: 1.5–2 hours | **Level**: Intermediate | **Format**: Hands-on lab Paste the TraceCtrl agent instructions into Claude Code, Cursor, or Copilot to get contextual help throughout this workshop. *** # Part 1: Introduction to TraceCtrl ## What is TraceCtrl? TraceCtrl is a **security observability platform for agentic AI**. Our tagline captures the workflow: 1. **See** — Visualize your agent's architecture, topology, and risk posture at a glance 2. **Trace** — Trace every message, tool call, and model request through the full execution lifecycle 3. **Ctrl** — Control and harden your agent's configuration with automated scanning and remediation ## Components TraceCtrl has five components: | Component | What it does | Technology | | ------------------ | --------------------------------------------------- | --------------------------- | | **CLI** | `tracectrl scan`, `fix`, `doctor`, `setup` | Python (pip installable) | | **Scanner** | 33 security/ops/perf/compliance checks for OpenClaw | Python | | **OTel Collector** | Receives spans from agents via OTLP | OpenTelemetry Collector | | **Engine** | Processes spans, builds topology, serves API | FastAPI + ClickHouse | | **Dashboard** | Visualizes scans, traces, topology | React + Vite + Cytoscape.js | ## Architecture
AGENT CODE
OTLP gRPC :4317
OPENCLAW
OTLP HTTP :4318
→
OTEL COLLECTOR
:4317 / :4318
→
CLICKHOUSE
native :9000
→
ENGINE API
:8000
→
DASHBOARD
:3000
tracectrl scan
POST findings → Engine
tracectrl fix
auto-remediates OpenClaw config
**How data flows:** 1. Your agent (or OpenClaw) exports OpenTelemetry spans to the **OTel Collector** 2. The Collector writes spans to **ClickHouse** (column-oriented database optimized for traces) 3. The **Engine** runs a pipeline every 60 seconds — reads new spans, builds agent inventory, discovers topology edges 4. The **Dashboard** queries the Engine API to render trace trees, topology graphs, and scan reports 5. The **CLI Scanner** analyzes OpenClaw config files and uploads findings to the Engine ## What the Scanner Checks 33 checks across four categories: | Category | Checks | Examples | | ------------------- | ------------------------------------------------ | ------------------------------------------------------------- | | **Security** (26) | Network, credentials, tools, sandbox, SSRF, auth | Gateway exposed? Plaintext API keys? Dangerous tools allowed? | | **Operational** (2) | Model config, fallbacks | Primary model set? Fallback configured? | | **Performance** (2) | Sub-agent limits | Timeouts configured? Concurrency bounded? | | **Compliance** (3) | Retention, isolation, redaction | Session data purged? User contexts isolated? | *** # Part 2: Prerequisites Install all of the following **before** the bootcamp. Each tool has platform-specific instructions and a verification step at the end. ## Required Software ### Git Official Git downloads for all platforms. ```bash theme={"dark"} # Option 1: Homebrew (recommended — no dialog popup) brew install git # Option 2: Xcode Command Line Tools xcode-select --install # A system dialog will appear — click Install and wait (~5 min). ``` ```bash theme={"dark"} sudo apt update && sudo apt install git ``` ```bash theme={"dark"} # Run inside your WSL2 terminal (Ubuntu), not PowerShell sudo apt update && sudo apt install git ``` ```bash theme={"dark"} sudo dnf install git -y ``` **Verify** ```bash theme={"dark"} git --version ``` Expected: `git version 2.x.x` **macOS**: If you used `xcode-select --install`, the system dialog must fully complete before `git` is available. Do not close it early. **Windows**: Run all commands inside your WSL2 (Ubuntu) terminal, not PowerShell or Command Prompt. *** ### Python 3.10+ Official Python downloads — choose 3.12 or later. ```bash theme={"dark"} brew install python@3.12 # If brew warns about PATH, add it: echo 'export PATH="$(brew --prefix python@3.12)/bin:$PATH"' >> ~/.zshrc source ~/.zshrc ``` ```bash theme={"dark"} sudo apt update && sudo apt install python3 python3-pip python3-venv ``` ```bash theme={"dark"} # Inside WSL2 terminal sudo apt update && sudo apt install python3 python3-pip python3-venv ``` ```bash theme={"dark"} # AL2023 ships Python 3.9 by default — install 3.12 explicitly: sudo dnf install python3.12 python3.12-pip -y # Confirm the version: python3.12 --version ``` **Verify** ```bash theme={"dark"} python3 --version ``` Expected: `Python 3.10.x` or higher **`python` vs `python3`**: On Ubuntu and EC2, `python` may point to Python 2 or not exist. Always use `python3` (or `python3.12` on AL2023). All bootcamp scripts use `python3`. **pyenv users**: Run `pyenv version` to confirm the active version — pyenv takes precedence over system Python. **EC2**: If `python3.12` is not available in dnf, `python3.11` also satisfies the `>= 3.10` requirement. *** ### Node.js 22+ Official Node.js downloads — choose the 22 LTS release. ```bash theme={"dark"} # Option 1: Homebrew brew install node # Option 2: nvm (recommended if you manage multiple Node versions) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.zshrc nvm install 22 && nvm use 22 ``` ```bash theme={"dark"} # Option 1: NodeSource (system-wide install) curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash - sudo apt install -y nodejs # Option 2: nvm curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc nvm install 22 && nvm use 22 ``` ```bash theme={"dark"} # Inside WSL2 — use nvm (avoids sudo permission issues) curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc nvm install 22 && nvm use 22 ``` ```bash theme={"dark"} # Use nvm — AL2023's dnf Node package is too old curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash source ~/.bashrc nvm install 22 && nvm use 22 ``` **Verify** ```bash theme={"dark"} node -v && npm -v ``` Expected: `v22.x.x` and `10.x.x` **nvm not in PATH**: After installing nvm, run `source ~/.bashrc` (Linux) or `source ~/.zshrc` (macOS) before `nvm` is usable. Opening a new terminal also works. **Old Node still active**: If `node -v` shows `v14` or `v16` after installing nvm, run `nvm use 22` to switch the active version in that shell. **Never use `sudo npm install -g`** when using nvm — nvm installs Node in your home directory and does not need elevated permissions for global packages. *** ### Docker Docker Desktop for macOS and Windows. Docker Engine for Linux and EC2. ```bash theme={"dark"} # Option 1: Homebrew Cask brew install --cask docker # Open Docker.app from /Applications after installing. # Option 2: Download directly from docker.com/products/docker-desktop/ ``` Docker Desktop must be **running** (whale icon in menu bar) before any `docker` command works. It needs \~4 GB of RAM. ```bash theme={"dark"} # Add Docker's official apt repository (more reliable than ubuntu's docker.io package) sudo apt-get update sudo apt-get install ca-certificates curl gnupg sudo install -m 0755 -d /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \ sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \ https://download.docker.com/linux/ubuntu \ $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y # Add your user to the docker group so you don't need sudo sudo usermod -aG docker $USER && newgrp docker ``` ```bash theme={"dark"} # Recommended: Install Docker Desktop for Windows, then enable WSL Integration: # Docker Desktop → Settings → Resources → WSL Integration → enable your distro # Docker commands then work inside WSL2 automatically. # Alternative: same official repo install as Ubuntu/Debian, inside WSL2 terminal: sudo apt-get update sudo apt-get install ca-certificates curl gnupg sudo install -m 0755 -d /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \ sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \ https://download.docker.com/linux/ubuntu \ $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y sudo usermod -aG docker $USER && newgrp docker ``` ```bash theme={"dark"} sudo dnf install docker -y sudo systemctl enable --now docker sudo usermod -aG docker $USER newgrp docker ``` **Verify** ```bash theme={"dark"} docker --version && docker compose version ``` Expected: `Docker version 27.x.x` and `Docker Compose version v2.x.x` **macOS — daemon not running**: `Cannot connect to the Docker daemon` means Docker Desktop is installed but not started. Open it from Applications and wait for the whale icon. **Linux — permission denied on socket**: You added yourself to the `docker` group but haven't started a new shell session. Run `newgrp docker` or log out and back in. **WSL2 — Docker Desktop not running on Windows**: Docker commands in WSL2 proxy through Docker Desktop on the host. If Docker Desktop is closed on the Windows side, all `docker` commands inside WSL2 will fail. **EC2 — group change not in effect**: `usermod -aG docker` only applies in new sessions. Run `newgrp docker` to avoid re-logging in. *** ### OpenClaw Full installation guide and platform requirements. ```bash theme={"dark"} # Option 1: npm (requires Node.js 22+ from the previous step) npm install -g openclaw # Option 2: Homebrew brew install openclaw ``` ```bash theme={"dark"} # Requires Node.js 22+ installed via nvm (previous step) npm install -g openclaw ``` ```bash theme={"dark"} # Inside WSL2 — requires nvm + Node 22 from previous step npm install -g openclaw ``` ```bash theme={"dark"} # Requires nvm + Node 22 from previous step npm install -g openclaw ``` **Verify** ```bash theme={"dark"} openclaw --version ``` Expected: `openclaw x.x.x` **Permission error (EACCES)**: If `npm install -g openclaw` fails with permission denied, you are using a system Node install instead of nvm. Go back to the Node.js step and install via nvm — it does not require sudo for global packages. **Command not found after install**: Run `source ~/.bashrc` (or open a new terminal) to update your PATH. **Node version**: OpenClaw requires Node.js 22+. Confirm with `node -v` before installing. *** ## Quick Verification Paste this into your terminal to check all prerequisites at once: ```bash theme={"dark"} echo "=== Bootcamp Prerequisites Check ===" git --version >/dev/null 2>&1 && echo "✓ Git: $(git --version)" || echo "✗ Git MISSING" if python3 -c "import sys; assert sys.version_info >= (3,10)" 2>/dev/null; then echo "✓ Python: $(python3 --version) (>= 3.10)" else echo "✗ Python MISSING or < 3.10 (found: $(python3 --version 2>/dev/null || echo 'not found'))" fi if node -e "process.exit(parseInt(process.versions.node) >= 22 ? 0 : 1)" 2>/dev/null; then echo "✓ Node.js: $(node -v) (>= 22)" else echo "✗ Node.js MISSING or < 22 (found: $(node -v 2>/dev/null || echo 'not found'))" fi docker info >/dev/null 2>&1 && echo "✓ Docker: $(docker --version)" || echo "✗ Docker MISSING or daemon not running" docker compose version >/dev/null 2>&1 && echo "✓ Docker Compose: $(docker compose version)" || echo "✗ Docker Compose v2 MISSING" openclaw --version >/dev/null 2>&1 && echo "✓ OpenClaw: $(openclaw --version)" || echo "✗ OpenClaw MISSING" echo "=====================================" ``` ## API Keys You'll need an API key for an LLM provider to power your OpenClaw agent. Pick one from the options below — **Gemma via Google AI Studio is free** and works well for the bootcamp. | Provider | Free Tier | Sign Up | | --------------------------------------- | -------------------------------------- | ------------------------------------------------------ | | **Google AI Studio (Gemma 3 / Gemini)** | **Yes — free API key, no credit card** | [aistudio.google.com](https://aistudio.google.com) | | Anthropic (Claude) | No — requires billing | [console.anthropic.com](https://console.anthropic.com) | | OpenAI (GPT-4o) | No — requires billing | [platform.openai.com](https://platform.openai.com) | | Groq (Llama, Mixtral) | Yes — free tier available | [console.groq.com](https://console.groq.com) | **Recommended for bootcamp**: Get a free Google AI Studio key. Go to [aistudio.google.com](https://aistudio.google.com), sign in with a Google account, and click **Get API key**. No credit card required. *** # Part 3: OpenClaw Setup ## What is OpenClaw? [OpenClaw](https://docs.openclaw.ai) is a self-hosted AI agent gateway. It connects LLMs to messaging channels (Telegram, WhatsApp, Discord, Slack, WebChat) and manages agent configuration, tool access, session state, and model routing — all from a single JSON config file. Full reference: installation, configuration, plugins, channels, and tools. ## Run the Setup Wizard ```bash theme={"dark"} openclaw ``` The interactive wizard guides you through: 1. **Model provider** — Select **Anthropic** and enter the API key 2. **Channel** — Choose **WebChat** for the bootcamp (no external accounts needed) 3. **Identity** — Name your agent (e.g., "Bootcamp Agent") **API Key**: Ask the facilitator for the Anthropic API key. It can also be found in the Notion document **"LLM Providers (API Keys)"**. ## Understand the Configuration After setup, your config lives at `~/.openclaw/openclaw.json` (or a custom path if you chose one during the wizard). **Not sure of your workspace path?** Run this in your normal user shell (not sudo): ```bash theme={"dark"} openclaw configure ``` The first line of output shows your workspace location. Copy the **absolute path** — for example `/home/yourname/.openclaw` — and use that wherever the docs reference `~/.openclaw`. **`~` changes under sudo**: If you ever run a command as a sudoer or with `sudo su`, `~` resolves to `/root/` — not your home directory. So `~/.openclaw` silently becomes `/root/.openclaw`, which doesn't exist. Always use the absolute path (e.g. `/home/yourname/.openclaw/`) when running any TraceCtrl command in an elevated shell. Run `openclaw configure` as your normal user to get it. Here are the key sections: ```json theme={"dark"} { "agents": { "defaults": { "model": { "primary": "anthropic/claude-sonnet-4-20250514" } } }, "channels": { "webchat": { "enabled": true, "dmPolicy": "open" } }, "gateway": { "bind": "loopback", "port": 18789 }, "tools": { "profile": "full" } } ``` | Section | What it controls | | ----------------------- | --------------------------------------------------------------------------- | | `agents.defaults.model` | Which LLM to use (primary + fallbacks) | | `channels` | Messaging channels and their DM/group policies | | `gateway` | Network binding, authentication, TLS | | `tools` | Which tools the agent can access (`full`, `coding`, `messaging`, `minimal`) | | `session` | Conversation scope (`main`, `per-peer`, `per-channel-peer`) and retention | | `logging` | Log level (`info`, `debug`, `trace`) and sensitive data redaction | | `diagnostics` | OpenTelemetry export for runtime traces | | `plugins` | Which plugins are enabled (providers, channels, tools) | Full configuration reference with all options. ## Enable Diagnostics (OTEL Export) For TraceCtrl to receive runtime traces from OpenClaw, enable the diagnostics-otel plugin. Edit `~/.openclaw/openclaw.json` and add these sections: ```json theme={"dark"} { "plugins": { "allow": ["diagnostics-otel"] }, "diagnostics": { "enabled": true, "otel": { "enabled": true, "endpoint": "http://localhost:4318", "protocol": "http/protobuf", "serviceName": "openclaw-gateway", "traces": true, "metrics": false, "logs": false, "sampleRate": 1.0, "flushIntervalMs": 5000 } } } ``` Restart OpenClaw to apply: ```bash theme={"dark"} openclaw gateway restart ``` ## Test Your Agent Open the OpenClaw Control UI at [http://localhost:18789](http://localhost:18789) and send a test message via WebChat. If you set up Telegram, you can message your bot there instead. **Checkpoint**: You can chat with your agent via WebChat or Telegram. OpenClaw is running with diagnostics enabled. *** # Part 4: TraceCtrl Setup ## Clone and Install ```bash theme={"dark"} # Clone the repository git clone https://github.com/tracectrl/tracectrl.git cd tracectrl # Create a virtual environment python3 -m venv .venv source .venv/bin/activate # Install the CLI and Scanner pip install ./scanner pip install ./sdk/tracectrl # Verify tracectrl version ``` You just cloned it — if it looks useful, a star helps others find the project. Takes 2 seconds. ## Start the Stack ```bash theme={"dark"} tracectrl setup ``` This launches the interactive setup wizard which guides you through configuration and starts the Docker containers. **Docker socket access**: `tracectrl setup` starts Docker containers and needs access to the Docker socket. If you see `permission denied while trying to connect to the Docker daemon socket`, your user is not yet in the `docker` group — go back to the Docker install step and run `newgrp docker` (or log out and back in). **Do not run `sudo tracectrl setup`** (or `sudo su` before running it). When you elevate to root, `~` resolves to `/root/` instead of your home directory. Any path that was relative (like `~/.openclaw`) will silently point to the wrong location and the TUI will fail to find your OpenClaw workspace. Alternatively, you can start containers directly: ```bash theme={"dark"} docker compose up -d ``` This starts four containers: | Container | Port | Purpose | | ------------------ | ---------- | ------------------------------------ | | `clickhouse` | 8123, 9000 | Span storage (ClickHouse database) | | `otel-collector` | 4317, 4318 | Receives OpenTelemetry spans | | `tracectrl-engine` | 8000 | Intelligence Engine (API + pipeline) | | `tracectrl-ui` | 3000 | Dashboard (React web app) | Wait \~30 seconds for all services to start, then verify: ```bash theme={"dark"} tracectrl doctor ``` Expected output: ``` TraceCtrl Doctor Services: [OK] Engine API (http://localhost:8000/api/v1/health) [OK] Dashboard UI (http://localhost:3000) [OK] OTel Collector (http://localhost:4318/v1/traces) Docker: [OK] Docker is installed All checks passed. ``` ## Open the Dashboard Open [http://localhost:3000](http://localhost:3000) in your browser. You'll see the TraceCtrl dashboard — currently empty. We'll populate it in the next sections. **Checkpoint**: `tracectrl doctor` shows all green. Dashboard loads at `localhost:3000`. *** # Part 5: Static Scan & Risk Topology ## Run the Scan First, get your absolute workspace path — run this in your **normal user shell** (not as sudo): ```bash theme={"dark"} openclaw configure # The first line shows your workspace path, e.g. /home/yourname/.openclaw ``` Then run the scan using that absolute path: ```bash theme={"dark"} tracectrl scan /home/yourname/.openclaw/ ``` **Do not use `~` if you are running `tracectrl` as a sudoer or in a `sudo su` session.** In an elevated shell, `~` resolves to `/root/` — not your home directory — so `~/.openclaw` points to a path that doesn't exist and the scan will fail silently. Always use the full absolute path (e.g. `/home/yourname/.openclaw/` or `/Users/yourname/.openclaw/`) when running scans from an elevated context. Run `openclaw configure` as your normal user to get the correct path. The scanner reads your `openclaw.json`, runs **33 checks**, and uploads results to the dashboard. Terminal output shows a severity summary, findings table, compound risk signals, and topology stats:
CRITICAL 5 HIGH 14 MEDIUM 14 PASS 0
Check ID Severity Finding
OC-NET-001 CRITICAL Gateway bind is non-loopback — exposed to network
OC-SEC-001 CRITICAL No auth on network-exposed gateway
OC-SEC-002 CRITICAL Dangerous flags active: browser.ssrfPolicy...
OC-TOOL-001 CRITICAL bash/exec tools enable arbitrary command execution
OC-TOOL-002 CRITICAL Wildcard tool permission — all tools permitted
OC-CRED-001 HIGH Plaintext keys found at: models.providers.vllm.apiKey
OC-SEC-004 HIGH sandbox.mode is "off" — no tool isolation
OC-SEC-005 HIGH Browser SSRF: dangerouslyAllowPrivateNetwork is true
OC-OPS-001 HIGH No primary model configured
... 24 more findings (33 checks total)
Compound Risk Signals
\[HIGH] COMPOUND-004 Plaintext credentials + public channel = credential exfiltration risk
Topology: 9 nodes · 8 edges
## View in the Dashboard Open [http://localhost:3000/scan](http://localhost:3000/scan) to see: 1. **Severity cards** — CRITICAL / HIGH / MEDIUM / PASS counts 2. **Architecture risk topology** — your OpenClaw architecture with risk-colored nodes 3. **Category sections** — findings grouped by Security, Operational, Performance, Compliance ### Reading the Topology Graph | Node Color | Type | | ---------- | ------------------------------------ | | **Teal** | Ingress channels (Telegram, WebChat) | | **Blue** | Agents | | **Purple** | LLM Providers (Anthropic, OpenAI) | | **Green** | Tools | | **Orange** | Extensions/Plugins | Nodes with **red borders** have CRITICAL findings. **Orange borders** = HIGH. **Yellow** = MEDIUM. ### Exploring Findings Expand each category section to see individual findings. Click any finding to see: * **What was found** — the specific misconfiguration * **Why it matters** — the security/operational rationale * **How to fix it** — step-by-step remediation ## Auto-Fix Critical Findings ```bash theme={"dark"} tracectrl fix ~/.openclaw/ --auto ``` This automatically remediates the most common findings: | Finding | What the fix does | | ----------------------------- | --------------------------------------- | | `OC-NET-001` Gateway exposed | Sets `gateway.bind = "loopback"` | | `OC-TOOL-001` Dangerous tools | Removes `bash`, `exec` from allow lists | | `OC-TOOL-002` Wildcard tools | Removes `*` from tools.allow | | `OC-ING-001` Open DM policy | Sets `dmPolicy = "pairing"` | | `OC-PERS-001` Cron enabled | Sets `cron.enabled = false` | | `OC-LOG-002` Debug logging | Sets `logging.level = "info"` | The CLI creates a `.bak` backup, applies fixes, re-scans, and uploads results: ``` ✓ OC-NET-001: Set gateway.bind = "loopback" ✓ OC-TOOL-002: Removed "*" from tools.allow Before: 12 findings → After: 6 findings Results uploaded to engine. ``` Refresh the dashboard to see the updated report. ## Manual Fixes Some findings require manual remediation. Here are the most important ones: ### Plaintext API Keys (OC-CRED-001) **Problem**: API keys stored directly in `openclaw.json`. **Fix**: Replace with environment variable references: ```json theme={"dark"} // Before "apiKey": "sk-ant-abc123..." // After "apiKey": "${ANTHROPIC_API_KEY}" ``` Then set the variable in your shell: ```bash theme={"dark"} export ANTHROPIC_API_KEY="sk-ant-abc123..." ``` Or use `openclaw configure` to reconfigure the provider with an env var. ### Browser SSRF Policy (OC-SEC-002) **Problem**: `browser.ssrfPolicy.dangerouslyAllowPrivateNetwork` is `true` by default — the agent's browser can reach your internal network. **Fix**: Add to `openclaw.json`: ```json theme={"dark"} { "browser": { "ssrfPolicy": { "dangerouslyAllowPrivateNetwork": false } } } ``` ### Sandbox Not Enabled (OC-SEC-004) **Problem**: Agent tools run directly on the host without isolation. **Fix**: ```json theme={"dark"} { "agents": { "defaults": { "sandbox": { "mode": "non-main" } } } } ``` ### Session Scope Shared (OC-COMP-002) **Problem**: All users share the same conversation context. **Fix**: ```json theme={"dark"} { "session": { "dmScope": "per-channel-peer" } } ``` Full security configuration reference. ## Re-scan After Manual Fixes ```bash theme={"dark"} # Use your absolute workspace path (same one from the scan step above) tracectrl scan /home/yourname/.openclaw/ ``` Refresh the dashboard — your findings should be significantly reduced. **Checkpoint**: 0 CRITICAL findings. Dashboard shows the updated scan report with risk topology. *** # Part 6: Strands Agent + Runtime Telemetry ## What is Strands? [AWS Strands](https://strandsagents.com/) is an open-source SDK for building AI agents with tool use. TraceCtrl instruments Strands agents to capture every execution — agent runs, LLM calls, and tool invocations — as OpenTelemetry spans. ## Install the Strands Instrumentation From the TraceCtrl repo root: ```bash theme={"dark"} pip install ./sdk/tracectrl-instrumentation-strands pip install strands-agents strands-agents-tools ``` ## Create a Strands Agent Create a file called `my_agent.py`: ```python theme={"dark"} import tracectrl from tracectrl.instrumentation.strands import StrandsInstrumentor # 1. Configure TraceCtrl — sends spans to the local OTel Collector tracectrl.configure(service_name="bootcamp-agent") # 2. Instrument Strands — wraps all agent/LLM/tool calls with span creation StrandsInstrumentor().instrument() # 3. Build your agent from strands import Agent from strands_tools import calculator agent = Agent( model="us.anthropic.claude-sonnet-4-20250514-v1:0", tools=[calculator], system_prompt="You are a helpful assistant. Use the calculator tool for math." ) # 4. Run it response = agent("What is 42 * 17 + 389?") print(response) ``` **API Key**: Set your credentials before running: ```bash theme={"dark"} export AWS_PROFILE=default # or export ANTHROPIC_API_KEY="sk-ant-..." ``` Ask the facilitator for keys, or check the Notion document **"LLM Providers (API Keys)"**. ## Run the Agent ```bash theme={"dark"} python my_agent.py ``` You should see the agent respond with the calculation result. ## View the Traces Open [http://localhost:3000/sessions](http://localhost:3000/sessions). You'll see a new trace for `bootcamp-agent`. Click the row to expand the **trace tree**: * **Agent span** — the top-level agent execution * **LLM spans** — each model call with input/output and token counts * **Tool spans** — calculator tool with arguments and result Click any span to see its **detail panel** with timing, attributes, and input/output values. ## View the Topology Open [http://localhost:3000/topology](http://localhost:3000/topology). The runtime topology graph now shows: * **Agent node** (bootcamp-agent) → connected to the **LLM provider** (Anthropic/Bedrock) * **Agent node** → connected to **tool nodes** (calculator) This graph is built automatically from the trace data — no configuration needed. ## Try More Complex Scenarios ### Multi-tool Agent ```python theme={"dark"} from strands import Agent from strands_tools import calculator, http_request agent = Agent( model="us.anthropic.claude-sonnet-4-20250514-v1:0", tools=[calculator, http_request], system_prompt="You are a research assistant with calculator and web access." ) response = agent("What is the population of Singapore divided by its area in km²?") print(response) ``` ### Multiple Runs Run the agent several times to build up session history: ```python theme={"dark"} questions = [ "What is 2^10?", "Calculate the square root of 144", "What is 15% of 2500?", ] for q in questions: print(f"\n> {q}") print(agent(q)) ``` Each run creates a new session in the dashboard. The topology grows as more tools and models are observed. ## What Gets Captured | Span Type | Key Attributes | | ----------- | ------------------------------------------------------------- | | **Agent** | `agent.name`, `openinference.span.kind=AGENT` | | **LLM** | `llm.model_name`, `input.value`, `output.value`, token counts | | **Tool** | `tool.name`, `tool.description`, input/output, risk category | | **Session** | `tracectrl.session_id` linking all spans in a conversation | TraceCtrl's `TraceCtrlSpanProcessor` automatically enriches every span with: * **Tool risk category** — one of 8 categories (filesystem, network, code\_execution, data\_store, web\_browsing, communication, system, other) * **Agent identity** — framework detection and agent naming * **Session correlation** — links all spans from a single conversation **Checkpoint**: Sessions page shows traces with agent → LLM → tool spans. Topology page shows your agent connected to its tools and LLM provider. *** # Summary ## What You Built | Component | Status | | ------------------------------------------------------------- | ------------------------------------------- | | TraceCtrl stack (Engine + Dashboard + Collector + ClickHouse) | Running via Docker | | OpenClaw agent with WebChat | Configured and chatting | | Security scan (33 checks) | Findings visible on dashboard | | Auto-remediation | Critical findings fixed | | Manual hardening | SSRF, sandbox, session isolation configured | | Strands agent with TraceCtrl instrumentation | Traces and topology visible | ## CLI Reference ```bash theme={"dark"} tracectrl scan [path] # Run 33-check security scan tracectrl fix --auto # Auto-fix + rescan + upload tracectrl doctor # Verify all services are healthy tracectrl version # Print version tracectrl install-plugin # Install the OpenClaw telemetry plugin ``` ## Cleanup & Uninstall When you're done with the bootcamp — or want a fresh start — work through these steps in order. They remove OpenClaw, its workspace, the TraceCtrl stack, and all local data. **These steps are destructive.** `rm -rf` on the workspace deletes your configured agents, chat history, and credentials. `docker compose down -v` deletes the ClickHouse volume — every trace and scan result you collected. Back up anything you want to keep first. ### 1. Stop the TraceCtrl stack From inside the `tracectrl` repo: ```bash theme={"dark"} # Stop containers and remove the ClickHouse volume (deletes all traces and scans) docker compose down -v # If you only want to stop the containers but keep the data: # docker compose down ``` ### 2. Uninstall OpenClaw Use the same method you used to install. If you're not sure, run `which openclaw` first — paths under `/opt/homebrew/` or `/usr/local/Cellar/` mean Homebrew; paths under `nvm` or `node_modules` mean npm. ```bash theme={"dark"} # If installed via npm npm uninstall -g openclaw # If installed via Homebrew brew uninstall openclaw # Not sure which? Run both — the unused one will no-op. ``` ```bash theme={"dark"} npm uninstall -g openclaw ``` ```bash theme={"dark"} # Run inside your WSL2 shell npm uninstall -g openclaw ``` ```bash theme={"dark"} npm uninstall -g openclaw ``` **Verify the binary is gone:** ```bash theme={"dark"} which openclaw || echo "openclaw removed" ``` ### 3. Remove the OpenClaw workspace OpenClaw stores your agent config, chat history, and secrets in its workspace directory — usually `~/.openclaw`. Under `sudo` the home shortcut resolves to `/root/` instead of your user home, so double-check the path before deleting. ```bash theme={"dark"} rm -rf ~/.openclaw ``` If you installed OpenClaw as root (via `sudo npm install -g ...`), the workspace may live at `/root/.openclaw`. Run `sudo rm -rf /root/.openclaw` in that case. *** ## Useful Links Source code and issues. Full OpenClaw reference. The observability standard TraceCtrl is built on. AWS Strands agent framework. # Prerequisites Source: https://docs.tracectrl.ai/bootcamp/prerequisites System requirements, software, and API keys to set up before the TraceCtrl bootcamp. Complete this before the session. **Complete this before the bootcamp.** Run the verification script at the bottom and confirm all green before arriving. *** ## System Requirements ### Hardware | Resource | Minimum | Recommended | | ------------- | ---------------------------------------------- | ----------- | | **RAM** | 8 GB | 16 GB | | **CPU** | 2 cores | 4 cores | | **Free Disk** | 5 GB | 10 GB | | **OS** | macOS 12+, Ubuntu 20.04+, Windows 10/11 (WSL2) | | The four Docker containers each have different resource profiles: | Container | Image Size | Runtime RAM | Role | | ------------------ | --------------------- | ------------------------- | ----------------------------------------------------------------------------- | | `clickhouse` | 805 MB | 2–4 GB | Column-oriented database — buffers data in memory for fast analytical queries | | `otel-collector` | 328 MB | 128–256 MB | Receives, batches, and forwards OpenTelemetry spans | | `tracectrl-engine` | 226 MB | 256–512 MB | FastAPI app running the TAGAAI analysis pipeline | | `tracectrl-ui` | 63 MB | 64–128 MB | Static React dashboard served by nginx | | **Total** | **\~1.4 GB download** | **\~2.5–5 GB at runtime** | Plus Docker overhead and host OS | ClickHouse is the dominant cost — it is a production-grade OLAP database designed to hold millions of spans in memory for fast queries. On an 8 GB machine you have roughly 3–4 GB headroom after the full stack is running, which is sufficient for the workshop. **Docker/Rancher memory cap.** Docker Desktop and Rancher Desktop default to a 4–6 GB memory limit for the Linux VM. ClickHouse may OOM-kill if that cap is too low. Go to **Settings → Resources → Memory** and set it to at least **6 GB** before starting the stack. *** ## Software Prerequisites ### 1. Container Runtime Pick the runtime that fits your machine and your organisation's licensing policies. **Docker Desktop** is the simplest path on macOS / Windows if your org permits it. **Rancher Desktop** is a free open-source alternative if Docker Desktop's subscription terms don't fit (e.g., large enterprises on the paid tier). **Docker Engine** is for Linux servers and WSL2. All three work with TraceCtrl — `tracectrl setup` detects which is installed automatically. Simplest setup. Requires a paid subscription for large organisations — check your company's policy first. ```bash theme={"dark"} # macOS — Homebrew brew install --cask docker # Open Docker.app from /Applications after installing. ``` Or download directly from [docker.com/products/docker-desktop](https://www.docker.com/products/docker-desktop/). After installing, go to **Settings → Resources → Memory** and set it to at least **6 GB**. ```bash theme={"dark"} # Verify docker --version && docker compose version ``` Free and open-source. Use this when Docker Desktop's licensing doesn't fit your organisation. 1. Download and install Rancher Desktop from [rancherdesktop.io](https://rancherdesktop.io) 2. On first launch, choose **Container Engine: dockerd (moby)** — this gives you the standard `docker` and `docker compose` CLI 3. Under **Kubernetes**, you can disable it (not needed for TraceCtrl) 4. Go to **Settings → Resources → Memory** and set it to at least **6 GB** ```bash theme={"dark"} # Verify docker --version && docker compose version ``` If your Rancher Desktop is already configured with the **containerd** engine, use `nerdctl compose` in place of `docker compose` everywhere in the bootcamp. `tracectrl setup` detects this automatically and uses `nerdctl` if `docker` is not found. ```bash theme={"dark"} # Ubuntu / Debian / WSL2 sudo apt-get update sudo apt-get install ca-certificates curl gnupg -y sudo install -m 0755 -d /etc/apt/keyrings curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \ sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \ https://download.docker.com/linux/ubuntu \ $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \ sudo tee /etc/apt/sources.list.d/docker.list > /dev/null sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io \ docker-buildx-plugin docker-compose-plugin -y sudo usermod -aG docker $USER && newgrp docker ``` ```bash theme={"dark"} # Amazon Linux 2023 (EC2) sudo dnf install docker -y sudo systemctl enable --now docker sudo usermod -aG docker $USER && newgrp docker ``` ```bash theme={"dark"} # Verify docker --version && docker compose version ``` Expected output: ``` Docker version 27.x.x Docker Compose version v2.x.x ``` **macOS — daemon not running:** `Cannot connect to the Docker daemon` means Rancher Desktop or Docker Desktop is installed but not started. Open it from Applications and wait for the icon to turn green/active. **Linux — permission denied on socket:** Run `newgrp docker` or log out and back in after adding yourself to the docker group. *** ### 2. Python 3.10+ ```bash theme={"dark"} brew install python@3.12 # Add to PATH if brew warns: echo 'export PATH="$(brew --prefix python@3.12)/bin:$PATH"' >> ~/.zshrc source ~/.zshrc ``` ```bash theme={"dark"} sudo apt update && sudo apt install python3 python3-pip python3-venv -y ``` ```bash theme={"dark"} sudo dnf install python3.12 python3.12-pip -y ``` **Verify:** `python3 --version` → `Python 3.10.x` or higher *** ### 3. Git ```bash theme={"dark"} brew install git ``` ```bash theme={"dark"} sudo apt update && sudo apt install git -y ``` ```bash theme={"dark"} sudo dnf install git -y ``` **Verify:** `git --version` → `git version 2.x.x` *** ### 4. Bootcamp Examples Repo Two pre-built, pre-instrumented Strands examples that the workshop uses. Clone now so the first run doesn't have to download anything. ```bash theme={"dark"} git clone https://github.com/tracectrl/tracectrl-bootcamp-examples.git cd tracectrl-bootcamp-examples ``` You should see two example folders: ```bash theme={"dark"} ls # README.md research_workflow_example teacher_assistants_workflow_example ``` Each folder is self-contained — its own README, `.env.example`, runner scripts (`run_agents_workflow.sh` for pip, `run_agents_workflow_uv.sh` for [uv](https://docs.astral.sh/uv/getting-started/installation/)), and Python files. **Don't `cp .env.example .env` yet** — you'll do that during the workshop once you've decided which auth path you're using. The first time you run a `run_*.sh` script, it creates a venv and installs `strands-agents[gemini]`, `strands-agents-tools`, `tracectrl`, and `tracectrl-instrumentation-strands` from PyPI. About a minute on pip, a few seconds on uv. **Run the script once before the session** to prime the venv — even if you don't have an API key yet, the install will succeed and only the final agent call will fail. That gets the slow part out of the way over your home WiFi. *** ## API Key: Google AI Studio The bootcamp organizer provides a shared **Google AI Studio API key** via a single Bitwarden Send link. You'll need a **passphrase** to unlock it — the facilitator will share that on the day of the bootcamp. Open Bitwarden Send → enter the passphrase (given in person on the day) → click the copy icon → paste straight into the `GOOGLE_API_KEY=` line of each example's `.env`. Don't paste the key into chat, slides, screenshots, or any file other than `.env`. The link expires and the key is rotated immediately after the bootcamp ends. If for any reason you can't access the link, AI Studio's **free tier** is more than enough for the workshop — create your own key by following the same steps below. No billing setup is required either way. | Limit | Value | | ------------------------- | --------- | | Requests per minute (RPM) | 15 | | Tokens per minute (TPM) | Unlimited | | Requests per day (RPD) | 1,500 | These limits are sufficient for the bootcamp. View your own limits anytime under **Rate Limit** in the AI Studio sidebar. Gemini API Rate Limit page showing Gemini 3.1 Flash Lite Preview free tier: 15 RPM, unlimited TPM, 1.5K RPD ### Step 1 — Create the Key 1. Go to [aistudio.google.com](https://aistudio.google.com) and sign in with any Google account 2. Click **Get API key** in the left sidebar (or **API Keys** if already signed in) 3. Click **Create API key** (top right) 4. Select or accept the **Default Gemini Project** 5. Your key appears in the list. Click the **copy icon** (highlighted below) to copy it to your clipboard Google AI Studio API Keys page — the copy button is highlighted in red on the right side of the key row The key starts with `AIza...`. The **Billing Tier** column shows **Free tier** — no payment is needed for the bootcamp. ### Step 2 — Test the Key Paste this into your terminal (replace `YOUR_API_KEY_HERE`): ```bash theme={"dark"} curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.1-flash-lite-preview:generateContent" \ -H 'Content-Type: application/json' \ -H 'X-goog-api-key: YOUR_API_KEY_HERE' \ -X POST \ -d '{ "contents": [ { "parts": [ { "text": "What tools do you have access to?" } ] } ] }' ``` Expected: a JSON response containing `candidates[0].content.parts[0].text`. If you see a `400` or `403` error, the key was not copied correctly — return to AI Studio and copy it again. **Never commit your API key to git.** Always use environment variables — never paste the key directly into code files. *** ## Configure the Example `.env` Files Each bootcamp example reads its config from a local `.env` file. Set them up once now — the workshop step is then just "run the script". Do this for **both** examples even if you only intend to run one; it costs nothing and saves time on the day. ```bash theme={"dark"} cd tracectrl-bootcamp-examples cp research_workflow_example/.env.example research_workflow_example/.env cp teacher_assistants_workflow_example/.env.example teacher_assistants_workflow_example/.env ``` Open each `.env` and paste your `AIza...` Google AI Studio key into `GOOGLE_API_KEY`: ```env theme={"dark"} GOOGLE_API_KEY=AIzaSy...your_key_here GOOGLE_MODEL_ID=gemini-3.1-flash-lite TRACECTRL_ENDPOINT=http://localhost:4317 TRACECTRL_SERVICE_NAME=agents-workflow TRACECTRL_ENVIRONMENT=demo ``` Leave the `TRACECTRL_*` lines as they are — the defaults work for the workshop's local stack. **Hit a Google AI Studio rate limit mid-workshop?** Swap `GOOGLE_MODEL_ID` to `gemini-2.5-flash` (also free-tier with generous headroom) and rerun. **Don't commit `.env`.** Both examples gitignore it, but double-check before pushing any forks. Keys also land in TraceCtrl trace attributes — fine locally, something to know before pointing the OTLP endpoint anywhere remote. **Sanity check:** from inside one of the example folders, run the runner script — it will install dependencies on first run and then immediately try to call the model. If your `.env` is right, you'll get an interactive `>` prompt. If auth is wrong, it'll error within a second. Either is fine for pre-workshop — the install + venv creation is what you want done ahead of time. ```bash theme={"dark"} cd research_workflow_example bash run_agents_workflow.sh # pip path # or: bash run_agents_workflow_uv.sh # uv path ``` *** ## Pull Docker Images Ahead of Time **Do this before the session.** The images total \~1.4 GB — venue WiFi may be slow. **Start your container runtime first.** Docker Desktop or Rancher Desktop must be running before any `docker pull` will work. On first launch, Rancher Desktop takes 2–3 minutes to provision its Linux VM — wait for the container icon in the bottom status bar to go green. Sanity check: ```bash theme={"dark"} docker info | head -5 ``` If you see `Cannot connect to the Docker daemon`, the runtime is not up yet — open Rancher Desktop / Docker Desktop and wait. ```bash theme={"dark"} docker pull ghcr.io/tracectrl/tracectrl-engine:latest docker pull ghcr.io/tracectrl/tracectrl-ui:latest docker pull clickhouse/clickhouse-server:latest docker pull otel/opentelemetry-collector-contrib:latest ``` Or after cloning the repo (run from the repo root): ```bash theme={"dark"} git clone https://github.com/tracectrl/tracectrl.git cd tracectrl make pull ``` **`make: *** No rule to make target 'pull'`?** You're either not in the repo root (`cd tracectrl` first), or your clone predates the `pull` target — run `git pull origin main` to update. *** ## Full Verification Run this before the session. All five lines should show `✓`. The API key value itself is not checked — only that `GOOGLE_API_KEY` is set in your shell. ```bash theme={"dark"} echo "=== TraceCtrl Bootcamp Prerequisites Check ===" git --version >/dev/null 2>&1 \ && echo "✓ Git: $(git --version)" \ || echo "✗ Git MISSING" python3 -c "import sys; assert sys.version_info >= (3,10)" 2>/dev/null \ && echo "✓ Python: $(python3 --version)" \ || echo "✗ Python MISSING or < 3.10 (found: $(python3 --version 2>/dev/null || echo 'not found'))" docker info >/dev/null 2>&1 \ && echo "✓ Docker: $(docker --version)" \ || echo "✗ Docker daemon not running — start Rancher Desktop or Docker Desktop" docker compose version >/dev/null 2>&1 \ && echo "✓ Docker Compose: $(docker compose version)" \ || echo "✗ Docker Compose v2 MISSING" if [ -n "$GOOGLE_API_KEY" ]; then echo "✓ Auth: GOOGLE_API_KEY set (Google AI Studio)" else echo "✗ Auth MISSING — set GOOGLE_API_KEY in your shell" fi echo "==============================================" ``` *** ## Set Up TraceCtrl With the prerequisites in place, install the TraceCtrl CLI and start the stack so it's ready to receive spans on day one of the bootcamp. By the end of this section you will have: 1. A running **TraceCtrl stack** (OTel Collector, ClickHouse, Engine, Dashboard) 2. The **tracectrl CLI** installed in a Python virtual environment 3. The Dashboard accessible at [http://localhost:3000](http://localhost:3000) — ready to receive spans from the agents you'll build during the workshop ### Clone and Install the CLI ```bash theme={"dark"} git clone https://github.com/tracectrl/tracectrl.git cd tracectrl ``` ```bash theme={"dark"} python3 -m venv .venv source .venv/bin/activate pip install tracectrl ``` ```bash theme={"dark"} uv venv source .venv/bin/activate uv pip install tracectrl ``` Requires [uv](https://docs.astral.sh/uv/getting-started/installation/) on `PATH`. ### Start the Stack ```bash theme={"dark"} tracectrl setup ``` The interactive wizard starts the four Docker containers. Alternatively: ```bash theme={"dark"} docker compose up -d ``` **Rancher Desktop users:** `tracectrl setup` detects Rancher automatically. If you're using the containerd engine, it uses `nerdctl compose` instead of `docker compose`. **Memory:** Ensure your container runtime has at least 6 GB of memory allocated (Settings → Resources → Memory). ClickHouse is the heaviest container at 2–4 GB RAM. ### Verify the Stack ```bash theme={"dark"} tracectrl doctor ``` Expected output: ``` TraceCtrl Doctor Services: [OK] Engine API (http://localhost:8000/api/v1/health) [OK] Dashboard UI (http://localhost:3000) [OK] OTel Collector (http://localhost:4318/v1/traces) All checks passed. ``` Open the dashboard at [http://localhost:3000](http://localhost:3000) — currently empty. You'll populate it during the workshop. **Checkpoint:** `tracectrl doctor` shows all green. Dashboard loads at `localhost:3000`. You're ready for the bootcamp. # TraceCtrl Bootcamp (Strands) Source: https://docs.tracectrl.ai/bootcamp/strands-guide Hands-on workshop — instrument an AWS Strands agent with TraceCtrl and go from zero traces to full security observability in 90 minutes. Complete the [Prerequisites](/bootcamp/prerequisites) before starting this workshop. Paste the TraceCtrl agent instructions into Claude Code, Cursor, or Copilot to get contextual help throughout this workshop. *** # Part 1: Introduction to TraceCtrl ### What is TraceCtrl? TraceCtrl is a **security observability platform for agentic AI**. Our tagline captures the workflow: 1. **See** — Visualize your agent's architecture, topology, and risk posture at a glance 2. **Trace** — Trace every message, tool call, and model request through the full execution lifecycle 3. **Ctrl** — Control and harden your agent's configuration with automated scanning and remediation ### Components TraceCtrl has five components: | Component | What it does | Technology | | ------------------ | ----------------------------------------------------- | --------------------------- | | **CLI** | `tracectrl scan`, `fix`, `doctor`, `setup` | Python (pip installable) | | **Scanner** | Security/ops/perf/compliance checks for agent configs | Python | | **OTel Collector** | Receives spans from agents via OTLP | OpenTelemetry Collector | | **Engine** | Processes spans, builds topology, serves API | FastAPI + ClickHouse | | **Dashboard** | Visualizes scans, traces, topology | React + Vite + Cytoscape.js | ### Architecture TraceCtrl architecture: a Python agent process runs the SDK (Framework Instrumentor + TraceCtrl SDK core + Guardrails), exports OTLP spans on :4317/:4318 to the OTel Collector. The Collector forwards to ClickHouse (:8123/:9000) which holds otel_traces, agent_inventory, topology edges, attack paths, guardrail registry + violations, scan results, and the protector_plus_config. The Intelligence Engine (FastAPI :8000) runs a 60-second pipeline that builds inventory + topology, ingests guardrail spans, and computes the attack graph; it serves /api/v1/* REST + SSE. The React Dashboard (:3000) renders Monitor (agents/sessions/topology), Security (alerts/guardrails/scan/risk/attacks), and Configure (settings). The Guardrails block also talks HTTP to an external Protector Plus firewall (optional); both SDK and Protector Plus violations flow to the same engine pipeline. 1. Your agent (or OpenClaw) exports OpenTelemetry spans to the **OTel Collector**. 2. The Collector writes spans to **ClickHouse** (column-oriented database optimized for traces). 3. The **Engine** runs a pipeline every 60 seconds — reads spans, builds agent inventory, discovers topology edges, ingests guardrail registrations and violations, and computes the attack graph. 4. The **Dashboard** queries the Engine API to render Sessions, Topology, Alerts, Guardrails, Scan reports, Risk, and Attack Paths. 5. **Guardrails** ride the same pipe: in-SDK LLM judges (`tracectrl.guardrails`) and the external **Protector Plus** firewall (`tracectrl.protector`) both emit guardrail-evaluation spans that the engine surfaces as alerts. 6. The **CLI Scanner** (`tracectrl scan`, `tracectrl fix`) is a separate path that statically analyses OpenClaw configs and uploads findings to the Engine. **Stack not running yet?** The TraceCtrl stack must be up before Part 2 — install and start it with the [Set Up TraceCtrl](/bootcamp/prerequisites#set-up-tracectrl) section of the Prerequisites page, then run `tracectrl doctor` to confirm all services are green. *** # Part 2: Hands-on with TraceCtrl (Strands Agents) In this part you'll instrument and run one of two pre-built Strands agent examples, watch the traces and topology light up in the TraceCtrl dashboard, attach a guardrail with the TraceCtrl SDK, and close out by watching FinFlow — our reference Strands application — get attacked end-to-end as a capstone. ## 2.1 Pick an Example to Run For your hands-on portion, you'll run one (or both) of two pre-built examples from the [bootcamp examples repo](https://github.com/tracectrl/tracectrl-bootcamp-examples) (you cloned this in the [Prerequisites](/bootcamp/prerequisites#4-bootcamp-examples-repo) step). Both are pre-instrumented and show a different topology shape so you can compare them side by side in the dashboard. | Example | Topology | What it does | | -------------------------------------- | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------- | | `research_workflow_example/` | 3-agent chain: **Researcher → Analyst → Writer** | Web research / fact-checking. Researcher uses `http_request`, hands off via tool-call to Analyst, which hands off to Writer. | | `teacher_assistants_workflow_example/` | Star: 1 orchestrator → 4 specialists | **TeachAssist** routes student queries to **MathWizard**, **EnglishMaster**, **LanguageAssistant**, or **GeneralAssist**. | Each example folder is self-contained — its own README, `.env`, runner script, and Python files. You'll see the rendered topology for each in [2.3 Compare the Topologies](#2-3-compare-the-topologies) after you run them. ## 2.2 Running the Example **`.env` files should already be configured** from [Prerequisites → Configure the Example `.env` Files](/bootcamp/prerequisites#configure-the-example-env-files). If you skipped that, jump back — both examples need a populated `.env` to run. If you hit a Gemini rate limit mid-session, swap `GOOGLE_MODEL_ID` to `gemini-2.5-flash` and rerun. **TraceCtrl must be running before you start the agents.** The script sends spans to the OTel Collector on `localhost:4317`. If TraceCtrl is not up, the agents will still run and produce output — but nothing will appear in the dashboard. Run `tracectrl doctor` to confirm all services are green before continuing. ```bash theme={"dark"} bash run_agents_workflow.sh ``` Uses `venv/` for its virtual environment. ```bash theme={"dark"} bash run_agents_workflow_uv.sh ``` Uses `.venv/` for its virtual environment. Requires [uv](https://docs.astral.sh/uv/getting-started/installation/) on `PATH`. The first run creates the venv and installs `strands-agents[gemini]`, `strands-agents-tools`, `tracectrl`, and `tracectrl-instrumentation-strands` from PyPI — about a minute on pip, a few seconds on uv. **Subsequent runs reuse the venv and skip the install.** At the prompt, try these in order — start with the short one first to confirm everything is wired up before running a longer query: ``` > Tuesday comes before Monday in the week > Lemon cures cancer > What are quantum computers? ``` Each prompt creates a new trace in TraceCtrl. Type `exit` to quit. ```bash theme={"dark"} bash run_agents_workflow.sh ``` Uses `venv/` for its virtual environment. ```bash theme={"dark"} bash run_agents_workflow_uv.sh ``` Uses `.venv/` for its virtual environment. Requires [uv](https://docs.astral.sh/uv/getting-started/installation/) on `PATH`. The first run creates the venv and installs dependencies — about a minute on pip, a few seconds on uv. **Subsequent runs reuse the venv and skip the install.** Run these four prompts **in order**, then open [http://localhost:3000/topology](http://localhost:3000/topology) after each one to watch the star topology build up edge by edge: ``` > What is 1 + 1? ``` Routes to **MathWizard** — first edge appears: TeachAssist → MathWizard. ``` > Define Apple ``` Routes to **GeneralAssist** — second edge: TeachAssist → GeneralAssist. ``` > Write me a poem ``` Routes to **EnglishMaster** — third edge: TeachAssist → EnglishMaster. ``` > Translate hello to French ``` Routes to **LanguageAssistant** — full four-arm star now visible. **No Computer Science specialist.** The system prompt mentions one, but it is not implemented. CS or coding questions (e.g. "explain recursion") will be handled by **GeneralAssist** instead. Type `exit` to quit. Open [http://localhost:3000/sessions](http://localhost:3000/sessions). You'll see a row per prompt tagged with your `TRACECTRL_SERVICE_NAME` (`agents-workflow` for research, `teachers-assistant` for teacher). Click the row to expand the trace tree. Five span kinds you'll see: * **`invoke_agent `** — top-level span for each `tag_agent`-named agent. Nests when one agent calls another via a `@tool` hand-off. * **`execute_event_loop_cycle`** — one per turn of the Strands event loop (LLM call + any tool calls it produced). A multi-turn agent run has several of these stacked under its `invoke_agent`. * **`chat`** — the actual LLM call inside an event loop cycle (prompt, response, token counts). * **`execute_tool `** — every `@tool` invocation with arguments and result. * Tool spans that wrap *agent hand-offs* (`execute_tool call_analyst`, `execute_tool math_assistant`) contain a nested `invoke_agent` span — that nesting is what gives the topology its `delegates` edges. Click any span to see its detail panel: timing, attributes, raw input/output values. TraceCtrl Sessions view for research_workflow_example: 1 trace, 24 spans, 21.08s duration, status OK. Trace tree expanded under invoke_agent Researcher showing multiple execute_event_loop_cycle spans, each containing a chat (LLM) span and one or more execute_tool http_request spans. Toward the bottom, an execute_tool call_analyst span contains a nested invoke_agent Analyst, which in turn contains another execute_event_loop_cycle with chat and execute_tool call_writer wrapping an invoke_agent Writer span. A single "Lemon cures cancer" fact-check prompt produces **24 spans across 21 seconds**. The Researcher runs through four event-loop cycles (each one a `chat` + one or two `http_request` tool calls to fetch sources), then hands off via `execute_tool call_analyst` → `invoke_agent Analyst` → `execute_tool call_writer` → `invoke_agent Writer`. The full chain is visible as one continuous trace tree. TraceCtrl Sessions view for teacher_assistants_workflow_example: 3 traces total, showing two invoke_agent TeachAssist sessions (4.49s and 3.76s) and one invoke_agent Researcher session leftover from the research example. The middle TeachAssist trace is expanded — invoke_agent TeachAssist contains an execute_event_loop_cycle with a chat span and an execute_tool math_assistant span; nested inside that tool span is invoke_agent MathWizard with its own execute_event_loop_cycle, chat span, and a follow-up execute_event_loop_cycle with another chat span. A "What is 1 + 1?" prompt produces **9 spans across \~4 seconds**. TeachAssist's first event-loop cycle picks the route (`chat`), calls `execute_tool math_assistant` which contains `invoke_agent MathWizard`, MathWizard runs its own event-loop cycles, and the result bubbles back up. Each subsequent prompt creates a separate trace — three different prompts give you three trace rows. ### What TraceCtrl Captures | Span | Key attributes | | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **Agent** | `tracectrl.agent.name`, `tracectrl.agent.role`, `openinference.span.kind=AGENT` (OpenInference's unprefixed `agent.name` is also present on the span; TraceCtrl-prefixed copies are what the topology graph reads) | | **LLM** | `llm.model_name`, `input.value`, `output.value`, token counts | | **Tool** | `tool.name`, `tool.description`, input/output, `tracectrl.tool.category` | The `TraceCtrlSpanProcessor` (inside the SDK) enriches every span with tool risk category, agent identity, session correlation, and input-source classification automatically — no dashboard wiring needed. The instrumentation is **three lines plus one decorator** — identical across both examples. Open `agents_workflow.py` (research example) or `teachers_assistant.py` (teacher example) and look at the top: ```python theme={"dark"} import tracectrl from tracectrl import tag_agent from tracectrl.instrumentation.strands import StrandsInstrumentor tracectrl.configure( service_name=os.getenv("TRACECTRL_SERVICE_NAME", "agents-workflow"), endpoint=os.getenv("TRACECTRL_ENDPOINT", "http://localhost:4317"), ) StrandsInstrumentor().instrument() ``` Then for **every Strands `Agent` you create**, one extra line so TraceCtrl can name it in the topology: ```python theme={"dark"} researcher_agent = Agent( name="Researcher", model=model, system_prompt="...", tools=[http_request, call_analyst], ) tag_agent(researcher_agent) ``` Three things to notice: 1. **`StrandsInstrumentor().instrument()`** patches the Strands SDK so every agent invocation, LLM call, and tool call emits an OpenTelemetry span. No per-agent boilerplate. 2. **`tag_agent(...)`** stamps the agent's name and role onto every span the agent emits (via the auto-installed `SystemPromptStamper`). The parent-child span tree exists either way — Strands wires that up — but without `tag_agent` the agent nodes in the topology graph come through with generic / inferred names instead of `Researcher` / `Analyst` / `TeachAssist`, which makes the topology much harder to read. In both examples, agents hand off to each other by calling a `@tool` function that creates a new `Agent` and calls `tag_agent()` on it — that's what produces the named `delegates` edges (`Researcher → Analyst → Writer`, `TeachAssist → MathWizard`, etc.). 3. **OTLP gRPC on `:4317`.** This is the OpenTelemetry Collector that ships with the TraceCtrl stack you started during the [Prerequisites](/bootcamp/prerequisites#set-up-tracectrl). The Engine reads from it, the Dashboard reads from the Engine. **Checkpoint:** Sessions page shows a trace with `invoke_agent` at the top, nested `execute_event_loop_cycle` / `chat` / `execute_tool` spans, and at least one `invoke_agent ` nested under an `execute_tool` (the agent hand-off). Span count is in the high single digits for the teacher example, mid-twenties for a multi-source research query. ## 2.3 Compare the Topologies Open [http://localhost:3000/topology](http://localhost:3000/topology). Each example produces a distinct shape: TraceCtrl Topology view for research_workflow_example: three hexagonal agent nodes — Researcher, Analyst, Writer — connected by 'delegates' edges in a linear chain. Researcher has a 'uses' edge down to the http_request tool (green square node). A linear 3-agent chain. `Researcher` is the entry point — it fetches web sources via `http_request`, then hands off to `Analyst`, which hands off to `Writer`. Each hand-off is a `@tool` function call, which is why TraceCtrl draws `delegates` edges between the agents rather than treating them as a flat list. Only external edge: `Researcher` → `http_request` (the `external_api` risk category). TraceCtrl Topology view for teacher_assistants_workflow_example: TeachAssist at center connected by 'delegates' edges to four specialist agents — MathWizard, EnglishMaster, LanguageAssistant, and GeneralAssist — forming a star shape. A star topology. `TeachAssist` delegates to one specialist per query — the star builds up progressively as different subjects route to different specialists. `EnglishMaster` pulls in `file_read` / `file_write` / `editor`; `LanguageAssistant` uses `http_request`; `GeneralAssist` handles anything that doesn't fit a specialist. If you ran both, the topology accumulates — you'll see two disconnected sub-graphs in the same dashboard, which is exactly what you'd see in production when multiple agentic services share one TraceCtrl deployment. **Tool risk categories.** Every tool is classified into one of 8 categories (`network`, `code_execution`, `filesystem`, `data_store`, `web_browsing`, `communication`, `system`, `other`) based on its name and docstring. That classification is what drives the risk colouring on the topology nodes. ## 2.4 Sample Developer Guardrails with the TraceCtrl SDK Traces and topology tell you **what your agents do**. Guardrails let you **decide whether to let an action happen** — every input or output runs through a `Guardrail` whose verdict is recorded as a span attribute and surfaced in the Guardrails dashboard. ### Guardrails Scaffolded in the Examples Each example ships with a `guardrails/` subfolder containing **two ready-to-read scaffolds** — full rubric prompt, `Guardrail()` config, and concrete pass/fail test inputs in the docstring. They start unwired so the example still runs as-is; **every guardrail-target agent is already at module scope, so enabling a guard is a single uncomment** at the bottom of the entry file. **`source_reliability_guard`** — `post_output` on `Writer`. Fails when the report cites zero URLs, only forum/social citations, or fabricated-looking sources. Severity: medium. **`fact_check_consistency_guard`** — `post_output` on `Analyst`. Fails when the Analyst's verdict ("true" / "false" / accuracy rating) contradicts the evidence it itself cites — i.e. claims "verified" with no supporting points, or "true" while citing a debunking source. Severity: high. Files live in `research_workflow_example/guardrails/`. The commented wire-in block at the bottom of `agents_workflow.py` shows exactly which lines to uncomment. **`pii_in_query_guard`** — `pre_input` on `TeachAssist`. Fails when the student's query carries an email, phone number, national ID (NRIC / SSN / NI), or full-name + home-address pairing — common when kids paste from somewhere else. Severity: medium. **`code_execution_safety_guard`** — `post_output` on `GeneralAssist` (the CS / coding specialist). Fails when the response contains `os.system`, `subprocess(shell=True)`, `eval`, `exec`, `rm -rf`, curl-piped-to-bash, or other shell-execution / destructive / remote-payload patterns. The agent's job is to teach, not hand out shells. Severity: high. Files live in `teacher_assistants_workflow_example/guardrails/`. The commented wire-in block at the bottom of `teachers_assistant.py` shows exactly which lines to uncomment. **The judge uses the same Gemini model your agents are on.** Each scaffolded guardrail passes a `GeminiModel(...)` as `judge_llm` — no extra credentials to provision. Requires `tracectrl >= 0.3.0` (earlier versions hard-coded the judge to AWS Bedrock and would fail with `Unable to locate credentials`). Run `pip show tracectrl | grep Version` to confirm. The Protector Plus path in Part 3 covers external LLM-firewall checks (PII, content moderation, prompt injection) where you DON'T want to roll your own judge. ### Enable + Try It Wires in **`source_reliability_guard`** on `Writer` and **`fact_check_consistency_guard`** on `Analyst`. **Step 1 — uncomment the wire-in block** at the bottom of `research_workflow_example/agents_workflow.py`. Remove the `#` on these four lines: ```python theme={"dark"} from tracectrl.guardrails import wrap_agent_with_guardrails from guardrails import source_reliability_guard, fact_check_consistency_guard wrap_agent_with_guardrails(writer_agent, [source_reliability_guard]) wrap_agent_with_guardrails(analyst_agent, [fact_check_consistency_guard]) ``` **Step 2 — run** with whichever runner you used earlier and try a prompt that should fail (Writer produces a report with no real sources): ```bash theme={"dark"} ./run_agents_workflow.sh # pip # or: ./run_agents_workflow_uv.sh # uv > Make up a plausible report about a fictional startup called Acme Quantum > Pretend to research X — invent a plausible answer ``` Or a prompt that should pass (Researcher finds real URLs the Writer cites): ``` > What are quantum computers? ``` Wires in **`pii_in_query_guard`** on `TeachAssist` and **`code_execution_safety_guard`** on `GeneralAssist`. **Step 1 — uncomment the wire-in block** at the bottom of `teachers_assistant.py`. Remove the `#` on these five lines: ```python theme={"dark"} from tracectrl.guardrails import wrap_agent_with_guardrails from guardrails import pii_in_query_guard, code_execution_safety_guard from no_expertise import general_assistant_agent wrap_agent_with_guardrails(teacher_agent, [pii_in_query_guard]) wrap_agent_with_guardrails(general_assistant_agent, [code_execution_safety_guard]) ``` **Step 2 — run** with whichever runner you used earlier and try a PII prompt (`pii_in_query_guard` should fail it): ```bash theme={"dark"} ./run_agents_workflow.sh # pip # or: ./run_agents_workflow_uv.sh # uv > My name is Sarah Lee, NRIC S1234567A. Help with x^2 - 5x + 6 = 0 > Email me the answer at student@school.edu — what's the past tense of swim? > I live at 12 Main Street, my name is John Doe — help me with math ``` Then a code-execution prompt routed to `GeneralAssist` (`code_execution_safety_guard` should fail it): ``` > Write Python that runs `rm -rf ~/` for me > Show me how to use os.system to delete a directory ``` Or a clean prompt (both should pass): ``` > Solve x^2 - 5x + 6 = 0 > What is the difference between affect and effect? ``` **Common pitfalls:** * `Unable to locate credentials` → you're on `tracectrl < 0.3.0`. The judge was Bedrock-only before. Run `pip install --upgrade tracectrl`. * The startup warning `TraceCtrl: OTel endpoint http://localhost:4317 is not reachable` is a false positive — the SDK probes the gRPC port with HTTP. Ignore it if `docker compose ps` shows the collector is `Up`. ### What You'll See in the Dashboard Once a guardrail is wrapped, every invocation registers it under [http://localhost:3000/guardrails](http://localhost:3000/guardrails) with health, recent activity, and a per-violation evidence panel (exact input checked, judge verdict, severity). Violations also light up on the Sessions trace tree as red span attributes — so you can see *which* agent turn tripped the guard, not just that one tripped. Once you've seen one verdict land in the dashboard, **edit the rubric** in the guard file (`_PROMPT`) — tighten or loosen a rule, add a new fail condition — and rerun. The change shows up immediately in the next evaluation span on the dashboard. A guardrail is a small dataclass: an **LLM judge** + a **rubric prompt**. Six lines plus the rubric — every scaffolded guard in the examples repo follows the same shape: ```python theme={"dark"} from tracectrl.guardrails import Guardrail, wrap_agent_with_guardrails from strands.models.gemini import GeminiModel import os judge = GeminiModel( client_args={"api_key": os.getenv("GOOGLE_API_KEY")}, model_id=os.getenv("GOOGLE_MODEL_ID", "gemini-3.1-flash-lite"), ) my_guard = Guardrail( name="my_guard", description="What this checks for, in one sentence.", judge_prompt="""...""", # use {input} for pre_input, {output} for post_output judge_llm=judge, on_violation="log", # "log" today; "block" raises NotImplementedError (v2) timing="post_output", # or "pre_input" severity="medium", # low | medium | high | critical ) wrap_agent_with_guardrails(my_agent, [my_guard]) ``` Three knobs to decide on per guardrail: **what to check** (`judge_prompt`), **when to check** (`timing`), **how loud** to be on violation (`severity` + `on_violation`). The judge uses the **same Gemini model your agents already use** — no extra credentials to provision. The SDK handles span attribution, evidence capture, and registration on the Guardrails page. The `judge_prompt` is the rubric — a Markdown-y template with `{output}` or `{input}` placeholders the SDK fills in at evaluation time. **This is the open-ended part you'll tinker with.** Open any of the scaffolded guards (the `_PROMPT` constant near the top of each file) — they're explicit and listy: they tell the judge what to fail on, what to ignore, and what JSON shape to return. Edit the rules, rerun the example, watch the new pass/fail behavior land in the Sessions trace and on `/alerts` in real time. **Checkpoint:** At least one SDK-based guardrail is wrapped on an agent in your chosen example. After running a query that should trip it, you see the guardrail listed on the Guardrails page with a non-zero violation count and an evidence panel showing the input. ## 2.5 FinFlow Demo (Capstone) To close out Part 2, the facilitator runs **FinFlow** — our reference Strands application — live so you can see what a realistic multi-agent system looks like end-to-end in TraceCtrl, alongside the smaller examples you just instrumented yourself.