audit

ルーティングされたツール呼び出しのための追記専用 JSONL 監査トレイルです: build_record、 append_record、artifact_paths、resolve_audit_path を提供し、さらにプロンプト・画像 ペイロード・認証情報をトレイルに残さないための秘匿化ヘルパーを備えます。

関連項目

レコードがいつ書かれるかは Insiders ヘッダー、ルーティング、監査 を、 MCP_AUDIT_LOG_PATH は 設定 を参照してください。

Append-only JSONL audit trail for routed tool calls.

One record per line, one os.write per record. The file is opened with O_APPEND so concurrent writers append whole lines rather than overwrite one another: a crash mid-write can lose a line but never corrupt a line already written.

Nothing here may break a tool call. Every I/O or serialisation failure is logged and swallowed, because observability must never become a dependency of the business path.

Credentials and image payloads are never recorded. Prompts are reduced to their length plus a truncated SHA-256, image arguments are replaced by a marker, and any over-long string is digested instead of written verbatim, so a base64 blob cannot reach the trail even under an unexpected argument name.

novelai_image_mcp.audit.AUDIT_FILENAME = 'audit.jsonl'

File name used when no explicit audit path is configured.

novelai_image_mcp.audit.DIGEST_LENGTH = 16

Number of hex characters kept from a digest.

novelai_image_mcp.audit.MAX_ARGUMENT_LENGTH = 256

Longest argument string recorded verbatim; longer values are digested.

novelai_image_mcp.audit.MAX_RECORDED_HEADERS = 32

Largest number of headers kept in an audit record. The routing layer already caps its snapshot at 64; this is a second, tighter bound so a hostile client cannot grow an audit line without limit.

novelai_image_mcp.audit.MAX_RECORDED_HEADER_LENGTH = 256

Longest header value kept in an audit record.

novelai_image_mcp.audit.append_record(record, *, path)[ソース]

Append record as a single JSON line; return whether it was written.

The record is serialised first and then handed to exactly one os.write on a descriptor opened O_APPEND, so concurrent writers cannot interleave halves of a line. Failures are logged and reported as False -- this function never raises, because a tool call must not fail on account of the audit trail.

パラメータ:
戻り値の型:

bool

novelai_image_mcp.audit.artifact_paths(result)[ソース]

Return the sorted *.png paths a tool result mentions.

Image tools report what they wrote as text (Saved 1 image(s): [...]); this reads those paths back for the audit record. The result is only observed, never rewritten, and a result without text blocks yields [].

パラメータ:

result (Any)

戻り値の型:

list[str]

novelai_image_mcp.audit.build_record(*, routing, tool, duration_ms, outcome, features=(), artifacts=(), arguments=None, unknown_keys=(), malformed=())[ソース]

Build one JSON-serialisable audit record.

features, artifacts, unknown_keys and malformed are sorted so two records describing the same state are byte-identical.

パラメータ:
  • routing (RoutingContext)

  • tool (str)

  • duration_ms (float)

  • outcome (str)

  • features (Collection[str])

  • artifacts (Collection[str])

  • arguments (Mapping[str, Any] | None)

  • unknown_keys (Collection[str])

  • malformed (Collection[str])

戻り値の型:

dict[str, Any]

novelai_image_mcp.audit.cap_headers(headers)[ソース]

Apply the audit-side cap to an already-sanitised header snapshot.

The input is expected to be RoutingContext.recorded_headers, which the routing layer has already stripped of every credential-bearing name. This only bounds the size: at most :data:MAX_RECORDED_HEADERS entries, each value at most :data:MAX_RECORDED_HEADER_LENGTH characters, kept in lexicographic order of the (lower-cased) name.

パラメータ:

headers (Mapping[str, str] | None)

戻り値の型:

dict[str, str]

novelai_image_mcp.audit.digest_text(value)[ソース]

Return the length and truncated SHA-256 of value, never the text.

パラメータ:

value (str)

戻り値の型:

dict[str, Any]

novelai_image_mcp.audit.resolve_audit_path(*, audit_log_path, output_dir=None)[ソース]

Resolve the audit destination.

An explicit audit_log_path wins; otherwise the trail lives beside the generated images at <output_dir>/audit.jsonl.

パラメータ:
  • audit_log_path (str | None)

  • output_dir (str | Path | None)

戻り値の型:

Path

novelai_image_mcp.audit.summarise_arguments(arguments)[ソース]

Summarise tool arguments so the record can never leak a payload.

Prompts become a length plus a truncated SHA-256, image arguments become a marker, and every other value is reduced to something small and JSON-serialisable.

パラメータ:

arguments (Mapping[str, Any] | None)

戻り値の型:

dict[str, Any]

レコードが書かれるとき

監査トレイルは insiders サーフェスの一部です: ToolCallLoggingMiddleware は ツール呼び出しごとに 1 レコードを、model-routing が有効な間だけ 追記します。 opt-in ヘッダーを送らないリクエストは何も書き込みません。

resolve_audit_path が出力先を選びます — 明示的な MCP_AUDIT_LOG_PATH が優先され、 なければ NOVELAI_OUTPUT_DIR 内の audit.jsonl になります。

レコードのフィールド

build_record は呼び出しごとに、JSON にシリアライズ可能なフラットなオブジェクトを 1 つ生成します:

フィールド

内容

ts

UTC タイムスタンプ (ISO-8601)。

route

サニタイズ済みのルート。

model / agent / client / session

抽出されたルーティング値、または null。

tool

ツール名。

duration_ms

実時間 (小数第 3 位に丸め)。

outcome

ok、error、rejected のいずれか。

features

有効な insiders 機能名 (ソート済み)。

artifacts

結果が言及した *.png パス (ソート済み)。

unknown_keys

insiders ヘッダーの未認識キー (ソート済み)。

malformed

insiders ヘッダーの使用不能な項目 (ソート済み)。

headers

サニタイズ済みルーティングヘッダーのスナップショット。MAX_RECORDED_HEADERS (32) 件、各値 MAX_RECORDED_HEADER_LENGTH (256) 文字までで、小文字化した名前の辞書順に並びます。

arguments

要約された呼び出し引数 — 下記参照。

features、artifacts、unknown_keys、malformed はソートされるため、同じ状態を表す 2 つのレコードはバイト単位で同一になります。

秘匿化

summarise_arguments は、あらゆる引数をファイルに到達し得る前に縮約します:

  • プロンプト形式 の引数 (prompt、prompts、negative_prompt、 negativeprompt) は digest_text により {"length": n, "sha256": "<first 16 hex characters>"} になります。プロンプト本文が 書かれることはありません。

  • 画像形式 の引数 (image、images、init_image、mask、 reference、references、base64) はリテラルの [redacted image] になります。

  • MAX_ARGUMENT_LENGTH (256) 文字を超える すべての 文字列は、書かずに ダイジェスト化されます。予期しない引数名で base64 ブロブがすり抜けることは ありません。

  • マッピングは {"keys": n} に、リスト・タプル・集合は {"items": n} に、その他の オブジェクトは型名に縮約されます。None、真偽値、整数、浮動小数点数はそのまま 記録されます。

認証情報を含むヘッダーは上流の routing._recorded で除去されるため、このモジュールが 上限を設けるスナップショットには、そもそも authorization、cookie、set-cookie、 proxy-authorization、および *-token / *-secret / *-password / *-key / *-credential ヘッダーが含まれません。

並行性と耐久性

append_record はまずレコードをシリアライズし、次に O_APPEND で開いたディスクリプタ (モード 0o600、必要なら親ディレクトリを作成) に対して 厳密に 1 回の os.write で 書き込みます。したがって並行ライターは、1 行の半分同士を混在させるのではなく行全体を 追記します。書き込み途中のクラッシュで行が失われることはあり得ますが、すでに書かれた行が 壊れることはありません。

失敗時の挙動

可観測性が業務パスの依存になることはありません。append_record は自身の OSError / TypeError / ValueError を捕捉し、logger.error で失敗を記録して False を返します — 決して例外を送出しないため、監査ファイルが書けないことがツール呼び出しの失敗に変わる コードパスは存在しません。

関連項目