adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

LiteLLM giving error with OpenAI models and Grafana's MCP server

Open umangk-2410 opened this issue 1 year ago • 19 comments

The bug I was integrating OpenAI's gpt-4o model ADK using LiteLLM, but it gave me error regarding the schema for one of tools for the Grafana's MCP server.

To Reproduce Steps to reproduce the behavior:

  1. Defining the Agent
root_agent = LlmAgent(
            model=LiteLlm(model="openai/gpt-4o"),
            name='grafana_retrieval_agent',
            description="Helps user retrieve metrics and logs from Grafana Datasources.",
            instruction=REVISED_RETRIEVAL_PROMPT,
            tools=tools,
            output_key="retrieval_agent_output"
        )
  1. Defining the MCP server
async def grafana_mcp():
    try:
        print(f"Attempting to connect to Grafana MCP Server")
        tools, exit_stack = await MCPToolset.from_server(
            connection_params = StdioServerParameters(
                command="mcp-grafana",
                args=[],
                env={
                    "GRAFANA_URL": "http://localhost:3000",
                    "GRAFANA_API_KEY": GRAFANA_API_KEY
                }
            )
        )
        return tools, exit_stack
    except Exception as e:
        print(f"Failed to connect to Grafana MCP Server: {e}")
        return [], None
  1. Defining the run logic
    async def run(self, query: str):
        session_service = InMemorySessionService()
        session = session_service.create_session(
            state={}, app_name='mcp_grafana_app', user_id='user_fs'
        )

        print(f"\nUser Query for Retrieval Agent:\n '{query}'")
        content = types.Content(role='user', parts=[types.Part(text=query)])

        root_agent, exit_stack = await self.init_agent()
        runner = Runner(
            app_name='mcp_grafana_app',
            agent=root_agent,
            session_service=session_service,
        )

        print("Running Retrieval Agent...")
        events_async = runner.run_async(
            session_id=session.id, user_id=session.user_id, new_message=content
        )

        output = None
        async for event in events_async:
            # print(event.content.parts[0])
            text = event.content.parts[0].text
            function_response = event.content.parts[0].function_response
            # if text is not None:
                # print(text)
            if function_response is not None:
                print(function_response.response["result"])
            output = text

        print("Closing MCP server connection...")
        await exit_stack.aclose()
        print("Cleanup complete.")

        return o
  1. The error
Attempting to connect to Grafana MCP Server
time=2025-05-25T18:36:14.513+05:30 level=INFO msg="Starting Grafana MCP server using stdio transport"
time=2025-05-25T18:36:14.513+05:30 level=INFO msg="Using Grafana configuration" url=http://localhost:3000 api_key_set=true
Fetched 26 tools from MCP server.
Running Retrieval Agent...

Give Feedback / Get Help: https://github.com/BerriAI/litellm/issues/new
LiteLLM.Info: If you need to debug this error, use `litellm._turn_on_debug()'.

an error occurred during closing of asynchronous generator <async_generator object stdio_client at 0x72332c9fbd80>
asyncgen: <async_generator object stdio_client at 0x72332c9fbd80>
  + Exception Group Traceback (most recent call last):
  |   File "/home/ubermenchh/work/AIOps-Agent/.venv/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 772, in __aexit__
  |     raise BaseExceptionGroup(
  | BaseExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/home/ubermenchh/work/AIOps-Agent/.venv/lib/python3.12/site-packages/mcp/client/stdio/__init__.py", line 173, in stdio_client
    |     yield read_stream, write_stream
    | GeneratorExit
    +------------------------------------

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/ubermenchh/work/AIOps-Agent/.venv/lib/python3.12/site-packages/mcp/client/stdio/__init__.py", line 167, in stdio_client
    anyio.create_task_group() as tg,
    ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubermenchh/work/AIOps-Agent/.venv/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 778, in __aexit__
    if self.cancel_scope.__exit__(type(exc), exc, exc.__traceback__):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/ubermenchh/work/AIOps-Agent/.venv/lib/python3.12/site-packages/anyio/_backends/_asyncio.py", line 457, in __exit__
    raise RuntimeError(
RuntimeError: Attempted to exit cancel scope in a different task than it was entered in
An error occurred: litellm.BadRequestError: OpenAIException - Invalid schema for function 'list_alert_rules': 'STRING' is not valid under any of the given schemas.

Expected behavior

  • When using gemini models with ADK, the process runs smoothly without any error. Only when i integrate using LiteLLM i am getting this error.
  • I also tried gemini models with LiteLLM and again it perfectly.
  • I also tried this in OpenAI's SDK and it worked with it perfectly too. The issue only occurs with ADK.

Desktop (please complete the following information):

  • OS: Arch Linux
  • Python version(python -V): 3.12.9
  • ADK version(pip show google-adk): 0.1.0

umangk-2410 avatar May 25 '25 13:05 umangk-2410

I also encountered this issue

mrbaowei avatar May 27 '25 10:05 mrbaowei

I saw you are using a relatively older version of ADK. Could you try the latest version to see if still experience the same issue? @umangk-2410

hangfei avatar Jun 01 '25 23:06 hangfei

I saw you are using a relatively older version of ADK. Could you try the latest version to see if still experience the same issue? @umangk-2410

problem still exists in adk 1.2.1 version.

Tianluo-Chunlei avatar Jun 05 '25 04:06 Tianluo-Chunlei

Sorry for replying this late, but this still happens. I had to filter out the tools causing this error to run my Agent.

umangk-2410 avatar Jun 05 '25 06:06 umangk-2410

Can confirm this happens with simple mcps too, @hangfei I think there is some error the mcps are not getting cleanly exited which is causing memory issues

shankarpriyank avatar Jul 02 '25 08:07 shankarpriyank

Any mitigations for this?

Issue is very consistent with many mcp servers

aravindsuresh1 avatar Jul 03 '25 11:07 aravindsuresh1

using tool_filter arg with MCPToolset is a way to mitigate this if you really do not require the tool that is giving the error

umangk-2410 avatar Jul 03 '25 11:07 umangk-2410

@umangk-2410 how do you know the particular tool that is causing the error? Because I see this issue is pretty consistent

aravindsuresh1 avatar Jul 03 '25 11:07 aravindsuresh1

@aravindsuresh1 check this line in the error logs,

An error occurred: litellm.BadRequestError: OpenAIException - Invalid schema for function 'list_alert_rules': 'STRING' is not valid under any of the given schemas.

This tells the tool schema for the function list_alert_rules in not valid. So i just filtered out this tool function for my use case and my agent workflow worked.

ps: there might be many tools having invalid schemas so check if you really need those tools or not.

umangk-2410 avatar Jul 03 '25 11:07 umangk-2410

@umangk-2410 I don't see that here in my case. This is the only log message I see:

INFO:     127.0.0.1:43246 - "GET /debug/trace/session/c25aa722-26e3-4168-8894-025f3c186f18 HTTP/1.1" 200 OK
INFO:     127.0.0.1:57620 - "POST /run_sse HTTP/1.1" 200 OK
2025-07-03 17:34:31,675 - INFO - envs.py:47 - Loaded .env file  /home/aravind/my-project/.env
2025-07-03 17:34:31,676 - INFO - mcp_session_manager.py:289 - Cleaning up disconnected session: stdio_session

aravindsuresh1 avatar Jul 03 '25 12:07 aravindsuresh1

I don't think your issue is regarding invalid tool schemas. Maybe check if others are having this issue on the MCP server's github. Are you able to use the MCP on Cursor or VS Code.

umangk-2410 avatar Jul 03 '25 12:07 umangk-2410

The issue seems pretty consistent with any MCP tool. The tool itself isn't the issue, it's the async context that ADK creates when using any MCP tool.

devries avatar Jul 03 '25 12:07 devries

If you are manually creating the google.adk.runners.Runner, I did have some luck calling the await runner.close() within my main async function before returning. Essentially this looks like:

import asyncio
from google.adk.runners import Runner

async def main():
    # Set up session service and session if necessary

    runner = Runner(app_name="test_app", agent=root_agent, session_service=session_service)

    # Do all your fun AI stuff

    await runner.close()

if __name__=='__main__':
    asyncio.run(main())

devries avatar Jul 03 '25 12:07 devries

@devries Thanks, does this work with ADK WEB too?

Can you please provide a reference example?

aravindsuresh1 avatar Jul 03 '25 12:07 aravindsuresh1

@hangfei any tentative timelines for the bug fix?

aravindsuresh1 avatar Jul 03 '25 13:07 aravindsuresh1

Unfortunately I can't find a way to do this in adk web.

devries avatar Jul 04 '25 18:07 devries

Any update on this ? I got the same error while using OpenAI models with mcp servers.

raghul-velt avatar Jul 09 '25 11:07 raghul-velt

I'm having the same issue.

It doesn't happen all the time - it only happens if you have one parameter that is an object, e.g:

"variantOption": {
  "type": "object",
  "properties": {
    "name": {
      "type": "STRING",
      "description": "Name of the variant option to filter by"
    },
    "value": {
      "type": "STRING",
      "description": "Value of the variant option to filter by"
    }
  },
  "description": "Variant option to filter by"
}

The problem is that in the lite_llm.py file there's this logic

def _schema_to_dict(schema: types.Schema) -> dict:
  """Recursively converts a types.Schema to a dictionary.

  Args:
    schema: The schema to convert.

  Returns:
    The dictionary representation of the schema.
  """

  schema_dict = schema.model_dump(exclude_none=True)
  if "type" in schema_dict:
    schema_dict["type"] = schema_dict["type"].lower()
  if "items" in schema_dict:
    if isinstance(schema_dict["items"], dict):
      schema_dict["items"] = _schema_to_dict(
          types.Schema.model_validate(schema_dict["items"])
      )
    elif isinstance(schema_dict["items"]["type"], types.Type):
      schema_dict["items"]["type"] = TYPE_LABELS[
          schema_dict["items"]["type"].value
      ]
  if "properties" in schema_dict:
    properties = {}
    for key, value in schema_dict["properties"].items():
      if isinstance(value, types.Schema):
        properties[key] = _schema_to_dict(value)
      else:
        properties[key] = value
        if "type" in properties[key]:
          properties[key]["type"] = properties[key]["type"].lower()
    schema_dict["properties"] = properties
  return schema_dict

as you can see it doesn't take into consideration the fact that you can have properties inside properties.

My fix will be to do something like

        if "properties" in properties[key]:
            properties[key]["properties"] = {
                k: _schema_to_dict(v) for k, v in properties[key]["properties"].items()
            }

thiagosalvatore avatar Jul 17 '25 20:07 thiagosalvatore

Hi all! Thanks for contributing, we merged a PR for this issue a few weeks back. Feel free to reopen the issue if you're still seeing it in newer versions!

jwiejulie avatar Aug 25 '25 17:08 jwiejulie