# @wardnmesh/sdk-node

> **Latest Version: v0.4.5** (Released 2026-01-19)

**WardnMesh.AI** (formerly AgentGuard) is an active defense middleware for AI Agents. This SDK allows you to verify LLM inputs/outputs, block prompt injections, and prevent data exfiltration in real-time.

## ✨ What's New in v0.4.0

🚨 **Breaking Changes**: Action-based architecture replaces boolean `allowed` field.

- ✅ **Granular Actions**: `block`, `confirm`, `warn`, `log`, `allow` instead of `true`/`false`
- ✅ **Confirmation Support**: Native user confirmation for high-risk operations
- ✅ **Enhanced Context**: Richer violation metadata with `recommendedAction` and `scope`
- ✅ **Fail-Closed Security**: Defensive design defaults to `'block'` on invalid states

📖 [Migration Guide](MIGRATION_v0.4.0.md) | [CHANGELOG](CHANGELOG.md)

## Features

- 🛡️ **Active Defense**: Blocks prompt injections, jailbreaks, and PII leaks.
- ⚡ **Middleware First**: Easy integration with Express and Next.js.
- 🔍 **Telemetry**: Real-time violation reporting to Central Control Bus (CCB).
- 🧠 **Context Aware**: Tracks tool usage history to detect multi-step attacks (Sequence Detection).
- 🚀 **Fail-Open**: Designed to prioritize application availability (blocks are logged, errors are ignored by default).

## Installation

```bash
npm install @wardnmesh/sdk-node@latest
# or
yarn add @wardnmesh/sdk-node@latest
```

## v0.4.0 API Overview

The new action-based API provides fine-grained control over threat responses:

```typescript
import { Wardn } from '@wardnmesh/sdk-node';

const guard = Wardn.getInstance();
const result = await guard.scan({ prompt: userInput });

// Handle different threat levels
switch (result.action) {
  case 'block':
    // Critical violation - deny immediately
    throw new Error('Security violation');

  case 'confirm':
    // High-risk - request user approval
    const approved = await getUserConfirmation(result.confirmationDetails);
    if (!approved) throw new Error('Operation denied');
    break;

  case 'warn':
    // Medium-risk - log warning and allow
    console.warn('Security warning:', result.violations);
    break;

  case 'log':
    // Low-risk - log for monitoring
    console.log('Security event:', result.violations);
    break;

  case 'allow':
    // No violations - safe to proceed
    break;
}

// Continue with your logic...
```

### Confirmation Dialog Example

When `action === 'confirm'`, the SDK provides pre-formatted confirmation context:

```typescript
if (result.action === 'confirm') {
  const { message, timeout, defaultAction } = result.confirmationDetails;

  console.log(message);
  // ⚠️ Security Alert
  // Rule: recursive_delete
  // Severity: HIGH
  // Description: Detected dangerous recursive delete operation

  const approved = await getUserInput(); // Your confirmation UI
  if (!approved) throw new Error('Operation denied by user');
}
```

## Quick Start

### 1. Initialize the Guard

Initialize the singleton `Wardn` instance at the start of your application.

```typescript
import Wardn, { Rule, RiskLevel } from '@wardnmesh/sdk-node';

const rules: Rule[] = [
  {
    id: 'block-aws-keys',
    name: 'Block AWS Keys',
    category: 'safety',
    severity: 'critical',
    description: 'Prevents leakage of AWS Access Keys',
    detector: {
      type: 'pattern',
      config: {
        targetTool: 'llm_output', 
        targetParameter: 'content',
        patterns: [
          { name: 'AWS Key ID', regex: 'AKIA[0-9A-Z]{16}', description: 'AWS Access Key ID' }
        ]
      }
    },
    escalation: { 1: 'block' }
  }
];

// Initialize (Singleton)
const guard = Wardn.init({
  rules,
  enabled: true,
  maxHistorySize: 50, // Limit memory usage
  telemetry: {
    enabled: true,
    serviceName: 'my-agent-service'
  }
});
```

### 2. Usage with Express

Use the `createExpressMiddleware` to automatically scan incoming requests.

```typescript
import express from 'express';
import { createExpressMiddleware } from '@wardnmesh/sdk-node';

const app = express();

// IMPORTANT: body-parser or express.json() must be used BEFORE WardnMesh
app.use(express.json());

// Apply Middleware
app.use(createExpressMiddleware(guard, {
  // Optional: Custom request extraction
  extractRequest: (req) => ({
    sessionId: req.headers['x-session-id'] as string,
    prompt: req.body.user_prompt
  }),
  // Optional: Custom block handler
  onBlock: (req, res, result) => {
    res.status(400).json({ error: 'Security Violation Detected', violations: result.violations });
  }
}));

app.post('/chat', (req, res) => {
  // If we reach here, the request is safe!
  res.json({ response: 'Hello world' });
});

app.listen(3000);
```

### 3. Usage with Next.js (App Router)

Wrap your API Route handlers with `withAgentGuard`.

```typescript
// app/api/chat/route.ts
import { NextResponse } from 'next/server';
import { withAgentGuard } from '@wardnmesh/sdk-node';
import { guard } from '@/lib/wardn'; // Import your initialized guard instance

export const POST = withAgentGuard(guard, async (req) => {
  const body = await req.json();
  // Process request...
  return NextResponse.json({ message: 'Safe!' });
});
```

## Configuration

### `WardnConfig`

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `rules` | `Rule[]` | Required | Array of active security rules. |
| `enabled` | `boolean` | `true` | Master switch for the SDK. |
| `maxHistorySize` | `number` | `50` | Max tool calls to keep in session state (prevents memory bloat). |
| `telemetry.enabled` | `boolean` | `false` | Enable sending data to CCB. |
| `telemetry.serviceName` | `string` | `unknown` | Identifier for this service. |

### Interactive Setup (Recommended)

Run the initialization wizard to automatically configure telemetry and generate your `.env` file:

```bash
npx wardn-init
```

### Environment Variables

| Variable | Description |
|----------|-------------|
| `WARDN_API_KEY` | **Required** for telemetry. Get yours at <https://wardnmesh.ai> |
| `WARDN_API_URL` | Optional. Defaults to `https://api.wardnmesh.ai` |
| `WARDN_TELEMETRY_ENABLED` | Set to `true` to enable cloud syncing. |

## Custom State Management

By default, `Wardn` uses an in-memory state provider. For production (serverless/distributed), implement `SessionStateProvider`:

```typescript
import { SessionStateProvider } from '@wardnmesh/sdk-node';

class RedisStateProvider implements SessionStateProvider {
  // ... implement getState and setState using Redis
}

Wardn.init(config, new RedisStateProvider());
```

## Other Integration Options

### For Claude Code & Claude Desktop

If you're using **Claude Code CLI** or **Claude Desktop**, use the **WardnMesh MCP Server** instead of this SDK:

```bash
npm install -g @wardnmesh/mcp-server
```

The MCP Server provides:
- 🔧 **Auto-setup** for Claude Code hooks
- 🛡️ **Real-time scanning** of user prompts and tool arguments
- 🔍 **Security checks** for Bash commands, file operations, and content

**Learn more:** [MCP Server Documentation](../mcp-server/README.md)

### For Other Platforms

- **OpenAI API**: Use this SDK with custom middleware
- **LangChain**: Use this SDK with callback handlers
- **CrewAI**: Use the Python SDK (`pip install wardnmesh`)
- **Cursor/VS Code**: Coming soon - MCP Server integration
