Skip to content

InvalidCastException when Gemini agent invokes MCP tools (TextContent → JsonElement cast failure) #104

@gabaoalb

Description

@gabaoalb

Description

When using the Gemini integration provided by this package together with Microsoft Agent Framework (MAF) and an MCP server, tool invocation fails at runtime.

The exact same MCP server and toolset work correctly when the agent is backed by OpenAI, which suggests the issue is specific to the Gemini response handling / function call conversion logic.

The failure occurs when the Gemini agent attempts to process the tool response returned by the MCP server.

Environment

  • .NET version: 10
  • Microsoft.Extensions.AI and Microsoft.Extensions.AI.OpenAI (Microsoft Agent Framework)
  • ModelContextProtocol.AspNetCore
  • Google_GenerativeAI.Microsoft

Expected Behavior

The Gemini-based agent should behave the same as the OpenAI-based agent:

  • Connect to the MCP server
  • Discover tools
  • Invoke the echo tool
  • Receive and print the tool result

Example expected output:

Echo: Hello, MCP!
Echo: Hello, MCP!

Actual Behavior

The OpenAI agent works correctly:

Echo: Hello, MCP!

The Gemini agent throws and exception:

System.InvalidCastException: Unable to cast object of type
'Microsoft.Extensions.AI.TextContent' to type 'System.Text.Json.JsonElement'.

at GenerativeAI.Microsoft.GenerativeAIChatClient.CallFunctionAsync(...)
at GenerativeAI.Microsoft.GenerativeAIChatClient.GetResponseAsync(...)
at Microsoft.Extensions.AI.FunctionInvokingChatClient.GetResponseAsync(...)
at Microsoft.Agents.AI.ChatClientAgent.RunCoreAsync(...)

Example

I created a sample project that reproduces the error; if needed, you can find it in my repository.
https://github.com/gabaoalb/DotnetAi

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions