Adk Pythonclient
    Adk Pythonclient

    Adk Pythonclient

    Demo of ADK (Agent Development Kit) as an MCP (Model Context Protocol) client for flight search capabilities.

    4.3

    GitHub Stats

    Stars

    26

    Forks

    12

    Release Date

    5/8/2025

    about 2 months ago

    Detailed Description

    python adk as mcp client using gemini 2 llm as flight search assistant

    python adk + mcp gemini

    a practical implementation demonstrating adk (agent development kit) as an mcp (model context protocol) client for flight search capabilities. this project showcases asynchronous integration between adk's llmagent and an external mcp server, featuring dynamic tool discovery, stateful session management, and structured function calling. powered by google's gemini model, it implements proper resource handling and event-driven architecture for a robust, extensible assistant.

    📚 table of contents

    🔍 introduction to adk and mcp

    this project showcases the integration of two powerful google technologies:

    • agent development kit (adk): an open-source, code-first python toolkit for building intelligent ai agents
    • model context protocol (mcp): a standardized protocol for ai models to interact with external tools

    in this implementation, adk acts as the mcp client, connecting to an mcp server that provides flight search capabilities.

    🏗️ architecture

    the flight search assistant follows a streamlined request flow that combines the power of google gemini, adk, and mcp to process user queries and provide intelligent responses.

    architecture diagram

    🧩 core components

    • google gemini 2 as llm
    • agent development kit (adk) as agent
    • model context protocol (mcp)
    • serpapi for search
    • python 3.8+

    ✨ technology highlights

    • google gemini 2
      powers conversational ai and context-aware interactions.
    • agent development kit (adk)
      manages conversation flow and tool orchestration.
    • model context protocol (mcp)
      handles secure tool operations and external api calls.
    • serpapi
      provides access to real-time flight data.

    🚀 features

    • adk as mcp client integration - seamless connection between adk agent and mcp server using mcptoolset
    • dynamic tool discovery - automatic detection and integration of mcp server capabilities
    • asynchronous event processing - event-driven architecture with adk's runner for non-blocking operations
    • stateful sessions - conversation context management with inmemorysessionservice
    • structured tool invocation - type-safe function calling through mcp protocol
    • clean resource management - proper connection lifecycle handling with exit stacks

    🧠 core concepts

    adk - agent development kit

    agent development kit (adk) is an open-source, code-first python toolkit for building, evaluating, and deploying intelligent ai agents. adk enables developers to create agentic workflows — from simple single-agent tasks to complex multi-agent orchestration — all within a modular and extensible framework.

    agents in adk

    an agent is an autonomous, self-contained execution unit designed to achieve specific goals. agents can:

    1. perform tasks
    2. interact with users
    3. leverage external tools
    4. collaborate with other agents to complete complex workflows

    core agent categories

    adk offers three primary agent types:

    • llm agents (e.g., llmagent, agent):

      • use llms to understand, reason, plan, and act
      • ideal for dynamic, language-driven tasks
    • workflow agents (e.g., sequentialagent, parallelagent, loopagent):

      • orchestrate other agents in predictable patterns
      • don't rely on an llm for flow control
      • best for structured, repeatable processes
    • custom agents:

      • built by extending baseagent
      • enable custom logic, specialized workflows, or unique tool integrations
      • perfect for advanced, tailor-made solutions

    in this project, we're using llm agents with mcptools.

    tools in adk

    a tool represents a specific capability granted to an ai agent, allowing it to perform actions and interact with the external world beyond basic text generation and reasoning. a tool is usually a modular code component — such as a python function, class method, or even another agent — designed to carry out a defined task.

    how agents use tools

    agents dynamically leverage tools through function-calling mechanisms, where the llm:

    1. reasons over context
    2. selects and invokes the appropriate tool with generated inputs
    3. observes the result
    4. integrates the output into its next action or response

    tool types in adk

    adk supports several types of tools:

    1. function tools: custom tools built specifically for your application's unique logic

      • functions/methods: standard synchronous python functions or class methods
      • agents-as-tools: specialized agents as callable tools within a parent agent
      • long-running function tools: tools for asynchronous or time-intensive operations
    2. built-in tools: predefined tools included in the framework (web search, code execution, rag)

    3. third-party tools: integrations from popular ecosystems like langchain or crewai

    mcp client integration

    in this project, adk serves as an mcp client that connects to an mcp server (mcp-flight-search). this connection allows the adk agent to discover and use tools exposed by the mcp server to search for flights.

    🛠️ implementation steps

    prerequisites

    1. python 3.8+ installed
    2. google gemini generative ai access via api key
    3. a valid serpapi key (used to fetch live flight data)

    step 1: setup environment

    # setup virtual environment (mac or unix)
    python -m venv venv
    source venv/bin/activate  # on windows: venv\scripts\activate
    
    # install dependencies
    pip install google-adk  # agent development kit
    pip install mcp-flight-search  # mcp server 
    pip install google-generativeai python-dotenv  # genai python sdk
    

    set environment variables:

    # note: adk uses google_api_key instead of gemini_api_key
    export google_api_key="your-google-api-key"
    export serp_api_key="your-serpapi-key"
    

    step 2: install mcp server

    to enable gemini to interact with real-world apis, we use an mcp-compliant server. for this project, we use mcp-flight-search — a lightweight mcp server built using fastmcp which exposes a tool that searches real-time flight data using serpapi.

    verify that the mcp server is properly installed:

    pip show mcp-flight-search
    

    step 3: connecting to mcp server

    # --- step 1: get tools from mcp server ---
    async def get_tools_async():
        """gets tools from the flight search mcp server."""
        print("attempting to connect to mcp flight search server...")
        server_params = stdioserverparameters(
            command="mcp-flight-search",
            args=["--connection_type", "stdio"],
            env={"serp_api_key": os.getenv("serp_api_key")},
        )
        
        tools, exit_stack = await mcptoolset.from_server(
            connection_params=server_params
        )
        print("mcp toolset created successfully.")
        return tools, exit_stack
    

    step 4: agent creation

    # --- step 2: define adk agent creation ---
    async def get_agent_async():
        """creates an adk agent equipped with tools from the mcp server."""
        tools, exit_stack = await get_tools_async()
        print(f"fetched {len(tools)} tools from mcp server.")
        
        # create the llmagent
        root_agent = llmagent(
            model=os.getenv("gemini_model", "gemini-2.5-pro-preview-03-25"),
            name='flight_search_assistant',
            instruction='help user to search for flights using available tools based on prompt. if return date not specified, use an empty string for one-way trips.',
            tools=tools,
        )
        
        return root_agent, exit_stack
    

    step 5: integration and session management

    async def async_main():
        # create services
        session_service = inmemorysessionservice()
      
        # create a session
        session = session_service.create_session(
            state={}, app_name='flight_search_app', user_id='user_flights'
        )
      
        # define the user prompt
        query = "find flights from atlanta to las vegas 2025-05-05"
        print(f"user query: '{query}'")
        
        # format input as types.content
        content = types.content(role='user', parts=[types.part(text=query)])
      
        # get agent and exit_stack
        root_agent, exit_stack = await get_agent_async()
      
        # create runner
        runner = runner(
            app_name='flight_search_app',
            agent=root_agent,
            session_service=session_service,
        )
    

    step 6: execution

        print("running agent...")
        events_async = runner.run_async(
            session_id=session.id,
            user_id=session.user_id,
            new_message=content
        )
      
        # process events
        async for event in events_async:
            print(f"event received: {event}")
      
        # always clean up resources
        print("closing mcp server connection...")
        await exit_stack.aclose()
        print("cleanup complete.")
    

    step 7: demo

    example user query:

    "find flights from atlanta to las vegas 2025-05-05"
    

    here's a demonstration of the flight search assistant in action:

    standard logging mode

    standard logging demo

    debug mode

    debug mode demo

    🚦 getting started guide

    installation steps

    1. clone repository

    git clone https://github.com/arjunprabhulal/adk-python-mcp-client.git
    cd adk-python-mcp-client
    

    2. environment setup

    set up a python virtual environment and install dependencies:

    # setup virtual environment (mac or unix)
    python -m venv venv
    source venv/bin/activate  # on windows: venv\scripts\activate
    
    # install all dependencies from requirements.txt
    pip install -r requirements.txt
    

    3. configuration

    create and configure your environment variables:

    # copy the example environment file
    cp .env.example .env
    
    # edit the .env file with your actual api keys
    # replace placeholders with your actual keys:
    # google_api_key=your-actual-google-api-key
    # serp_api_key=your-actual-serpapi-key
    

    4. start services

    run the client script to start the application:

    python client.py
    

    the application will:

    1. connect to the mcp flight search server
    2. initialize the adk agent with your gemini api key
    3. process the default flight query or your custom query
    4. display the conversation events and final results

    📁 project structure

    adk-python-mcp-client/
    ├── images/
    │   ├── adk-mcp-client-log.gif      # standard logging demo animation
    │   ├── adk-mcp-client-debug.gif    # debug mode demo animation
    │   └── image.png                   # architecture diagram
    ├── client.py                       # adk client implementation
    ├── readme.md                       # project documentation
    ├── requirements.txt                # dependencies
    ├── .env.example                    # environment variables template
    └── .env                            # environment variables (not tracked by git)
    

    🔄 key considerations for integration

    1. mcp vs. adk

      • mcp is an open protocol that standardizes how ai models interact with external tools and data sources
      • adk is a python-based framework for building and deploying ai agents
      • mcptoolset bridges mcp and adk by enabling adk agents to consume tools exposed by mcp servers
    2. tool types and integration

      • adk tools: python objects designed for direct use within adk agents
      • mcp tools: capabilities exposed by mcp servers, adapted by mcptoolset for use within adk agents
      • third-party tools: libraries like langchain and crewai offer tools that can be integrated
    3. asynchronous architecture

      • both adk and the mcp python library are built on python's asyncio framework
      • tool implementations and server handlers should be asynchronous (async def) to ensure non-blocking operations
    4. stateful sessions in mcp

      • mcp establishes persistent, stateful connections between clients and servers
      • this statefulness allows for context retention across interactions but requires careful session management
    5. deployment considerations

      • the persistent nature of mcp connections can pose challenges for scaling and deployment
      • infrastructure considerations include load balancing and session affinity
    6. managing mcp connections in adk

      • mcptoolset manages the lifecycle of mcp connections within adk
      • using an exit_stack ensures connections are properly terminated when execution completes

    ⚠️ troubleshooting

    1. api key issues:

      • adk expects google_api_key instead of gemini_api_key
      • if you encounter valueerror: missing key inputs argument!, check that you're using the correct environment variable
      • error message: valueerror: missing key inputs argument! to use the google ai api, provide (api_key) arguments. to use the google cloud api, provide (vertexai, project & location) arguments.
    2. rate limiting:

      • you may encounter 429 rate-limit errors: google.genai.errors.clienterror: 429 resource_exhausted
      • consider implementing retries with exponential backoff
    3. mcp connection issues:

      • ensure the mcp server is properly installed and accessible
      • check that your serpapi key is correctly configured
    4. internal server errors:

      • you may occasionally see 500 internal server errors from the gemini api
      • these can often be resolved by retrying the request after a short delay

    📚 official documentation references

    for more detailed information about adk and mcp, refer to the official documentation:

    📦 repository

    this project is available on github at arjunprabhulal/adk-python-mcp-client.

    👨‍💻 author

    created by arjun prabhulal. for more articles on ai/ml and generative ai, follow arjun prabhulal on medium.

    Star History

    Star History

    Apr 12Apr 15Apr 19Apr 23May 8May 16Jun 4Jun 2307142128
    Powered by MSeeP Analytics

    About the Project

    This app has not been claimed by its owner yet.

    Claim Ownership

    Receive Updates

    Security Updates

    Get notified about trust rating changes

    to receive email notifications.