Skip to content

Streaming aggregator throws Sequence contains no elements for server-tool result blocks (web_search/web_fetch/code_execution/MCP) #211

Description

@KryziK

Ran into the following issue and had Claude write up the following:

SDK: Anthropic (anthropics/anthropic-sdk-csharp) — reproduced on 12.21.0 through 12.27.0

Summary: BetaMessageContentAggregator (used by beta streaming and ToolRunner.Streaming()) throws InvalidOperationException: Sequence contains no elements whenever a streamed response contains a content block that arrives whole in content_block_start with no content_block_delta events — i.e. all server-tool result blocks. Non-streaming Beta.Messages.Create is unaffected.

Root cause: In BetaMessageContentAggregator.MergeBlock, the Single(T item) helper ignores its item argument and instead does blockContents.OfType().Single(), where blockContents is the delta events only (see GetResult, which filters to BetaRawContentBlockDeltaEvent). For block types routed through Single() (web_search_tool_result, web_fetch_tool_result, server_tool_use, code-execution/MCP results, redacted_thinking, container_upload) the delta list never contains a matching T, so .Single() throws.

Expected: the aggregated BetaMessage includes the server-tool blocks (the full block is already present in content_block_start).

Fix: have Single(T item) return item (the complete start-event block) instead of querying the delta list.

Minimal repro:

using Anthropic;
using Anthropic.Models.Beta.Messages;

var client = new AnthropicClient(); // ANTHROPIC_API_KEY in env
var p = new MessageCreateParams {
    Model = "claude-opus-4-8",
    MaxTokens = 1024,
    Messages = [new() { Role = Role.User, Content = "What is the latest stable Rust version? Search the web." }],
    Tools = [new BetaToolUnion(new BetaWebSearchTool20250305 { MaxUses = 2 })],
};

await foreach (var _ in client.Beta.Messages.CreateStreaming(p)) { }
// throws InvalidOperationException: Sequence contains no elements
// once the web_search_tool_result block is aggregated

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions