> ## Documentation Index
> Fetch the complete documentation index at: https://docs.centure.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK Reference

> Complete API reference for the Centure Node.js SDK

This page documents the types, methods, and configuration options available in the `@centure/node-sdk` package.

## Client Methods

### scanText

Scans text content for prompt injection attempts.

```typescript theme={null}
async scanText(text: string): Promise<ScanResponse>
```

**Parameters:**

* `text` (string) - The text content to scan

**Returns:** `Promise<ScanResponse>`

**Throws:**

* `BadRequestError` - Invalid request format
* `UnauthorizedError` - Invalid or missing API key
* `MissingApiKeyError` - No API key provided

### scanImage

Scans images for text-based prompt injection attempts.

```typescript theme={null}
async scanImage(image: string | Buffer): Promise<ScanResponse>
```

**Parameters:**

* `image` (string | Buffer) - Base64-encoded image string or Buffer object

**Returns:** `Promise<ScanResponse>`

**Throws:**

* `BadRequestError` - Invalid image format
* `UnauthorizedError` - Invalid or missing API key
* `PayloadTooLargeError` - Image exceeds size limit
* `MissingApiKeyError` - No API key provided

## Response Types

### ScanResponse

The response object returned by all scan methods.

```typescript theme={null}
interface ScanResponse {
  is_safe: boolean;
  categories: DetectedCategory[];
  request_id: string;
  api_key_id: string;
  request_units: number;
  billed_request_units: number;
  service_tier: ServiceTier;
}
```

**Fields:**

<ResponseField name="is_safe" type="boolean" required>
  Indicates whether the content is safe. `false` means prompt injection was detected.
</ResponseField>

<ResponseField name="categories" type="DetectedCategory[]" required>
  Array of detected threat categories with confidence levels. Empty array when `is_safe` is `true`.
</ResponseField>

<ResponseField name="request_id" type="string" required>
  Unique identifier for this scan request. Use this for tracking and support inquiries.
</ResponseField>

<ResponseField name="api_key_id" type="string" required>
  The ID of the API key used for this request.
</ResponseField>

<ResponseField name="request_units" type="number" required>
  Number of request units consumed by this scan operation.
</ResponseField>

<ResponseField name="billed_request_units" type="number" required>
  Number of request units billed for this scan. May differ from `request_units` when discounts apply.
</ResponseField>

<ResponseField name="service_tier" type="ServiceTier" required>
  The service tier associated with your API key.
</ResponseField>

**Example:**

```json theme={null}
{
  "is_safe": false,
  "categories": [
    {
      "code": "context_injection",
      "confidence": "high"
    },
    {
      "code": "output_manipulation",
      "confidence": "medium"
    }
  ],
  "request_id": "req_abc123xyz",
  "api_key_id": "key_def456uvw",
  "request_units": 1,
  "billed_request_units": 1,
  "service_tier": "standard"
}
```

### DetectedCategory

Represents a detected threat with its confidence level.

```typescript theme={null}
interface DetectedCategory {
  code: ThreatCategory;
  confidence: ConfidenceLevel;
}
```

**Fields:**

<ResponseField name="code" type="ThreatCategory" required>
  The type of threat detected. See [Threat Categories](#threat-categories) below.
</ResponseField>

<ResponseField name="confidence" type="ConfidenceLevel" required>
  Confidence level of the detection: `"low"`, `"medium"`, or `"high"`.
</ResponseField>

## Threat Categories

The SDK detects the following threat categories. Each corresponds to a specific attack pattern.

<Info>
  See the [Risk Classifications](/security/risk-classifications) page for detailed explanations of each category.
</Info>

```typescript theme={null}
type ThreatCategory =
  | "output_manipulation"
  | "context_injection"
  | "data_exfiltration"
  | "unauthorized_actions";
```

| Category               | Description                                                |
| ---------------------- | ---------------------------------------------------------- |
| `output_manipulation`  | Attempts to control output format, content, or style       |
| `context_injection`    | Injection of fake context, roles, or instruction overrides |
| `data_exfiltration`    | Attempts to extract sensitive data                         |
| `unauthorized_actions` | Attempts to trigger unauthorized actions or API calls      |

## Confidence Levels

Confidence levels indicate the detection certainty:

```typescript theme={null}
type ConfidenceLevel = "low" | "medium" | "high";
```

* **`high`** - Strong indicators of prompt injection. Block these requests.
* **`medium`** - Moderate indicators. Consider additional validation or monitoring.
* **`low`** - Weak indicators. May require context-specific handling.

<Tip>
  Block all `high` confidence detections in production. Apply additional scrutiny to `medium` confidence results based on your risk tolerance.
</Tip>

## Service Tiers

Service tiers determine rate limits and features available to your API key:

```typescript theme={null}
type ServiceTier = "low" | "standard" | "dedicated";
```

## Client Configuration

### Constructor Options

```typescript theme={null}
interface CentureClientOptions {
  apiKey?: string;
  baseUrl?: string;
  fetch?: typeof fetch;
  fetchOptions?: RequestInit;
}
```

**Options:**

<ResponseField name="apiKey" type="string">
  Your Centure API key. If not provided, the client reads from the `CENTURE_API_KEY` environment variable.
</ResponseField>

<ResponseField name="baseUrl" type="string" default="https://api.centure.ai">
  The base URL for the Centure API. Override this for testing or custom deployments.
</ResponseField>

<ResponseField name="fetch" type="typeof fetch">
  Custom fetch implementation. Use this to provide a different fetch function (e.g., `node-fetch` for older Node.js versions).
</ResponseField>

<ResponseField name="fetchOptions" type="RequestInit">
  Additional options passed to all fetch requests. Use this to set custom headers, timeouts, or other request parameters.
</ResponseField>

### Configuration Examples

**Custom timeout:**

```typescript theme={null}
const client = new CentureClient({
  apiKey: "your-api-key",
  fetchOptions: {
    timeout: 30000, // 30 seconds
  },
});
```

**Custom headers:**

```typescript theme={null}
const client = new CentureClient({
  apiKey: "your-api-key",
  fetchOptions: {
    headers: {
      "X-Custom-Header": "value",
    },
  },
});
```

**Custom fetch implementation:**

```typescript theme={null}
import fetch from "node-fetch";

const client = new CentureClient({
  apiKey: "your-api-key",
  fetch: fetch as any,
});
```

**Testing environment:**

```typescript theme={null}
const client = new CentureClient({
  apiKey: "test-api-key",
  baseUrl: "http://localhost:3001",
});
```

## Error Classes

The SDK provides specific error classes for different failure scenarios:

```typescript theme={null}
import {
  BadRequestError,
  UnauthorizedError,
  PayloadTooLargeError,
  MissingApiKeyError,
} from "@centure/node-sdk";
```

| Error Class            | HTTP Status | Description                                   |
| ---------------------- | ----------- | --------------------------------------------- |
| `MissingApiKeyError`   | N/A         | No API key provided in options or environment |
| `UnauthorizedError`    | 401         | Invalid or expired API key                    |
| `BadRequestError`      | 400         | Invalid request format or parameters          |
| `PayloadTooLargeError` | 413         | Image exceeds maximum size limit              |

**Error handling pattern:**

```typescript theme={null}
try {
  const result = await client.scanText(userInput);

  if (!result.is_safe) {
    // Handle unsafe content
    console.log("Threats detected:", result.categories);
  }
} catch (error) {
  if (error instanceof UnauthorizedError) {
    // Handle authentication error
  } else if (error instanceof BadRequestError) {
    // Handle validation error
  } else if (error instanceof PayloadTooLargeError) {
    // Handle size limit error
  } else {
    // Handle unexpected errors
  }
}
```

## TypeScript Support

The SDK includes full TypeScript definitions. All types are exported for use in your application:

```typescript theme={null}
import type {
  ScanResponse,
  DetectedCategory,
  ThreatCategory,
  ConfidenceLevel,
  ServiceTier,
} from "@centure/node-sdk";

function handleScanResult(result: ScanResponse): void {
  if (!result.is_safe) {
    result.categories.forEach((category: DetectedCategory) => {
      console.log(`Threat: ${category.code} (${category.confidence})`);
    });
  }
}
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Quickstart" icon="rocket" href="/sdk/nodejs-quickstart">
    Return to the quickstart guide for installation and basic usage
  </Card>

  <Card title="MCP Integration" icon="plug" href="/sdk/nodejs-mcp">
    Secure Model Context Protocol applications with the SDK
  </Card>
</CardGroup>
