ClaudeCloudflare Developer PlatformMar 2, 2026, 12:00 AM

Agents, Workers - Agents SDK v0.7.0: Observability rewrite, keepAlive, and waitForMcpConnections

A condensed section focused on the key takeaways first.

Original Post

Quick Digest

Summary

A condensed section focused on the key takeaways first.

claudeenmodel: claude-sonnet-4-20250514

Agents SDK v0.7.0: Observability rewrite, keepAlive, and waitForMcpConnections

Key Points

  • Observability system rewritten with diagnostics channels
  • keepAlive prevents Durable Object eviction during long operations
  • MCP connections now wait before processing chat messages

Summary

Cloudflare Agents SDK v0.7.0 introduces a major observability system rewrite using diagnostics channels, adds keepAlive functionality to prevent Durable Object eviction, and ensures MCP tools are available before chat message processing.

Key Points

  • Observability Rewrite: Replaced console.log-based system with structured events published to 7 named diagnostics channels (agents:state, agents:rpc, agents:message, etc.) with zero overhead when not listening
  • keepAlive() Methods: New keepAlive() and keepAliveWhile() functions prevent Durable Object eviction during long-running operations using 30-second heartbeat schedules
  • MCP Connection Waiting: waitForMcpConnections ensures MCP server connections are ready before onChatMessage runs, with configurable timeout (default 10 seconds)
  • Enhanced MCP Features: Server deduplication by name/URL, optional callbackHost for non-OAuth servers, and improved URL security validation
  • Developer Experience: Type-safe event subscription, automatic cleanup functions, and integration with Tail Workers for production monitoring

Full Translation

Translations

A translation section that keeps the flow of the original article.

claudejamodel: claude-sonnet-4-20250514

Agents SDK v0.7.0: 可観測性の書き直し、keepAlive、waitForMcpConnections

Agents SDK v0.7.0: 可観測性の書き直し、keepAlive、waitForMcpConnections

公開日: 2026年3月2日
カテゴリ: Agents, Workers

Agents SDKの最新リリースでは、diagnostics_channelを使用した可観測性の完全な書き直し、長時間実行される作業中のDurable Objectの退避を防ぐkeepAlive()の追加、そしてonChatMessage実行時にMCPツールが常に利用可能になるよう保証するwaitForMcpConnectionsが導入されました。

可観測性の書き直し

以前の可観測性システムは、カスタムのObservability.emit()インターフェースとconsole.log()を使用していました。v0.7.0では、これを診断チャンネルに公開される構造化イベントに置き換えました。デフォルトでは無音で、誰も監視していない場合はオーバーヘッドがゼロです。

すべてのイベントにはtypepayloadtimestampがあります。イベントは7つの名前付きチャンネルにルーティングされます:

チャンネルイベントタイプ
agents:statestate:update
agents:rpcrpc, rpc:error
agents:messagemessage:request, message:response, message:clear, message:cancel, message:error, tool:result, tool:approval
agents:scheduleschedule:create, schedule:execute, schedule:cancel, schedule:retry, schedule:error, queue:retry, queue:error
agents:lifecycleconnect, destroy
agents:workflowworkflow:start, workflow:event, workflow:approved, workflow:rejected, workflow:terminated, workflow:paused, workflow:resumed, workflow:restarted
agents:mcpmcp:client:preconnect, mcp:client:connect, mcp:client:authorize, mcp:client:discover

型安全なアクセスには、agents/observabilityから型付きのsubscribe()ヘルパーを使用してください:

import { subscribe } from "agents/observability";

const unsub = subscribe("rpc", (event) => {
  if (event.type === "rpc") {
    console.log(`RPC call: ${event.payload.method}`);
  }
  if (event.type === "rpc:error") {
    console.error(
      `RPC failed: ${event.payload.method}${event.payload.error}`,
    );
  }
});

// 完了時にクリーンアップ
unsub();

本番環境では、すべての診断チャンネルメッセージが自動的にTail Workersに転送されます。エージェント自体にサブスクリプションコードは不要です:

export default {
  async tail(events) {
    for (const event of events) {
      for (const msg of event.diagnosticsChannelEvents) {
        // msg.channelは"agents:rpc"、"agents:workflow"など
        console.log(msg.timestamp, msg.channel, msg.message);
      }
    }
  },
};

カスタムObservabilityオーバーライドインターフェースは、イベントをフィルタリングしたり外部サービスに転送したりする必要があるユーザー向けに引き続きサポートされています。

完全なイベントリファレンスについては、Observabilityドキュメントを参照してください。

keepAlive()とkeepAliveWhile()

Durable Objectは、非アクティブ期間後(通常、受信リクエスト、WebSocketメッセージ、アラームがない状態で70-140秒)に退避されます。長時間実行される操作中(LLMレスポンスのストリーミング、外部APIの待機、マルチステップ計算の実行)に、エージェントが実行途中で退避される可能性があります。

keepAlive()は30秒のハートビートスケジュールを作成することでこれを防ぎます。アラームの発火により非アクティブタイマーがリセットされます。呼び出し時にハートビートをキャンセルするdisposer関数を返します。

const dispose = await this.keepAlive();
try {
  const result = await longRunningComputation();
  await sendResults(result);
} finally {
  dispose();
}

keepAliveWhile()は非同期関数を自動クリーンアップでラップします。ハートビートは関数実行前に開始され、完了時に停止されます:

const result = await this.keepAliveWhile(async () => {
  const data = await longRunningComputation();
  return data;
});

重要な詳細:

  • 複数の同時呼び出し元 — 各keepAlive()呼び出しは独立したdisposerを返します。1つを破棄しても他に影響しません。
  • AIChatAgent組み込み — AIChatAgentはストリーミングレスポンス中に自動的にkeepAlive()を呼び出します。自分で追加する必要はありません。
  • スケジューリングシステムを使用 — ハートビートは独自のスケジュールと競合しません。検査が必要な場合はgetSchedules()に表示されます。

注意: keepAlive()@experimentalとマークされており、リリース間で変更される可能性があります。

完全なAPIリファレンスと使用時のガイダンスについては、Schedule tasks — Keeping the agent aliveを参照してください。

waitForMcpConnections

AIChatAgentは、onChatMessageを呼び出す前にMCPサーバー接続の安定を待つようになりました。これにより、特にDurable Objectの休止後に接続がバックグラウンドで復元されている際に、this.mcp.getAITools()が完全なツールセットを返すことが保証されます。

export class ChatAgent extends AIChatAgent {
  // デフォルト — 最大10秒待機
  // waitForMcpConnections = { timeout: 10_000 };
  
  // 無期限に待機
  waitForMcpConnections = true;
  
  // 待機を無効化
  waitForMcpConnections = false;
}
動作
{ timeout: 10_000 }最大10秒待機(デフォルト)
{ timeout: N }最大Nミリ秒待機
trueすべての接続が準備完了まで無期限に待機
false待機しない(0.2.0以前の古い動作)

より低レベルな制御には、onChatMessage内で直接this.mcp.waitForConnections()を呼び出してください。

その他の改善

  • 名前とURLによるMCP重複排除 — HTTP transportを使用するaddMcpServerは、サーバー名とURLの両方で重複排除を行います。同じ名前で異なるURLで呼び出すと新しい接続が作成されます。URLは比較前に正規化されます(末尾スラッシュ、デフォルトポート、ホスト名の大文字小文字)。

  • 非OAuthサーバーでcallbackHostがオプション — OAuth を使用しないMCPサーバーに接続する際、addMcpServercallbackHostを必要としなくなりました。

  • MCP URLセキュリティ — SSRFを防ぐため、接続前にサーバーURLが検証されます。プライベートIP範囲、ループバックアドレス、リンクローカルアドレス、クラウドメタデータエンドポイントがブロックされます。

  • カスタム拒否メッセージaddToolOutputは、human-in-the-loopツール承認フローでカスタム拒否メッセージ用のstate: "output-error"errorTextをサポートするようになりました。

  • チャットオプションのrequestIdonChatMessageオプションに、ログ記録とイベント相関用のrequestIdが含まれるようになりました。

アップグレード

最新バージョンに更新するには:

npm i agents@latest @cloudflare/ai-chat@latest