Skip to content

Image/audio content in SamplingMessage and CreateMessageResult is base64-encoded twice #2033

Open

Description

@atailakh

Describe the bug

Image (and audio) content in sampling messages is base64-encoded twice on the wire.

SingleItemOrListConverter<T>.Write serializes each item with options.GetTypeInfo(typeof(object)). For a ContentBlock list this resolves the derived type's default contract (e.g. ImageContentBlock) instead of ContentBlock.Converter. The default contract serializes ReadOnlyMemory<byte> Data (which already holds base64 UTF-8 bytes) as base64 again.

Affected: SamplingMessage.Content and CreateMessageResult.Content. In practice, McpServer.SampleAsync / AsSamplingChatClient() with a DataContent image sends an image the client cannot use: after decoding, the client gets the base64 text instead of the image bytes, and model providers reject it (e.g. OpenAI-compatible APIs return 400 invalid image data).

To Reproduce

byte[] png = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A];
var block = ImageContentBlock.FromBytes(png, "image/png");

JsonSerializer.Serialize<ContentBlock>(block, McpJsonUtilities.DefaultOptions);
// "data":"iVBORw0KGgo="          <- correct

JsonSerializer.Serialize(new SamplingMessage { Role = Role.User, Content = [block] }, McpJsonUtilities.DefaultOptions);
// "data":"aVZCT1J3MEtHZ289"      <- base64 of the base64

Expected behavior

Content blocks inside SamplingMessage / CreateMessageResult serialize the same way as a standalone ContentBlock (data encoded once).

Version

ModelContextProtocol.Core 2.4.0 (also reproduces on main).

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions