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

I have Custom MCP Server and Custom frontend UI for AI Agent. But I am facing this error. Please help.

Open Priyanshu-NorthAstra opened this issue 1 year ago • 11 comments

Django version 4.2.10, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Request received [24/May/2025 22:47:54] "POST /agents/api/agent/ HTTP/1.1" 500 145 Performing system checks...

System check identified no issues (0 silenced).

You have 58 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, django_celery_beat, emailsync, quickbook, sessions, social_django, user_management. Run 'python manage.py migrate' to apply them. May 24, 2025 - 22:48:50 Django version 4.2.10, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Request received Initializing Agent Creating Agent Agent created Agent initialized an error occurred during closing of asynchronous generator <async_generator object aconnect_sse at 0x1258eb560> asyncgen: <async_generator object aconnect_sse at 0x1258eb560> Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/httpx_sse/_api.py", line 70, in aconnect_sse yield EventSource(response) GeneratorExit

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/httpx_sse/_api.py", line 69, in aconnect_sse async with client.stream(method, url, headers=headers, **kwargs) as response: File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit raise RuntimeError("generator didn't stop after athrow()") RuntimeError: generator didn't stop after athrow() an error occurred during closing of asynchronous generator <async_generator object sse_client at 0x121352740> asyncgen: <async_generator object sse_client at 0x121352740> Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 57, in sse_client async with aconnect_sse( File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit raise RuntimeError("generator didn't stop after athrow()") RuntimeError: generator didn't stop after athrow()

During handling of the above exception, another exception occurred:

  • Exception Group Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 767, in aexit | raise BaseExceptionGroup( | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 154, in sse_client | yield read_stream, write_stream | GeneratorExit | | During handling of the above exception, another exception occurred: | | Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 57, in sse_client | async with aconnect_sse( | File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit | raise RuntimeError("generator didn't stop after athrow()") | RuntimeError: generator didn't stop after athrow() +------------------------------------

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 53, in sse_client async with anyio.create_task_group() as tg: File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 773, in aexit if self.cancel_scope.exit(type(exc), exc, exc.traceback): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 456, in exit raise RuntimeError( RuntimeError: Attempted to exit cancel scope in a different task than it was entered in [24/May/2025 22:49:00] "POST /agents/api/agent/ HTTP/1.1" 500 145

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]: Mac OS
  • Python version(python -V): 3.11
  • ADK version(pip show google-adk): 1.0.0

Additional context Add any other context about the problem here.

Priyanshu-NorthAstra avatar May 24 '25 22:05 Priyanshu-NorthAstra

` class AI_Agent: def init(self): print("Initializing Agent") _, project_id = google.auth.default() os.environ.setdefault("GOOGLE_CLOUD_PROJECT", project_id) os.environ.setdefault("GOOGLE_CLOUD_LOCATION", "us-central1") os.environ.setdefault("GOOGLE_GENAI_USE_VERTEXAI", "True")

    print("Creating Agent")
    self.name = "Karyo"
    self.model = "gemini-2.0-flash"
    self.instruction =  utils.read_file("assets/karyo_instructions.txt")
    self.description = utils.read_file("assets/karyo_description.txt")
    
    self.agent = Agent(
        name = self.name,
        instruction=self.instruction,
        model=self.model,
        description= self.description,
        tools=[
            MCPToolset(connection_params=SseServerParams(url="http://localhost:5173/sse"))
        ]
    )
    print("Agent created")
    self.session_service = InMemorySessionService()
    self.artifact_service = InMemoryArtifactService()

    self.runner = Runner(
        agent=self.agent,
        app_name="Karyo_App",
        artifact_service=self.artifact_service,
        session_service=self.session_service
    )
    print("Agent initialized")

def get_agent(self)-> Agent:
    return self.agent
    
async def run_process(self, message: str, context: Dict[str, Any], session_id: Optional[str] = None) -> Dict[str, Any]:
    
    #Get User Id from context or use default
    user_id = context.get("user_id", "default")

    # Create or get Session
    if not session_id:
        session_id = str(uuid.uuid4())
    
    session = await self.session_service.get_session(app_name="Karyo_App", user_id = user_id, session_id= session_id)
    if not session:
        session = await self.session_service.create_session(app_name="Karyo_App", user_id = user_id, session_id= session_id, state={})

    request_content = adk_types.Content(role="user", parts=[adk_types.Part(text=message)])

    try:
        events = self.runner.run_async(
            user_id=user_id,
            session_id=session_id,
            new_message=request_content
        )

        final_message = None
        raw_events = []
        return_object = None

        async for event in events:
            raw_events.append(event.model_dump(exclude_none = True))
            if event.is_final_response() and event.content and event.content.role == "model":
                if event.content.parts and event.content.parts[0].text:
                    final_message = event.content.parts[0].text

        
        return_object = {
            "message": final_message,
            "status": "success",
            "data": {
                "raw_events": raw_events[-3:]
            }
        }
    except Exception as e:
        print(f"Error: {str(e)}")
        return_object = {
            "message" : f"Error: {str(e)}",
            "status" : "error",
            "data": {}
        }
    finally:
        import warnings

        try:
            await events.aclose()
        except RuntimeError as e:
            if "generator didn't stop after athrow()" in str(e):
                warnings.warn("SSE generator did not close cleanly.")
            else:
                raise

    return return_object

`

This is the code if anybody is curious.

Priyanshu-NorthAstra avatar May 25 '25 00:05 Priyanshu-NorthAstra

I think this may be related to your mcp server implementation. Here are some resources you can take a look to help

  1. https://google.github.io/adk-docs/mcp/#mcp-tools-in-adk
  2. Youcan checkout our adk web source code for examples: https://github.com/google/adk-web

wyf7107 avatar May 26 '25 18:05 wyf7107

Thank you for response. If that would be the case, then it shouldn't work as expected when running using 'adk web' but it works extremely well for that workflow. But whenever, I try to use a runner, it gives me generator cleanup error. I tried looking at the resources available at google-adk docs. But I think its not updated to match the current version. Because, when I follow those instructions for (runner + MCP Server Tools), I get a different error: from_server is not defined in MCPToolset. Which is valid because of the newer version. But the docs still suggests to use that when using runner. That's why I sought some help here.

Priyanshu-NorthAstra avatar May 26 '25 18:05 Priyanshu-NorthAstra

Let me pull some helpers here @Jacksunwei @hangfei

wyf7107 avatar May 26 '25 18:05 wyf7107

Thank you so much!!

Priyanshu-NorthAstra avatar May 26 '25 18:05 Priyanshu-NorthAstra

` import mcp from starlette.responses import Response from requests import Request from starlette.applications import Starlette from starlette.routing import Route, Mount import uvicorn from mcp.server.fastmcp import FastMCP from mcp.server.sse import SseServerTransport from quickbook_tools import QuickBooksMCPTools from gmail_tools import GmailMCPTools import json

  print("[DEBUG] Initializing MCP server...")
  mcp = FastMCP("server")
  sse = SseServerTransport("/messages/")
  print("[DEBUG] MCP server initialized")
  
  # Register all tools with proper error handling
  @mcp.tool()
  def list_gmail_messages(access_token: str, user_id: str = "me") -> str:
      print(f"[DEBUG] list_gmail_messages called with user_id={user_id}")
      try:
          print("[DEBUG] Calling GmailMCPTools.list_messages")
          result = GmailMCPTools.list_messages(access_token, user_id)
          print(f"[DEBUG] GmailMCPTools.list_messages returned: {result[:100]}...")
          return result
      except Exception as e:
          print(f"[DEBUG] Error in list_gmail_messages: {str(e)}")
          return json.dumps({"error": str(e)}, indent=2)
  
  @mcp.tool()
  def get_gmail_message(access_token: str, message_id: str, user_id: str = "me") -> str:
      print(f"[DEBUG] get_gmail_message called with message_id={message_id}, user_id={user_id}")
      try:
          print("[DEBUG] Calling GmailMCPTools.get_message")
          result = GmailMCPTools.get_message(access_token, message_id, user_id)
          print(f"[DEBUG] GmailMCPTools.get_message returned: {result[:100]}...")
          return result
      except Exception as e:
          print(f"[DEBUG] Error in get_gmail_message: {str(e)}")
          return json.dumps({"error": str(e)}, indent=2)
  
  @mcp.tool()
  def send_gmail_email(
      access_token: str,
      from_email: str,
      to_email: str,
      body_text: str,
      subject: str = "No Subject",
      user_id: str = "me"
  ) -> str:
      print(f"[DEBUG] send_gmail_email called with from={from_email}, to={to_email}, subject={subject}")
      try:
          print("[DEBUG] Calling GmailMCPTools.send_email")
          result = GmailMCPTools.send_email(
              access_token=access_token,
              from_email=from_email,
              to_email=to_email,
              body_text=body_text,
              subject=subject,
              user_id=user_id
          )
          print(f"[DEBUG] GmailMCPTools.send_email returned: {result[:100]}...")
          return result
      except Exception as e:
          print(f"[DEBUG] Error in send_gmail_email: {str(e)}")
          return json.dumps({"error": str(e)}, indent=2)
  
  @mcp.tool()
  def get_pending_invoices(realm_id: str, access_token: str) -> str:
      print(f"[DEBUG] get_pending_invoices called with realm_id={realm_id}")
      try:
          print("[DEBUG] Calling QuickBooksMCPTools.get_pending_invoices")
          response = QuickBooksMCPTools.get_pending_invoices(realm_id, access_token)
          print(f"[DEBUG] QuickBooksMCPTools.get_pending_invoices returned: {response[:100]}...")
          print("[DEBUG] Returning hardcoded response for testing")
          return response
      except Exception as e:
          print(f"[DEBUG] Error in get_pending_invoices: {str(e)}")
          return json.dumps({"error": str(e)}, indent=2)
  
  @mcp.tool()
  def get_recent_expenses(realm_id: str, access_token: str) -> str:
      print(f"[DEBUG] get_recent_expenses called with realm_id={realm_id}")
      try:
          print("[DEBUG] Calling QuickBooksMCPTools.get_recent_expenses")
          result = QuickBooksMCPTools.get_recent_expenses(realm_id, access_token)
          print(f"[DEBUG] QuickBooksMCPTools.get_recent_expenses returned: {result[:100]}...")
          return result
      except Exception as e:
          print(f"[DEBUG] Error in get_recent_expenses: {str(e)}")
          return json.dumps({"error": str(e)}, indent=2)
  
  async def handle_sse_connection(request: Request):
      print(f"[DEBUG] handle_sse_connection called with request: {request}")
      _server = mcp._mcp_server
      async with sse.connect_sse(
          request.scope,
          request.receive,
          request._send,
      ) as (reader, writer):
          await _server.run(reader, writer, _server.create_initialization_options())
  
      # Ensure a valid response is returned to the ASGI framework
      return Response(status_code=200)
  
  print("[DEBUG] Creating Starlette app...")
  app = Starlette(
      debug=True,
      routes=[
          Route("/sse", endpoint=handle_sse_connection),
          Mount("/messages/", app=sse.handle_post_message),
      ],
  )
  print("[DEBUG] Starlette app created")
  
  if __name__ == "__main__":
      print("[DEBUG] Starting uvicorn server...")
      uvicorn.run(app, host="localhost", port=5173)
      print("[DEBUG] Server started")

`

This is my MCP Server Tools for reference.

Priyanshu-NorthAstra avatar May 26 '25 18:05 Priyanshu-NorthAstra

Hi @Priyanshu-NorthAstra ,

MCP requires strong long-live connection between client and server and requires some special cleanup. @seanzhou1023 recently distilled the logic we did in adk cli fast_api server into separate module. It's already in the development head. You could take a look for your reference.

https://github.com/google/adk-python/commit/92c37496d33a0f475d98501853c032541f8ce026

Jacksunwei avatar May 27 '25 04:05 Jacksunwei

Thank you. I'll go through the code and understand how to use it in my implementation.

Priyanshu-NorthAstra avatar May 27 '25 20:05 Priyanshu-NorthAstra

Hey, Thank you, that generator error was fixed by adding a finally block with await tools.close(); however, I am getting a different error now, with the following: Session shutdown error (continuing cleanup): 'ClientSession' object has no attribute 'shutdown' What could be the reason for this? Sorry to keep bugging you guys here, since the documentations are not up-to-date, this is my only source of help. Thank you everyone!

Priyanshu-NorthAstra avatar May 27 '25 20:05 Priyanshu-NorthAstra

you can use runner's close method to close all toolset used by an agent that is run by the runner : https://github.com/google/adk-python/blob/5d2a876ca8b68b038a81d0ae8d289bfdec945d41/src/google/adk/runners.py#L488

seanzhou1023 avatar May 27 '25 22:05 seanzhou1023

Django version 4.2.10, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Request received [24/May/2025 22:47:54] "POST /agents/api/agent/ HTTP/1.1" 500 145 Performing system checks...

System check identified no issues (0 silenced).

You have 58 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, django_celery_beat, emailsync, quickbook, sessions, social_django, user_management. Run 'python manage.py migrate' to apply them. May 24, 2025 - 22:48:50 Django version 4.2.10, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Request received Initializing Agent Creating Agent Agent created Agent initialized an error occurred during closing of asynchronous generator <async_generator object aconnect_sse at 0x1258eb560> asyncgen: <async_generator object aconnect_sse at 0x1258eb560> Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/httpx_sse/_api.py", line 70, in aconnect_sse yield EventSource(response) GeneratorExit

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/httpx_sse/_api.py", line 69, in aconnect_sse async with client.stream(method, url, headers=headers, **kwargs) as response: File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit raise RuntimeError("generator didn't stop after athrow()") RuntimeError: generator didn't stop after athrow() an error occurred during closing of asynchronous generator <async_generator object sse_client at 0x121352740> asyncgen: <async_generator object sse_client at 0x121352740> Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 57, in sse_client async with aconnect_sse( File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit raise RuntimeError("generator didn't stop after athrow()") RuntimeError: generator didn't stop after athrow()

During handling of the above exception, another exception occurred:

  • Exception Group Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 767, in aexit | raise BaseExceptionGroup( | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception) +-+---------------- 1 ---------------- | Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 154, in sse_client | yield read_stream, write_stream | GeneratorExit | | During handling of the above exception, another exception occurred: | | Traceback (most recent call last): | File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 57, in sse_client | async with aconnect_sse( | File "/usr/local/Cellar/[email protected]/3.11.12_1/Frameworks/Python.framework/Versions/3.11/lib/python3.11/contextlib.py", line 267, in aexit | raise RuntimeError("generator didn't stop after athrow()") | RuntimeError: generator didn't stop after athrow() +------------------------------------

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/mcp/client/sse.py", line 53, in sse_client async with anyio.create_task_group() as tg: File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 773, in aexit if self.cancel_scope.exit(type(exc), exc, exc.traceback): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/priyanshu-internship/Desktop/North Astra/finance-agent-backend/.venv/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 456, in exit raise RuntimeError( RuntimeError: Attempted to exit cancel scope in a different task than it was entered in [24/May/2025 22:49:00] "POST /agents/api/agent/ HTTP/1.1" 500 145

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]: Mac OS
  • Python version(python -V): 3.11
  • ADK version(pip show google-adk): 1.0.0

Additional context Add any other context about the problem here.

facing similar issue when connecting to fastmcp server with streamable-http transport. However, the agent still able to receive response from the fastmcp but the error message "unable to cleanup async generator" pops out every time.

weisiang9678 avatar Aug 06 '25 02:08 weisiang9678