メインコンテンツまでスキップ
このページは機械翻訳であり、十分なレビューを経ていません。英語の原文が正となります。セキュリティ、プライバシー、データの取り扱い、コンプライアンス、ライセンスに関する記述は、技術レビューが完了するまで英語のまま掲載しています。 英語の原文を読む

Node.js SDK

対応モード: Hosted Hybrid Local 利用可能なプラン: Free Solo Teams

英語の原文 -- 翻訳は技術レビュー待ちです

The Control Zero Node.js SDK provides deterministic policy enforcement for AI agents running in JavaScript and TypeScript environments. A deny stops the guarded call before it executes. Hosted policies arrive as signed bundles that are verified before use, and the SDK fails closed by default when it cannot establish coverage.

適切な適用面を選ぶ

変更できないアプリケーションにはゲートウェイプロキシを、開発者向けの AI ツールにはコーディングフックを使用します。JavaScript または TypeScript のアプリケーションコードを自分で管理できる場合に、この SDK を使用します。

インストール​

@controlzero パッケージは npmjs.org ではなく、Control Zero レジストリ(https://npm.controlzero.ai)から提供されます。.npmrc(プロジェクトレベルまたはユーザーレベル)で、スコープをこのレジストリに一度だけ向けてください。

@controlzero:registry=https://npm.controlzero.ai

そのうえで、インストールします。

npm install @controlzero/sdk

これにより、このページに記載されている機能セットに対応する現行の 1.13.x 系がインストールされます。@controlzero スコープ以外の依存関係は、引き続き npmjs.org から解決されます。

要件:

  • Node.js 18 以降
  • TypeScript 5.0+(任意。型チェック付きで使用する場合)

クイックスタート​

デプロイモードを選択します。

Hosted モードでは非同期の初期化が必要です

Python SDK とは異なり、Node.js の new Client({apiKey}) コンストラクタは、ローカルポリシーなしで apiKey が指定されるとエラーを投げます。Hosted モードでは非同期ファクトリを使用してください。

// Hosted mode -- MUST use async factory
const cz = await Client.create({ apiKey: 'cz_live_your_api_key_here' });

// Local mode only -- synchronous constructor works
const cz = new Client({ policyFile: 'controlzero.yaml' });

Hosted ポリシーはダッシュボードから取得されます。

英語の原文 -- 翻訳は技術レビュー待ちです

Audit in cloud.

ほとんどのチームに推奨します。

import { Client } from '@controlzero/sdk';

// MUST use async factory for hosted mode
const client = await Client.create({ apiKey: 'cz_live_your_api_key_here' });
// Or use env var: export CONTROLZERO_API_KEY="cz_live_..."

英語の原文 -- 翻訳は技術レビュー待ちです

The SDK pulls the signed policy bundle from the dashboard at first call, verifies its signature, decrypts locally, and enforces every call against the dashboard policy. Audit ships to the remote trail automatically.

設定​

非同期の Client.create ファクトリを使い、プロジェクトの API キーだけを渡します。

英語の原文 -- 翻訳は技術レビュー待ちです

The SDK pulls the signed policy bundle from the dashboard at first call, verifies its signature, decrypts locally, and enforces every call against the dashboard policy. Audit ships to the remote trail automatically.

import { Client } from '@controlzero/sdk';

const client = await Client.create({ apiKey: 'cz_live_your_api_key_here' });

new Client({ apiKey })(同期)は、API キーだけでは構築を拒否し、Client.create() を使うよう案内します。Hosted のブートストラップは I/O 呼び出しであり、await できる必要があるためです。

Local ローカルポリシーファイルを使う​

import { Client } from '@controlzero/sdk';

const client = new Client({ policyFile: './controlzero.yaml' });

インラインポリシー​

import { Client } from '@controlzero/sdk';

const client = new Client({
policy: {
rules: [
{ allow: 'database:query', reason: 'Reads are permitted' },
{ deny: 'database:*', reason: 'All other database operations are blocked' },
],
},
});
従来のアクション名と正式なアクション名のどちらも使えます

database:query、database:execute、database:delete は従来のアクション名で、正式な database:read、database:write、database:admin クラスと同じ呼び出しに一致します。新しいポリシーでは正式な名前を使うことを推奨しますが、従来の名前を使った既存のルールも変更なしで引き続き動作します。

ワイルドカードによるリソースの一致​

resources: ['*'] を指定したルールは、呼び出し側が context.resource を渡したかどうかにかかわらず、すべての呼び出しに一致します。ルールを一律に適用したく、呼び出しごとのリソースを持たない(または渡したくない)場合に使用します。

// Policy rule with universal resource matching
// { effect: 'allow', actions: ['database:read'], resources: ['*'] }

// This call matches even though context.resource is not set:
cz.guard('database', { method: 'query', args: { sql: 'SELECT 1' } });

ワイルドカードでないリソースパターン(例: resources: ['table/orders'])では、ルールが働くために、呼び出し側が一致する context.resource を渡す必要があります。

環境変数​

引数を直接渡す代わりに、環境変数で SDK を設定できます。

export CONTROLZERO_POLICY_FILE="./controlzero.yaml"
import { Client } from '@controlzero/sdk';

// Reads CONTROLZERO_POLICY_FILE from environment, or auto-discovers
// controlzero.yaml, controlzero.yml, or controlzero.json in cwd
const client = new Client();

設定オプション​

オプション環境変数型デフォルト説明
apiKeyCONTROLZERO_API_KEYstring-Project API key. Use Client.create({ apiKey }) to enable hosted mode (auto-pulls the signed policy bundle from the dashboard; remote audit).
policy-object-ルールを含むインラインのポリシーオブジェクト。
policyFileCONTROLZERO_POLICY_FILEstring-YAML または JSON のポリシーファイルへのパス。
strictHosted-boolfalseHybrid(API キー + ローカルポリシー)の場合に、警告する代わりに例外を発生させます。
logPath-string./controlzero.logローカルの監査ログファイルのパス。
logRotation-stringdaily監査ログのローテーション間隔。
logRetention-string30 daysHow long to keep rotated logs.
logCompression-stringnullローテーション済みログを圧縮します(例: gz)。
logFormat-stringjson監査ログの形式(json または pretty)。
refreshIntervalSeconds-number300Hosted モード: ダッシュボードに新しいポリシーバンドルがないか確認する間隔。
agentNameCZ_AGENT_NAMEstring-帰属を示すために監査イベントに記録されるラベル。
Node は 300 秒ごと、Python は 60 秒ごとに更新します

Node SDK の refreshIntervalSeconds のデフォルトは 300(5 分)です。Python SDK の refresh_interval_seconds のデフォルトは 60 です。2 つのポーリング間隔をそろえるには、refreshIntervalSeconds: 60 を設定します。

ポリシーの解決順序: policy オプション、policyFile オプション、環境変数 CONTROLZERO_POLICY_FILE、次に cwd で自動検出された最初のファイル(controlzero.yaml、次に controlzero.yml、次に controlzero.json -- 最初に存在したものが優先されます)、最後に 1 回だけ警告を出して何もせず通過させる動作になります。ポリシーファイルは YAML でも JSON でもよく、どちらも同一のスキーマを使用します。

基本的な使い方​

ツール呼び出しの評価​

主要なメソッドは guard() で、読み込まれたポリシーに対してツール呼び出しを評価します。

import { Client } from '@controlzero/sdk';

const client = new Client({ policyFile: './controlzero.yaml' });

const decision = client.guard('database', {
method: 'query',
args: { sql: 'SELECT * FROM orders' },
});

console.log(decision.effect); // "allow" or "deny"
console.log(decision.reason); // human-readable reason
console.log(decision.policyId); // matching policy ID

拒否されたアクションの処理​

ポリシーがアクションを拒否した場合は、判定の effect を確認するか、PolicyDeniedError を捕捉します。

import { Client, PolicyDeniedError } from '@controlzero/sdk';

const client = new Client({ policyFile: './controlzero.yaml' });

const decision = client.guard('filesystem', {
method: 'write_file',
args: { path: '/data/output.csv', content: '...' },
});

if (decision.effect === 'deny') {
console.log(`Blocked: ${decision.reason}`);
console.log(`Policy: ${decision.policyId}`);
}

または、raiseOnDeny を使って、拒否時に例外を投げることもできます。

try {
client.guard('filesystem', {
method: 'write_file',
args: { path: '/data/output.csv' },
raiseOnDeny: true,
});
} catch (error) {
if (error instanceof PolicyDeniedError) {
console.log(`Blocked: ${error.message}`);
}
}

API リファレンス​

Client​

メインのクライアントクラスです。guard() は同期です。ローカルポリシー、Hybrid、およびポリシーなしのパススルーのクライアントでは、構築は同期です。API キーのみの Hosted ブートストラップだけが、非同期ファクトリを必要とします。

new Client(options?)​

新しい Control Zero クライアントを作成します。利用可能なパラメータについては、設定オプションを参照してください。initialize() の呼び出しは不要です。コンストラクタがローカルポリシーを即座に読み込みます。ポリシーがまったく設定されていない場合、クライアントは 1 回だけ警告を出し、呼び出しをそのまま通過させます。

ローカルポリシーなしで apiKey を渡すと、HostedModeNotImplemented が投げられます。Hosted モードには Client.create() を使用してください。

static Client.create(options?): Promise<Client>​

英語の原文 -- 翻訳は技術レビュー待ちです

Async factory. Required for hosted mode: it fetches the signed policy bundle, verifies its signature and decrypts it before returning the client.

guard(tool, opts?): PolicyDecision​

読み込まれたポリシーに対してツール呼び出しを評価します。

パラメータ:

名前型必須説明
toolstringはいツール名(例: "database")。
optsGuardOptionsいいえmethod、args、raiseOnDeny、context を持つオプションオブジェクト。

GuardOptions:

フィールド型デフォルト説明
methodstring"*"メソッド名。ツールと組み合わせて "tool:method" というアクションになります。
argsobject{}DLP スキャンと条件評価に使う引数。
raiseOnDenybooleanfalsetrue の場合、拒否のときに PolicyDeniedError を投げます。
contextobject-一致判定に使う、resource と tags を持つ任意のコンテキスト。

戻り値: effect、reason、policyId、dlpFindings を持つ PolicyDecision。

close(): Promise<void>​

バッファリングされた監査ログをフラッシュし、リソースを解放します。

PolicyDecision​

guard() が返します。

属性型説明
effectstring"allow" または "deny"。
policyIdstring or null一致したポリシー(ある場合)。
reasonstring人が読める説明。
deniedboolean便利なプロパティ: effect が "deny" のとき true。
dlpFindingsarray引数内で見つかった DLP の一致のリスト。

PolicyDeniedError​

raiseOnDeny が true でポリシーがアクションを拒否した場合に、guard() が投げます。

class PolicyDeniedError extends Error {
readonly decision: PolicyDecision;
}

MCP での使用​

Control Zero は Model Context Protocol と自然に統合できます。次は、MCP のツール呼び出しをポリシーの適用でラップする例です。

import { Client, PolicyDeniedError } from '@controlzero/sdk';

const cz = new Client({ policyFile: './controlzero.yaml' });

function callMCPToolGoverned(server: string, tool: string, args: Record<string, unknown>): unknown {
// Evaluate the policy before calling the tool
cz.guard(server, {
method: tool,
args,
raiseOnDeny: true,
});

// Policy check passed. Call the tool
return mcpClient.callTool(server, tool, args);
}

LLM プロバイダーラッパー​

Node.js SDK には、一般的な LLM プロバイダーのクライアントにガバナンスを追加する軽量なラッパーが含まれています。各ラッパーは呼び出しをインターセプトし、ポリシーを評価して、プロバイダー本来の API の形を変えずに判定を記録します。

Google AI (Gemini)​

現行の @google/genai パッケージを使用します。wrapGoogle は、個々のモデルインスタンスではなくクライアントの .models 名前空間をラップするため、すべての generateContent / generateContentStream 呼び出しが統制されます。

import { Client } from '@controlzero/sdk';
import { wrapGoogle } from '@controlzero/sdk/integrations';
import { GoogleGenAI } from '@google/genai';

const cz = new Client({ policyFile: './controlzero.yaml' });

const googleClient = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const models = wrapGoogle(googleClient.models, cz, { agentId: 'my-agent' });

const result = await models.generateContent({
model: 'gemini-2.0-flash',
contents: 'Summarize the quarterly report',
});
console.log(result.text);

Anthropic​

import { Client } from '@controlzero/sdk';
import Anthropic from '@anthropic-ai/sdk';

const cz = new Client({ policyFile: './controlzero.yaml' });

const anthropic = new Anthropic({ apiKey: 'your-anthropic-key' });

import { wrapAnthropic } from '@controlzero/sdk/integrations';
const wrappedClient = wrapAnthropic(anthropic, cz);

const message = await wrappedClient.messages.create({
model: 'claude-sonnet-4-6',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Summarize the quarterly report' }],
});
console.log(message.content[0].text);

利用可能なラッパー​

関数プロバイダーインポートパス
wrapGoogle()Google AI (Gemini)@controlzero/sdk/integrations
wrapAnthropic()Anthropic (Claude)@controlzero/sdk/integrations
wrapOpenAI()OpenAI@controlzero/sdk/integrations

すべてのラッパーは事前チェック(モデルのブロック、コスト見積もり、PII 検出)を適用し、リクエストを監査証跡に記録します。ポリシーがリクエストを拒否した場合は、呼び出しがプロバイダーに届く前に PolicyDeniedError が投げられます。

エラー処理​

import { Client, PolicyDeniedError } from '@controlzero/sdk';

const client = new Client({ policyFile: './controlzero.yaml' });

try {
client.guard('database', {
method: 'query',
args: { sql: 'SELECT 1' },
raiseOnDeny: true,
});
} catch (error) {
if (error instanceof PolicyDeniedError) {
console.log(`Denied: ${error.decision.reason}`);
}
}

await client.close();

CommonJS のサポート​

SDK は ESM と CommonJS の両方をサポートしています。

// ESM
import { Client } from '@controlzero/sdk';

// CommonJS
const { Client } = require('@controlzero/sdk');

従来の名前 ControlZeroClient は、後方互換のための Client のエイリアスとしてエクスポートされています。

TypeScript​

SDK は TypeScript で書かれており、完全な型宣言が付属しています。すべての型はメインのエントリポイントからエクスポートされます。

import type { PolicyDecision } from '@controlzero/sdk';
import type { ClientOptions, GuardOptions } from '@controlzero/sdk';