Skip to content

Conversation

@leonardogrig
Copy link

Link to Issue or Description of Change

Problem:

MCP tools fail when model simplifies [{"type": "web"}] to ["web"].

Error:

MCP error -32602: sources.0: Invalid input: expected object, received string

Solution:

Added input transformation in McpTool._run_async_impl() to convert ["web"][{"type": "web"}] when schema expects array of single-property objects.

Testing Plan

Unit Tests:

  • Added 6 tests to test_mcp_tool.py
  • All tests pass
pytest tests/unittests/tools/mcp_tool/test_mcp_tool.py -k "transform" -v
# 6 passed

Tests:

  1. Simple types unchanged
  2. Array primitives → objects transformation
  3. Already-correct format unchanged
  4. Empty arrays
  5. Multi-property objects unchanged
  6. Integration test: transformation applied during tool execution

Manual E2E Test:

Tested with Firecrawl MCP firecrawl_search tool.

Before:

MCP error -32602: sources.0: Invalid input: expected object, received string

After:

[agent]: I found some recent AI news articles for you:
* AWS and OpenAI announce multi-year strategic partnership
* OpenAI and Amazon sign $38 billion deal for AI computing power
...

✅ Tool executes successfully

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Additional context

Implementation:

  • Added 2 methods: _transform_args_to_mcp_format() and _transform_value_to_schema()
  • ~70 lines of code
  • No breaking changes

Test Code Used

The following agent code was used to test the fix with the query: "can you fetch recent ai news?"

from google.adk.agents import LlmAgent
from google.adk.tools.mcp_tool.mcp_session_manager import StdioConnectionParams
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset
from google.adk.tools.google_api_tool import CalendarToolset
from mcp import StdioServerParameters
from dotenv import load_dotenv
import os
from pathlib import Path

# Load .env file from the same directory as this file
env_path = Path(__file__).parent / '.env'
load_dotenv(env_path)

# Load configuration from environment variables
FIRECRAWL_API_KEY = os.getenv("FIRECRAWL_API_KEY")
OAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID")
OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET")
MODEL = "gemini-2.5-pro"

tools = [
    # Firecrawl MCP Tool
    MCPToolset(
        connection_params=StdioConnectionParams(
            server_params=StdioServerParameters(
                command="npx",
                args=["-y", "firecrawl-mcp"],
                env={"FIRECRAWL_API_KEY": FIRECRAWL_API_KEY}
            ),
            timeout=30,
        ),
    ),
    # Google Calendar Toolset with OAuth
    CalendarToolset(
        client_id=OAUTH_CLIENT_ID,
        client_secret=OAUTH_CLIENT_SECRET
    ),
]

# Create the agent
root_agent = LlmAgent(
    model=MODEL,
    name="firecrawl_calendar_agent",
    description="A helpful AI assistant that scrapes websites with Firecrawl and manages your Google Calendar using natural language.",
    instruction="""
You are an AI assistant with two main capabilities:

1. **Web Scraping with Firecrawl**: You can fetch and analyze content from websites.

2. **Google Calendar Management**: You can help users manage their calendar by:
   - Listing upcoming events
   - Creating new calendar events
   - Getting event details
   - Updating existing events
   - Deleting events
   - Searching for specific events

""",
    tools=tools,
)

Current MCP tool usage error:
image

Fix after this PR:
image

leonardogrig and others added 3 commits November 3, 2025 18:41
Adds argument transformation layer to handle cases where model output simplifies array-of-objects to array-of-primitives for single-property object schemas.

  Example: Model generates ["web", "images"] for schema expecting
  [{"type": "web"}, {"type": "images"}], causing MCP validation errors.

  The transformation:
  - Only applies to arrays with object items containing one property
  - Preserves already-correct arguments
  - Returns original values when transformation doesn't apply

  Fixes validation errors with MCP tools that define array parameters
  with single-property object items (e.g., Firecrawl search sources).
@google-cla
Copy link

google-cla bot commented Nov 3, 2025

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist
Copy link

Summary of Changes

Hello @leonardogrig, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical bug where the output from language models, when simplified, caused MCP tools to fail due to a mismatch with their expected input schemas. Specifically, it resolves cases where an array of single-property objects was incorrectly simplified to an array of primitives. The solution introduces an intelligent argument transformation mechanism that automatically re-formats these simplified inputs to conform to the tool's schema, ensuring successful tool execution and improving the robustness of agent-tool interactions.

Highlights

  • Problem Resolution: Fixed an issue where MCP tools failed due to model outputs simplifying array-of-object arguments (e.g., "[{"type": "web"}]" becoming "["web"]").
  • Argument Transformation: Implemented a new argument transformation layer within McpTool._run_async_impl() to automatically convert simplified array arguments back to the expected object format when the schema requires it.
  • New Methods: Introduced _transform_args_to_mcp_format() and _transform_value_to_schema() to handle the argument restructuring logic.
  • Comprehensive Testing: Added 6 new unit tests covering various transformation scenarios and an end-to-end integration test to validate the fix.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@adk-bot adk-bot added the mcp [Component] Issues about MCP support label Nov 3, 2025
@adk-bot
Copy link
Collaborator

adk-bot commented Nov 3, 2025

Response from ADK Triaging Agent

Hello @leonardogrig, thank you for creating this PR!

It looks like you have not signed the Contributor License Agreement (CLA) yet. Please make sure to sign the CLA so we can proceed with reviewing your contribution.

Thank you for providing a detailed testing plan, it is very helpful for the reviewers!

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a transformation layer to handle cases where the language model simplifies arguments for MCP tools, for example, by turning an array of single-property objects into an array of primitives. The implementation is solid and well-tested for the intended scenarios. My main feedback is to improve the robustness of the transformation logic in _transform_value_to_schema to correctly handle mixed-type arrays, which could otherwise lead to runtime errors. I've provided a specific code suggestion to address this. Overall, this is a valuable fix.

Comment on lines +361 to +381
if schema_type == "array" and isinstance(value, list) and value:
items_schema = schema.get("items")
if not items_schema or items_schema.get("type") != "object":
return value

if not isinstance(value[0], dict):
if not all(not isinstance(item, dict) for item in value):
logger.warning(
"Mixed types in array for MCP tool %s", self.name
)
return value

item_properties = items_schema.get("properties", {})
if len(item_properties) == 1:
property_name = next(iter(item_properties))
logger.debug(
"Transforming array for MCP tool %s with property '%s'",
self.name,
property_name,
)
return [{property_name: item} for item in value]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The current logic for transforming values has a potential issue with mixed-type arrays. It assumes that if the first element in a list is a dictionary, the entire list is correctly formatted. This could lead to errors if the list contains a mix of dictionaries and primitives (e.g., [{'type': 'web'}, 'images']).

The suggested change refactors the logic to be more robust by explicitly checking if the list contains all dictionaries, all primitives, or a mix of both, ensuring that mixed lists are handled gracefully by logging a warning and returning the original value. This prevents potential downstream errors in the MCP tool.

It would also be beneficial to add a new unit test to cover this mixed-list scenario to prevent future regressions.

    if schema_type == "array" and isinstance(value, list) and value:
      items_schema = schema.get("items")
      if not items_schema or items_schema.get("type") != "object":
        return value

      is_list_of_dicts = all(isinstance(item, dict) for item in value)
      if is_list_of_dicts:
        return value

      is_list_of_primitives = all(not isinstance(item, dict) for item in value)
      if not is_list_of_primitives:
        logger.warning(
            "Mixed types in array for MCP tool %s", self.name
        )
        return value

      item_properties = items_schema.get("properties", {})
      if len(item_properties) == 1:
        property_name = next(iter(item_properties))
        logger.debug(
            "Transforming array for MCP tool %s with property '%s'",
            self.name,
            property_name,
        )
        return [{property_name: item} for item in value]

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The current logic for validating the array hinges on the type of the first element (value[0]). This creates a potential failure point if the array contains mixed types.

@ryanaiagent ryanaiagent self-assigned this Nov 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mcp [Component] Issues about MCP support

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants