# @centure/node-sdk 中文文档

规范地址：https://npmcn.com/package/%40centure/node-sdk/

版本：0\.1\.0
npm 元数据更新时间：2025-12-11T01:31:05.399Z
中文译文更新时间：2026-11-09T07:53:03.061Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40centure/node-sdk
原文对照：https://npmcn.com/package/%40centure/node-sdk/?lang=original
项目主页：https://github.com/centure-ai/typescript-sdk#readme
源码仓库：https://github.com/centure-ai/typescript-sdk

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：74 kB，31 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2025-11-07T02:28:43.484Z
- 最新版本发布：2025-12-11T01:31:05.000Z
- 近 30 天下载量：4587（2026-10-10 至 2026-11-08，npm 官方下载统计）
- 已发布版本数：2（近 12 个月 1 个）

## 中文简介

用于与 Centure 的 API 交互的 Typescript SDK

## 安装

```sh
npm install @centure/node-sdk
```

也可以使用：`pnpm add @centure/node-sdk`、`yarn add @centure/node-sdk`、`bun add @centure/node-sdk`

## README

# @centure/node-sdk (英语)

一个完全型式安全的TypeScript SDK,用于与Centure的API交互,用于即时注射检测.

## 安装

```bash
npm install @centure/node-sdk
```

## 使用量

### 初始化客户端

```typescript
import { CentureClient } from "@centure/node-sdk";

// Using environment variable CENTURE_API_KEY
const client = new CentureClient();

// Or provide API key directly
const client = new CentureClient({
  apiKey: "your-api-key",
  baseUrl: "https://api.centure.ai", // Optional, defaults to production
});
```

### 扫描快速注射的文本

```typescript
const result = await client.scanText("Your text content here");

console.log("Is safe:", result.is_safe);
console.log("Detected categories:", result.categories);
console.log("Reason:", result.reason); // Explanation when flagged
console.log("Request ID:", result.request_id);
```

### 扫描选项

两者 `scanText` 财务报告和审定财务报表 `scanImage` 接受选项 `ScanOptions` 参数 :

```typescript
// Only scan for specific categories
const result = await client.scanText("content", {
  only: ["data_exfiltration", "unauthorized_actions"],
});

// Exclude certain categories
const result = await client.scanText("content", {
  exclude: ["output_manipulation"],
});

// Set minimum confidence threshold
const result = await client.scanText("content", {
  minimum_confidence: "high",
});
```

#### 扫描选项

所有选项都是可选的.

| 参数 | 类型 | 说明 |
| --- | --- | --- |
| `only` | `RiskCategory[]?` | 只有这些类别的返回检测。 无法使用 `exclude`。 。 。 . |
| `exclude` | `RiskCategory[]?` | 不包括这些类别的检测。 无法使用 `only`。 。 。 . |
| `minimum_confidence` | `"medium"` | `"high"?` | 检测的最低信任水平. |

### 扫描图像( Base64 或缓冲)

```typescript
// Using base64 string
const base64Image = "iVBORw0KGgoAAAANSUhEUgAA...";
const result = await client.scanImage(base64Image);

console.log("Is safe:", result.is_safe);
console.log("Detected threats:", result.categories);
```

```typescript
// Using Buffer (Node.js) - automatically converted to base64
import fs from "fs";

const imageBuffer = fs.readFileSync("./image.png");
const result = await client.scanImage(imageBuffer);
```

## API 反应

所有扫描方法返回 a `ScanResponse` 对象 :

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

interface DetectedCategory {
  code: ThreatCategory;
  confidence: ConfidenceLevel;
}
```

| 外地 | 类型 | 说明 |
| --- | --- | --- |
| `is_safe` | `boolean` | 内容是否安全( 未发现快速注射) |
| `categories` | `DetectedCategory[]` | 查明的威胁类别清单 |
| `reason` | `string?` | 标出内容时的解释 |
| `request_id` | `string` | 此请求的独有标识符 |
| `api_key_id` | `string` | 使用的 API 密钥的标识 |
| `request_units` | `number` | 使用的请求单位数目 |
| `billed_request_units` | `number` | 申请单位数目 |
| `service_tier` | `ServiceTier` | 用于请求的服务级别 |

## MCP 一体化

SDK提供运输包装 [示范背景协议(MCP)](https://modelcontextprotocol.io/) 自动扫描消息进行快速注射攻击.

### CentureMCPCnition Transport 百分数运输

这个 `CentureMCPClientTransport` 包入任何 MCP 传输并截取信件, 在信件到达您的 MCP 服务器前扫描它们的安全威胁 .

#### 基本用途

```typescript
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { CentureClient } from "@centure/node-sdk";
import { CentureMCPClientTransport } from "@centure/node-sdk/mcp";

// Create your underlying MCP transport
const stdioTransport = new StdioClientTransport({
  command: "your-mcp-server",
  args: ["--arg1", "--arg2"],
});

// Wrap it with Centure security scanning
const secureTransport = new CentureMCPClientTransport({
  client: new CentureClient({
    apiKey: "your-api-key",
  }),
  transport: stdioTransport,
});

// Use with MCP client
const client = new Client({
  name: "your-client",
  version: "1.0.0",
});

await client.connect(secureTransport);
```

#### 配置参数

##### 所需参数

-   **`transport`** (单位:千美元)`Transport`:基本MCP包装运输(如:StioClient Transport、SSEClient Transport)
-   **`client`** (单位:千美元)`CentureClient`: 扫描信件的Centure API客户端实例

##### 可选钩

-   **`shouldScanMessage`** (单位:千美元)`(context: ShouldScanMessageContext) => boolean | ShouldScanMessageResult`:
    
    确定是否应该扫描特定信件。 返回时 `false` 或者说 `{ scan: false }` 以跳过扫描.
    
    ```typescript
    shouldScanMessage: ({ message, extra }) => {
      // Skip scanning for tool list requests
      if (message.method === "tool/list") {
        return false;
      }
      return true;
    };
    ```
    
-   **`onAfterScan`** (单位:千美元)`(context: OnAfterScanContext) => void | OnAfterScanResult`:
    
    消息扫描后呼叫, 不管结果如何. 可以回来 `{ passthrough: true }` 即使不安全,也允许信件.
    
    ```typescript
    onAfterScan: ({ message, scanResult }) => {
      console.log(`Scanned ${message.method}: ${scanResult.is_safe}`);
    };
    ```
    
-   **`onUnsafeMessage`** (单位:千美元)`(context: OnUnsafeMessageContext) => OnUnsafeMessageResult`:
    
    检测到不安全消息时调用 。 必须返回指定是允许还是屏蔽消息的对象 .
    
    ```typescript
    onUnsafeMessage: ({ message, scanResult }) => {
      // Allow medium-confidence threats
      const isMedium = scanResult.categories.every(
        (c) => c.confidence === "medium",
      );
    
      if (isMedium) {
        return { passthrough: true };
      }
    
      // Block high-confidence threats with custom error
      return {
        passthrough: false,
        replace: {
          jsonrpc: "2.0",
          id: message.id,
          error: {
            code: -32001,
            message: "Security violation detected",
          },
        },
      };
    };
    ```
    
-   **`onBeforeSend`** (单位:千美元)`(context: { message: JSONRPCMessage, extra?: MessageExtraInfo }) => void`:
    
    在通过运输发送任何信息之前已打电话.
    
    ```typescript
    onBeforeSend: ({ message, extra }) => {
      console.log(`Sending ${message.method}`);
    };
    ```
    

#### 完整示例

```typescript
const secureTransport = new CentureMCPClientTransport({
  client: new CentureClient({
    baseUrl: "http://localhost:3001",
    apiKey: "your-api-key",
  }),
  transport: stdioTransport,

  shouldScanMessage: ({ message }) => {
    // Skip scanning for certain safe methods
    if (message.method === "tool/list") {
      return false;
    }
    return true;
  },

  onUnsafeMessage: ({ message, scanResult }) => {
    // Allow medium-confidence detections
    const isMedium = scanResult.categories.every(
      (c) => c.confidence === "medium",
    );

    if (isMedium) {
      return { passthrough: true };
    }

    // Block high-confidence threats
    return {
      passthrough: false,
      replace: {
        jsonrpc: "2.0",
        id: message.id,
        error: {
          code: -32001,
          message: "Unsafe Message!",
        },
      },
    };
  },
});
```

#### 钩子类型

```typescript
type ShouldScanMessageContext = {
  message: JSONRPCMessage;
  extra?: MessageExtraInfo;
};

type OnAfterScanContext = {
  message: JSONRPCMessage;
  extra?: MessageExtraInfo;
  scanResult: ScanResponse;
};

type OnUnsafeMessageContext = {
  message: JSONRPCMessage;
  extra?: MessageExtraInfo;
  scanResult: ScanResponse;
};

type OnUnsafeMessageResult = {
  passthrough: boolean;
  replace?: JSONRPCMessage;
};
```

## 处理错误

SDK为不同的情景提供了特定的出错分类:

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

try {
  const result = await client.scanText("content");
} catch (error) {
  if (error instanceof UnauthorizedError) {
    console.error("Invalid API key");
  } else if (error instanceof BadRequestError) {
    console.error("Invalid request:", error.message);
  } else if (error instanceof PayloadTooLargeError) {
    console.error("Image too large");
  }
}
```

## 配置

### 自定义获取选项

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

### 自定义获取执行

```typescript
import fetch from "node-fetch";

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

## 威胁类别

API检测到以下威胁类别:

| 类别 | 说明 |
| --- | --- |
| `output_manipulation` | 控制 AI 输出内容、格式化或样式 |
| `context_injection` | 假上下文、角色、系统消息或指令覆盖 |
| `data_exfiltration` | 试图提取敏感数据 |
| `unauthorized_actions` | 试图触发未经授权的行动或API电话 |

## 许可证

麻省理工学院

## 常见问题

### @centure/node-sdk 是什么？

用于与 Centure 的 API 交互的 Typescript SDK

### 如何安装 @centure/node-sdk？

在项目目录运行 npm install @centure/node-sdk，或使用 pnpm add / yarn add / bun add。

### @centure/node-sdk 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @centure/node-sdk 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @centure/node-sdk 可以商用吗？

@centure/node-sdk 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @centure/node-sdk 的下载量有多少？

根据 npm 官方下载统计，@centure/node-sdk 在 2026/10/10 – 2026/11/08 这 30 天内被下载 4,587 次，日均约 153 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @centure/node-sdk 还在维护吗？

最新版本 0\.1\.0 发布于 2025/12/11（10 个月前）；至今共发布 2 个版本，其中过去 12 个月发布了 1 个；首次发布于 2025/11/07。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

