OpenAICloudflare 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.

openaienmodel: gpt-5-mini-2025-08-07

Agents SDK v0.7.0 — observability rewrite, keepAlive, waitForMcpConnections

Key Points

  • Observability now uses diagnostics_channel events
  • keepAlive() prevents Durable Object eviction during long tasks
  • waitForMcpConnections ensures MCP tools available before onChatMessage

Summary

Agents SDK v0.7.0 rewrites observability to use structured diagnostics channels (zero overhead when unused), adds keepAlive() and keepAliveWhile() to prevent Durable Object eviction during long-running work, and introduces waitForMcpConnections so MCP tools are available before onChatMessage runs. Several MCP and tool-related quality-of-life and security improvements are included.

Key Points

  • Observability
    • Replaces console/Observability.emit with diagnostics_channel events (type, payload, timestamp).
    • Events routed to named channels (agents:rpc, agents:workflow, agents:mcp, agents:message, etc.).
    • Use agents/observability.subscribe(channel, handler) for typed, type-safe subscriptions.
    • In production, Tail Workers automatically receive diagnosticsChannelEvents — no agent subscription required.
  • keepAlive() / keepAliveWhile()
    • keepAlive() creates a 30s heartbeat schedule to reset Durable Object inactivity timers; returns a disposer to cancel it.
    • keepAliveWhile(fn) starts the heartbeat for the duration of an async function and stops automatically.
    • Multiple concurrent callers are independent; AIChatAgent automatically uses keepAlive() during streaming.
    • Marked experimental (API may change).
  • waitForMcpConnections
    • AIChatAgent waits for MCP server connections before invoking onChatMessage to ensure this.mcp.getAITools() returns the full toolset.
    • Configuration: {timeout: 10000} (default), true (wait indefinitely), false (do not wait). Call this.mcp.waitForConnections() for manual control.
  • Other improvements
    • addMcpServer deduplicates by name+normalized URL; callbackHost optional for non-OAuth servers; server URLs validated to block private/metadata ranges.
    • addToolOutput supports state: "output-error" with errorText for custom denial flows.
    • onChatMessage options now include requestId for logging/correlation.

Upgrade

Run:

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

Notes

  • Observability is silent and zero-cost when no subscribers are present.
  • Review the Observability and Schedule docs for full event and API references.

Full Translation

Translations

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

openaijamodel: gpt-5-mini-2025-08-07

Agents、Workers - Agents SDK v0.7.0: 観測性の書き直し、keepAlive、および waitForMcpConnections

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

公開日: 2026-03-02

最新リリース (v0.7.0) では、diagnostics_channel による観測性の全面的な書き直し、Durable Object の長時間処理を保つための keepAlive()、そして MCP ツールが常に利用可能となるよう waitForMcpConnections が導入されました。

観測性の書き直し

以前は console.log() とカスタムの Observability.emit() インターフェースを使った仕組みでした。v0.7.0 ではこれを廃止し、構造化イベントを diagnostics_channel に公開する方式に変更しました。デフォルトではサイレントで、購読者がいない場合はオーバーヘッドはゼロです。各イベントは 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/observabilitysubscribe() ヘルパーを使います(例: JavaScript / TypeScript)。

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

運用時には、すべての diagnostics channel メッセージが自動的に Tail Workers に転送されるため、エージェント側で購読コードを書く必要はありません(例: Tail Worker)。

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 Objects は一定期間のアイドル後に(通常は着信リクエスト、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() 呼び出しは独立した破棄関数を返します。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() を直接呼び出できます。

その他の改善点

  • MCP の名前と URL による重複排除 — HTTP トランスポートの addMcpServer がサーバー名と URL の双方で重複排除を行うようになりました。同じ名前で異なる URL を渡すと新しい接続が作成されます。URL は比較前に正規化されます(末尾スラッシュ、デフォルトポート、ホスト名の大文字小文字など)。
  • 非 OAuth サーバー向けの callbackHost がオプションに — OAuth を使わない MCP サーバーへの接続時に addMcpServercallbackHost を必須としなくなりました。
  • MCP URL のセキュリティ — 接続前にサーバー URL を検証し、SSRF を防止します。プライベート IP 範囲、ループバック、リンクローカル、クラウドメタデータエンドポイントはブロックされます。
  • カスタム拒否メッセージ — addToolOutputstate: "output-error"errorText をサポートし、ヒューマンインザループのツール承認フローでカスタム拒否メッセージを表示できます。
  • チャットオプションの requestIdonChatMessage オプションに requestId が追加され、ログやイベント相関に利用できます。

アップグレード

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

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

詳しい API リファレンスや関連ドキュメントは公式ドキュメントを参照してください。