@centure/node-sdk

中文文档
0.1.0发布于 2025/12/11MITTypeScriptCommonJS零依赖构建来源已验证近 30 天下载 4587

A Typescript SDK for interacting with Centure's API

原始使用文档
文档目录15 节
  1. Installation
  2. Usage
  3. Initialize the Client
  4. Scan Text for Prompt Injection
  5. Scan with Options
  6. Scan Image (Base64 or Buffer)
  7. API Response
  8. MCP Integration
  9. CentureMCPClientTransport
  10. Error Handling
  11. Configuration
  12. Custom Fetch Options
  13. Custom Fetch Implementation
  14. Threat Categories
  15. License

@centure/node-sdk

A fully type-safe TypeScript SDK for interacting with Centure's API for prompt injection detection.

Installation

npm install @centure/node-sdk

Usage

Initialize the Client

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
});

Scan Text for Prompt Injection

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);

Scan with Options

Both scanText and scanImage accept an optional ScanOptions parameter:

// 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",
});

Scan Options

All options are optional.

ParameterTypeDescription
onlyRiskCategory[]?Only return detections for these categories. Cannot be used with exclude.
excludeRiskCategory[]?Exclude detections for these categories. Cannot be used with only.
minimum_confidence"medium" | "high"?Minimum confidence level for detections.

Scan Image (Base64 or Buffer)

// 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);
// 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 Response

All scan methods return a ScanResponse object:

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;
}
FieldTypeDescription
is_safebooleanWhether the content is safe (no prompt injection detected)
categoriesDetectedCategory[]List of detected threat categories
reasonstring?Explanation when content is flagged
request_idstringUnique identifier for this request
api_key_idstringID of the API key used
request_unitsnumberNumber of request units consumed
billed_request_unitsnumberNumber of request units billed
service_tierServiceTierService tier used for the request

MCP Integration

The SDK provides a transport wrapper for the Model Context Protocol (MCP) that automatically scans messages for prompt injection attacks.

CentureMCPClientTransport

The CentureMCPClientTransport wraps any MCP transport and intercepts messages to scan them for security threats before they reach your MCP server.

Basic Usage

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);

Configuration Parameters

Required Parameters
  • transport (Transport): The underlying MCP transport to wrap (e.g., StdioClientTransport, SSEClientTransport)
  • client (CentureClient): Centure API client instance for scanning messages
Optional Hooks
  • shouldScanMessage ((context: ShouldScanMessageContext) => boolean | ShouldScanMessageResult):

    Determines whether a specific message should be scanned. Return false or { scan: false } to skip scanning.

    shouldScanMessage: ({ message, extra }) => {
      // Skip scanning for tool list requests
      if (message.method === "tool/list") {
        return false;
      }
      return true;
    };
    
  • onAfterScan ((context: OnAfterScanContext) => void | OnAfterScanResult):

    Called after a message is scanned, regardless of the result. Can return { passthrough: true } to allow the message even if unsafe.

    onAfterScan: ({ message, scanResult }) => {
      console.log(`Scanned ${message.method}: ${scanResult.is_safe}`);
    };
    
  • onUnsafeMessage ((context: OnUnsafeMessageContext) => OnUnsafeMessageResult):

    Called when an unsafe message is detected. Must return an object specifying whether to allow or block the message.

    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):

    Called before any message is sent through the transport.

    onBeforeSend: ({ message, extra }) => {
      console.log(`Sending ${message.method}`);
    };
    

Complete Example

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!",
        },
      },
    };
  },
});

Hook Types

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;
};

Error Handling

The SDK provides specific error classes for different scenarios:

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");
  }
}

Configuration

Custom Fetch Options

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

Custom Fetch Implementation

import fetch from "node-fetch";

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

Threat Categories

The API detects the following threat categories:

CategoryDescription
output_manipulationControls AI output content, formatting, or style
context_injectionFake context, roles, system messages, or instruction overrides
data_exfiltrationAttempts to extract sensitive data
unauthorized_actionsAttempts to trigger unauthorized actions or API calls

License

MIT

版本与发布记录

@centure/node-sdk 共发布 2 个版本,首次发布于 2025/11/07;过去 12 个月发布了 1 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.0latest2025/12/1110 个月前
0.0.12025/11/071 年前

关于 @centure/node-sdk 的常见问题

@centure/node-sdk 是什么?

A Typescript SDK for interacting with Centure's API

如何安装 @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 和提交记录判断。