Skip to content

Commit dfae345

Browse files
Zie619claude
andcommitted
docs(sdk): [29.8] update interceptor docs with axios, undici, env vars, ESM/CJS
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 914fc7b commit dfae345

File tree

4 files changed

+140
-16
lines changed

4 files changed

+140
-16
lines changed

BIBLE.md

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,9 @@ client.track({ type: EventType.TOOL_CALL, name: 'search', payload: {} });
252252
```
253253

254254
**Modules**: `client.ts`, `events.ts`, `cedar.ts`, `interceptor.ts`, `standalone.ts`
255-
**Build**: `tsc` (TypeScript), outputs to `dist/`
255+
**Interception**: `fetch` (always), `axios` (optional), `undici` (optional) -- auto-detected at install-time
256+
**Integrations**: LangChain.js (`TruseraLangChainHandler` with optional Cedar enforcement)
257+
**Build**: `tsup` -- dual ESM (`dist/index.js`) + CJS (`dist/index.cjs`) with `.d.ts` declarations
256258
**Test**: `vitest`
257259

258260
### Go SDK (`trusera-sdk-go/`)
@@ -267,8 +269,9 @@ client.Track(trusera.Event{Type: trusera.ToolCall, Name: "search"})
267269

268270
**Modules**: `trusera.go`, `events.go`, `cedar.go`, `interceptor.go`, `standalone.go`
269271
**Build**: standard Go modules (`go.mod` points to `github.com/Trusera/ai-bom/trusera-sdk-go`)
270-
**Test**: `go test ./...`
272+
**Test**: `go test ./...` (CI gate in auto-release.yml runs tests before tagging)
271273
**Version**: git tag only (`trusera-sdk-go/vX.Y.Z`), no version file
274+
**Env vars**: `TRUSERA_API_KEY` (fallback for empty apiKey), `TRUSERA_API_URL` (fallback for base URL)
272275

273276
---
274277

docs/interceptor-sdks.md

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -69,14 +69,15 @@ Choose the SDK that matches your agent's language:
6969
|---------|--------|------------|-----|
7070
| **Package name** | `trusera-sdk` | `trusera-sdk` | `trusera-sdk-go` |
7171
| **Install command** | `pip install trusera-sdk` | `npm install trusera-sdk` | `go get github.com/Trusera/ai-bom/trusera-sdk-go` |
72-
| **HTTP Interception** | `@monitor` decorator | `fetch` monkey-patch | `http.RoundTripper` wrapper |
72+
| **HTTP Interception** | `@monitor` decorator | `fetch` + `axios` + `undici` | `http.RoundTripper` wrapper |
7373
| **LangChain Integration** | `TruseraCallbackHandler` | `TruseraLangChainHandler` | -- |
7474
| **CrewAI Integration** | `TruseraCrewCallback` (StepCallback) | -- | -- |
7575
| **AutoGen Integration** | `TruseraAutoGenHook` (MessageHook) | -- | -- |
7676
| **Enforcement Modes** | `log` / `warn` / `block` | `log` / `warn` / `block` | `log` / `warn` / `block` |
7777
| **Event Batching** | Thread-based queue | Timer-based queue | Goroutine-based queue |
7878
| **Async Support** | `asyncio` native | Native `Promise` / `async-await` | Goroutines |
79-
| **External Dependencies** | `httpx` | None (native `fetch`) | None (stdlib only) |
79+
| **Module Format** | -- | ESM + CJS (dual output via tsup) | -- |
80+
| **External Dependencies** | `httpx` | None (native `fetch`); optional `axios`, `undici` | None (stdlib only) |
8081
| **Min Runtime** | Python 3.9+ | Node.js 18+ | Go 1.21+ |
8182
| **Type Safety** | Type hints (mypy) | Full TypeScript generics | Static typing |
8283
| **Context Manager** | `with` statement | -- | `defer client.Close()` |
@@ -151,10 +152,14 @@ decorated function is called, the SDK captures input arguments, measures executi
151152
time, records the return value (or exception), and queues an event. A background
152153
thread flushes events to the Trusera API at configurable intervals.
153154

154-
**TypeScript** -- The `TruseraInterceptor` replaces the global `fetch` function with
155-
a wrapper that captures request URL, method, headers, and body. After the real
156-
request completes, the SDK records the response status and queues an event. A
157-
`setInterval` timer drives periodic flushes.
155+
**TypeScript** -- The `TruseraInterceptor` patches up to three HTTP libraries
156+
automatically: native `fetch` (always available), `axios` (via request/response
157+
interceptors), and `undici` (via monkey-patching `request` and `fetch`). Libraries
158+
are detected at install-time using `require()` -- if absent, they are silently
159+
skipped. Each intercepted call captures URL, method, headers, and body; after the
160+
real request completes the SDK records the response status and queues an event. A
161+
`setInterval` timer drives periodic flushes. The SDK ships as both ESM and CJS
162+
(built with tsup) so it works in any Node.js or Bun environment.
158163

159164
**Go** -- The SDK provides a custom `http.RoundTripper` that wraps the standard
160165
`http.Transport`. Every request passing through the wrapped `http.Client` is
@@ -293,8 +298,36 @@ await model.invoke("What are the top AI security risks?");
293298
await client.close();
294299
```
295300

301+
**With Cedar Policy Enforcement**:
302+
303+
The handler supports optional Cedar policy enforcement for tool and LLM calls.
304+
Pass `enforcement` and a `cedarEvaluator` to activate runtime policy checks:
305+
306+
```typescript
307+
import {
308+
TruseraClient,
309+
TruseraLangChainHandler,
310+
CedarEvaluator,
311+
} from "trusera-sdk";
312+
313+
const evaluator = new CedarEvaluator();
314+
await evaluator.loadPolicy(`
315+
forbid (principal, action == Action::"*", resource)
316+
when { resource.hostname == "langchain" };
317+
`);
318+
319+
const handler = new TruseraLangChainHandler(client, {
320+
enforcement: "block", // or "warn" or "log"
321+
cedarEvaluator: evaluator,
322+
});
323+
324+
// In block mode, denied tool/LLM calls throw:
325+
// Error: [Trusera] Policy violation: tool search denied - ...
326+
```
327+
296328
**What gets tracked**: Same event types as the Python LangChain integration --
297-
`LLM_INVOKE`, `TOOL_CALL`, and `DECISION` events.
329+
`LLM_INVOKE`, `TOOL_CALL`, and `DECISION` events. When enforcement is active,
330+
`POLICY_VIOLATION` events are also tracked for denied actions.
298331

299332
---
300333

@@ -1035,11 +1068,16 @@ client := trusera.NewClient("tsk_your_api_key",
10351068

10361069
| Option Function | Type | Default | Description |
10371070
|----------------|------|---------|-------------|
1038-
| `WithBaseURL(url)` | `string` | `https://api.trusera.io` | API base URL |
1071+
| `WithBaseURL(url)` | `string` | env `TRUSERA_API_URL` or `https://api.trusera.io` | API base URL |
10391072
| `WithAgentID(id)` | `string` | `""` | Pre-registered agent ID |
10401073
| `WithFlushInterval(d)` | `time.Duration` | `5s` | Duration between flushes |
10411074
| `WithBatchSize(n)` | `int` | `100` | Maximum events per batch |
10421075

1076+
**Environment Variable Fallbacks**: If the `apiKey` argument is empty,
1077+
`NewClient` reads `TRUSERA_API_KEY`. The default base URL is read from
1078+
`TRUSERA_API_URL` (falling back to `https://api.trusera.io`). Explicit
1079+
`WithBaseURL()` overrides the environment variable.
1080+
10431081
**Interceptor Options**:
10441082

10451083
| Field | Type | Default | Description |
@@ -1124,7 +1162,7 @@ identically in the Trusera dashboard.
11241162

11251163
**Key differences**:
11261164
- TypeScript `flush()` and `close()` return Promises; always `await` them.
1127-
- The TypeScript SDK uses `fetch` interception instead of a decorator pattern.
1165+
- The TypeScript SDK intercepts `fetch`, `axios`, and `undici` automatically.
11281166
Wrap tool functions manually with `createEvent()` if you need per-function tracking.
11291167
- CrewAI and AutoGen integrations are Python-only.
11301168

trusera-sdk-go/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,29 @@ event := trusera.NewEvent(trusera.EventDecision, "approve_transaction").
186186

187187
## Configuration Options
188188

189+
### Environment Variables
190+
191+
The Go SDK reads configuration from environment variables when explicit values
192+
are not provided:
193+
194+
| Variable | Description | Default |
195+
|----------|-------------|---------|
196+
| `TRUSERA_API_KEY` | API key (used when `apiKey` argument is `""`) | (none) |
197+
| `TRUSERA_API_URL` | Base URL for the Trusera API | `https://api.trusera.io` |
198+
199+
```bash
200+
export TRUSERA_API_KEY=tsk_your_api_key
201+
export TRUSERA_API_URL=https://api.trusera.io
202+
```
203+
204+
```go
205+
// Reads TRUSERA_API_KEY and TRUSERA_API_URL from environment
206+
client := trusera.NewClient("")
207+
defer client.Close()
208+
```
209+
210+
Explicit values always take precedence over environment variables.
211+
189212
### Client Options
190213

191214
```go

trusera-sdk-js/README.md

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,10 @@ The official TypeScript/JavaScript SDK for monitoring AI agents with [Trusera](h
77

88
## Key Features
99

10-
- **Transparent HTTP Interception**: Zero-code instrumentation of all outbound HTTP calls
10+
- **Transparent HTTP Interception**: Zero-code instrumentation via `fetch`, `axios`, and `undici`
1111
- **Policy Enforcement**: Runtime evaluation against Cedar policies with configurable enforcement modes
12-
- **LangChain.js Integration**: First-class support for LangChain.js callbacks
12+
- **LangChain.js Integration**: First-class support for LangChain.js callbacks with optional Cedar enforcement
13+
- **ESM + CJS**: Dual-format output (built with tsup) -- works in any Node.js or Bun environment
1314
- **Rich Event Tracking**: Track LLM calls, tool executions, data access, and custom events
1415
- **Batched Transmission**: Automatic event batching and retry logic
1516
- **Type-Safe**: Full TypeScript support with strict typing
@@ -74,6 +75,54 @@ await model.invoke("What are the top AI security risks?");
7475
await client.close();
7576
```
7677

78+
### Axios and Undici Interception
79+
80+
The interceptor automatically detects and patches `axios` and `undici` if they
81+
are installed. No additional configuration is needed:
82+
83+
```typescript
84+
import axios from "axios";
85+
import { TruseraClient, TruseraInterceptor } from "trusera-sdk";
86+
87+
const client = new TruseraClient({ apiKey: "tsk_xxx" });
88+
const interceptor = new TruseraInterceptor();
89+
interceptor.install(client, { enforcement: "warn" });
90+
91+
// axios requests are now tracked automatically
92+
await axios.get("https://api.openai.com/v1/models");
93+
94+
// undici requests too (if undici is installed)
95+
// import { request } from "undici";
96+
// await request("https://api.openai.com/v1/models");
97+
98+
await client.close();
99+
interceptor.uninstall();
100+
```
101+
102+
Libraries are detected via `require()` at install-time. If a library is not
103+
installed, it is silently skipped with no errors.
104+
105+
### LangChain.js with Cedar Enforcement
106+
107+
Add Cedar policy enforcement to tool and LLM calls:
108+
109+
```typescript
110+
import { TruseraClient, TruseraLangChainHandler, CedarEvaluator } from "trusera-sdk";
111+
112+
const evaluator = new CedarEvaluator();
113+
await evaluator.loadPolicy(`
114+
forbid (principal, action == Action::"*", resource)
115+
when { resource.hostname == "langchain" };
116+
`);
117+
118+
const handler = new TruseraLangChainHandler(client, {
119+
enforcement: "block",
120+
cedarEvaluator: evaluator,
121+
});
122+
123+
// Denied tool/LLM calls throw in block mode
124+
```
125+
77126
### Manual Event Tracking
78127

79128
For custom instrumentation:
@@ -282,17 +331,28 @@ The SDK tracks six core event types:
282331

283332
#### Methods
284333

285-
- `install(client: TruseraClient, options?: InterceptorOptions): void`: Install HTTP interceptor
286-
- `uninstall(): void`: Restore original fetch and remove interceptor
334+
- `install(client: TruseraClient, options?: InterceptorOptions): void`: Install HTTP interceptor for `fetch`, `axios` (if available), and `undici` (if available)
335+
- `uninstall(): void`: Restore original fetch, eject axios interceptors, and restore undici functions
287336

288337
### `TruseraLangChainHandler`
289338

290339
#### Methods
291340

292-
- `constructor(client: TruseraClient)`: Create handler for LangChain callbacks
341+
- `constructor(client: TruseraClient, options?: LangChainHandlerOptions)`: Create handler for LangChain callbacks with optional Cedar enforcement
293342
- `getPendingEventCount(): number`: Get count of incomplete events
294343
- `clearPendingEvents(): void`: Clear all pending events
295344

345+
#### LangChainHandlerOptions
346+
347+
```typescript
348+
interface LangChainHandlerOptions {
349+
enforcement?: "block" | "warn" | "log";
350+
cedarEvaluator?: CedarEvaluator;
351+
}
352+
```
353+
354+
When `enforcement` is `"block"` and a Cedar policy denies a tool/LLM call, the handler throws an `Error`. In `"warn"` mode it logs via `console.warn`. In `"log"` mode (default) violations are tracked silently.
355+
296356
### Utility Functions
297357

298358
- `createEvent(type: EventType, name: string, payload?, metadata?): Event`: Create a well-formed event

0 commit comments

Comments
 (0)