<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Indranil Ganguly on Medium]]></title>
        <description><![CDATA[Stories by Indranil Ganguly on Medium]]></description>
        <link>https://medium.com/@indranil.rockin?source=rss-edafd884b9a7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*3YvDrmrrnqVhXR4GRSMUlw.png</url>
            <title>Stories by Indranil Ganguly on Medium</title>
            <link>https://medium.com/@indranil.rockin?source=rss-edafd884b9a7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:30:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@indranil.rockin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Hands-on with MCP: Building a Real-Time Stock Price Tracker]]></title>
            <link>https://medium.com/@indranil.rockin/hands-on-with-mcp-building-a-real-time-stock-price-tracker-a00b7cb9d75b?source=rss-edafd884b9a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00b7cb9d75b</guid>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Indranil Ganguly]]></dc:creator>
            <pubDate>Fri, 18 Apr 2025 08:43:18 GMT</pubDate>
            <atom:updated>2025-04-18T10:54:43.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMhiiiOT8GOVL-nUI4zNkA.jpeg" /></figure><p>The tech world is abuzz with the Model Context Protocol (MCP), with some even hailing it as a “game-changer” (yes, the hype is real!). You might have already encountered the USB-C analogy, hinting at its potential for universal connectivity.</p><p>But this isn’t another explanation of what MCP <em>is</em>. Instead, we’ll dive into the practicalities: how you can actually start implementing it. Before we get our hands dirty with code, let’s quickly recap the essentials.</p><p><strong>What exactly is MCP?</strong></p><p>Developed by Anthropic, the Model Context Protocol (MCP) is an open standard designed to streamline how AI applications — think chatbots, IDE assistants, and custom agents — interact with external tools, data sources, and other systems.</p><p>At its core, MCP provides a clear and consistent blueprint for AI systems to discover, access, and utilize external capabilities, whether it’s querying a database or executing a specific function. This ability to leverage external tools allows models to transcend the limitations of their static training data, leading to enhanced adaptability and a more grounded understanding of the real world.</p><p><strong>The Architecture: Client-Server at Play</strong></p><p>MCP employs a client-server architecture to supercharge Large Language Models (LLMs). The server side is built around three key concepts:</p><ul><li><strong>Model-Controlled Tools:</strong> These are essentially executable functions that LLMs can call (using function calling mechanisms) to perform specific actions, like interacting with APIs.</li><li><strong>Application-Controlled Resources:</strong> These act as read-only data repositories, similar to RESTful GET endpoints. They provide LLMs with contextual information efficiently, without requiring computation or causing side effects.</li><li><strong>User-Controlled Prompts:</strong> These are pre-defined templates that optimize how LLMs utilize the available tools and resources during inference.</li></ul><p>The <strong>MCP Protocol</strong> itself is the standardized language governing communication between clients and servers. It dictates message formats, how servers announce their capabilities, the structure of AI queries and commands, and the format of results. Importantly, MCP is transport-agnostic, working seamlessly across web connections (HTTP/WebSockets) and local communication (standard IO). By using structured data like JSON, it ensures a consistent “grammar” for interaction. This means an AI can effortlessly switch between different MCP servers (imagine connecting to a design tool and then a data analysis tool) because the underlying communication method remains the same.</p><figure><img alt="Source: Anthropic MCP Documentation" src="https://cdn-images-1.medium.com/max/662/1*YfHfNn1_z8y5_RJEHIGA5w.png" /><figcaption>Source: Anthropic Official Documentation</figcaption></figure><p>For those eager to delve deeper into the architectural nuances, the <a href="https://modelcontextprotocol.io/introduction">official documentation</a> is your go-to resource.</p><p><strong>Getting Started: Beyond the Claude Desktop</strong></p><p>If you’ve explored online examples, you’ve likely noticed a strong emphasis on Claude Desktop and stdio transport. While those are valid starting points, the beauty of MCP lies in its flexibility.</p><p>Regardless of whether you’re building your server in Python, TypeScript, Java, or Rust, the crucial requirement is the ability to communicate using supported transports. The primary modes of interaction between clients and servers are:</p><ul><li><strong>stdio (Standard Input/Output):</strong> A straightforward and effective method for local integrations when the client and server reside on the same machine.</li><li><strong>HTTP with Server-Sent Events (SSE):</strong> A powerful approach that enables the server to proactively push messages to the client over a persistent HTTP connection.</li></ul><p>In this post, we’ll walk through building a “stock price tracker” MCP Server, leveraging SSE to establish real-time communication between the client and the server.</p><pre>import os<br>import subprocess  # For executing shell commands<br>from mcp.server.fastmcp import FastMCP  # High-level MCP wrapper for defining and exposing tools<br>from mcp.server import Server  # Underlying MCP server abstraction<br>from mcp.server.sse import SseServerTransport  # Transport layer for Server-Sent Events<br><br>from starlette.applications import Starlette  # ASGI web framework for building applications<br>from starlette.routing import Route, Mount  # Mechanisms for defining HTTP and message endpoints<br>from starlette.requests import Request  # Object representing incoming HTTP requests<br>import yfinance as yf  # Library for fetching historical and current stock data<br>import uvicorn  # ASGI server for running Starlette applications<br><br># --------------------------------------------------------------------------------------<br># STEP 1: Initialize FastMCP — the central component for defining and managing tools<br># --------------------------------------------------------------------------------------<br># Create a FastMCP instance with a descriptive name for the server<br>mcp = FastMCP(&quot;Stock Price SSE Server&quot;)<br><br>@mcp.tool()<br>def get_stock_price(symbol: str) -&gt; float:<br>    &quot;&quot;&quot;<br>    Retrieves the current stock price for a given ticker symbol.<br><br>    Args:<br>        symbol: The stock ticker symbol (e.g., &#39;AAPL&#39;).<br><br>    Returns:<br>        The latest closing price as a float. Returns -1.0 if price retrieval fails.<br>    &quot;&quot;&quot;<br>    try:<br>        ticker = yf.Ticker(symbol)<br>        # Fetch today&#39;s historical data. This might be empty if the market is closed<br>        # or if the provided symbol is invalid.<br>        data = ticker.history(period=&quot;1d&quot;)<br>        if not data.empty:<br>            # Get the last closing price from the fetched daily data<br>            price = data[&#39;Close&#39;].iloc[-1]<br>            return float(price)<br>        else:<br>            # If daily data is unavailable, attempt to get the regular market price<br>            # from the ticker&#39;s general information.<br>            info = ticker.info<br>            price = info.get(&quot;regularMarketPrice&quot;, None)<br>            if price is not None:<br>                return float(price)<br>            else:<br>                return -1.0  # Indicate failure to retrieve price<br>    except Exception:<br>        # Return -1.0 to signal that an error occurred during the stock price fetch.<br>        return -1.0<br><br>@mcp.resource(&quot;stock://{symbol}&quot;)<br>def stock_resource(symbol: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Exposes the current stock price as a named resource.<br><br>    Args:<br>        symbol: The stock ticker symbol.<br><br>    Returns:<br>        A formatted string containing the current stock price for the given symbol,<br>        or an error message if the price could not be retrieved.<br>    &quot;&quot;&quot;<br>    price = get_stock_price(symbol)<br>    if price &lt; 0:<br>        return f&quot;Error: Could not retrieve price for symbol &#39;{symbol}&#39;.&quot;<br>    return f&quot;The current price of &#39;{symbol}&#39; is ${price:.2f}.&quot;<br><br>@mcp.tool()<br>def get_stock_history(symbol: str, period: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Retrieves historical stock data for a given ticker symbol and time period.<br><br>    Args:<br>        symbol: The stock ticker symbol (e.g., &#39;GOOG&#39;).<br>        period: The time period for historical data (e.g., &#39;1mo&#39;, &#39;3mo&#39;, &#39;1y&#39;, &#39;5y&#39;).<br>                Refer to the yfinance documentation for valid period values.<br><br>    Returns:<br>        A string containing the historical stock data in CSV format.<br>        Returns an error message if data retrieval fails or if no data is found.<br>    &quot;&quot;&quot;<br>    try:<br>        ticker = yf.Ticker(symbol)<br>        data = ticker.history(period=period)<br>        if data.empty:<br>            return f&quot;No historical data found for symbol &#39;{symbol}&#39; with period &#39;{period}&#39;.&quot;<br>        # Convert the pandas DataFrame to a comma-separated value string<br>        csv_data = data.to_csv()<br>        return csv_data<br>    except Exception as e:<br>        return f&quot;Error fetching historical data: {str(e)}&quot;<br><br>@mcp.tool()<br>def compare_stocks(symbol1: str, symbol2: str) -&gt; str:<br>    &quot;&quot;&quot;<br>    Compares the current stock prices of two given ticker symbols.<br><br>    Args:<br>        symbol1: The ticker symbol of the first stock.<br>        symbol2: The ticker symbol of the second stock.<br><br>    Returns:<br>        A formatted string comparing the current prices of the two stocks,<br>        or an error message if price retrieval fails for either symbol.<br>    &quot;&quot;&quot;<br>    price1 = get_stock_price(symbol1)<br>    price2 = get_stock_price(symbol2)<br>    if price1 &lt; 0 or price2 &lt; 0:<br>        return f&quot;Error: Could not retrieve data for comparison of &#39;{symbol1}&#39; and &#39;{symbol2}&#39;.&quot;<br>    if price1 &gt; price2:<br>        result = f&quot;{symbol1} (${price1:.2f}) is higher than {symbol2} (${price2:.2f}).&quot;<br>    elif price1 &lt; price2:<br>        result = f&quot;{symbol1} (${price1:.2f}) is lower than {symbol2} (${price2:.2f}).&quot;<br>    else:<br>        result = f&quot;Both {symbol1} and {symbol2} have the same price (${price1:.2f}).&quot;<br>    return result<br><br><br># --------------------------------------------------------------------------------------<br># STEP 2: Create a Starlette application to expose MCP tools over HTTP using SSE<br># --------------------------------------------------------------------------------------<br>def create_starlette_app(mcp_server: Server, *, debug: bool = False) -&gt; Starlette:<br>    &quot;&quot;&quot;<br>    Constructs a Starlette web application with endpoints for Server-Sent Events (SSE)<br>    and message handling, integrating the MCP server.<br><br>    Args:<br>        mcp_server: The underlying MCP server instance.<br>        debug: A boolean indicating whether to enable debug mode for the Starlette app.<br><br>    Returns:<br>        A Starlette application instance with configured routes for SSE communication.<br>    &quot;&quot;&quot;<br>    # Initialize the SSE transport handler, defining the endpoint for SSE connections<br>    sse = SseServerTransport(&quot;/messages/&quot;)<br><br>    # Define an asynchronous function to handle incoming SSE client connections<br>    async def handle_sse(request: Request) -&gt; None:<br>        &quot;&quot;&quot;<br>        Handles a new client connection to the Server-Sent Events endpoint (`/sse`).<br>        It establishes an SSE connection and links the client&#39;s read and write streams<br>        to the MCP server for communication.<br>        &quot;&quot;&quot;<br>        # Establish an SSE connection context. Upon entering, the connection is active;<br>        # upon exiting, it&#39;s closed. The context provides read and write streams.<br>        async with sse.connect_sse(<br>            request.scope,<br>            request.receive,<br>            request._send,  # Low-level asynchronous send function provided by Starlette<br>        ) as (read_stream, write_stream):<br>            # Run the MCP server, passing the client&#39;s input and output streams.<br>            # Also provide initial options for the MCP server upon connection.<br>            await mcp_server.run(<br>                read_stream,<br>                write_stream,<br>                mcp_server.create_initialization_options(),<br>            )<br><br>    # Create and return the Starlette application with defined routes<br>    return Starlette(<br>        debug=debug,<br>        routes=[<br>            Route(&quot;/sse&quot;, endpoint=handle_sse),          # Endpoint for initiating SSE connections<br>            Mount(&quot;/messages/&quot;, app=sse.handle_post_message),  # Endpoint for receiving POST messages<br>        ],<br>    )<br><br><br># --------------------------------------------------------------------------------------<br># STEP 3: Start the Uvicorn server if this script is executed directly<br># --------------------------------------------------------------------------------------<br>if __name__ == &quot;__main__&quot;:<br>    # Access the underlying MCP server instance from the FastMCP wrapper<br>    mcp_server = mcp._mcp_server  # Accessing a protected member is acceptable in this context<br><br>    # Use argparse to handle command-line arguments for controlling the server&#39;s host and port<br>    import argparse<br><br>    parser = argparse.ArgumentParser(description=&#39;Run MCP SSE-based server&#39;)<br>    parser.add_argument(&#39;--host&#39;, default=&#39;0.0.0.0&#39;, help=&#39;Host IP address to bind the server to&#39;)<br>    parser.add_argument(&#39;--port&#39;, type=int, default=8081, help=&#39;Port number to listen for incoming connections&#39;)<br>    args = parser.parse_args()<br><br>    # Create the Starlette application, enabling debug mode for development<br>    starlette_app = create_starlette_app(mcp_server, debug=True)<br><br>    # Launch the Uvicorn ASGI server to run the Starlette application<br>    uvicorn.run(starlette_app, host=args.host, port=args.port)<br><br># To run this server, execute the script from your terminal using:<br># python your_script_name.py --host 0.0.0.0 --port 8081</pre><p>To enable SSE communication, your server needs to expose two key endpoints:</p><ul><li>/sse: This is where the client initiates the connection with an HTTP GET request. The server keeps this connection alive to send responses back to the client using SSE.</li><li>/messages: Clients use HTTP POST requests to send messages to this endpoint. The server processes these messages and sends replies back through the established SSE connection.</li></ul><p>In our server-side code, the SSEServerTransport manages the /sse endpoint, and each connected client&#39;s session is stored in a transports object. This design allows multiple clients to connect and interact concurrently without interference.</p><p>Another fundamental aspect of MCP demonstrated in the code is the use of <strong>tools</strong> and <strong>resources</strong>. Tools empower servers to expose executable functions that clients (and the LLMs they utilize) can invoke to perform specific actions. In our example, we’ve implemented three tools: get_stock_price, compare_stocks, and get_stock_history. Defining these tools is remarkably simple, thanks to the @mcp.tool() decorator.</p><p>Next, we created a Starlette application to expose these MCP tools over HTTP using SSE. The rest of the server-side code is designed to be intuitive and self-explanatory.</p><p><strong>Building the MCP Client</strong></p><p>Now that our MCP Server is up and running, the next crucial step is to create an MCP client to interact with it.</p><pre>import asyncio  # Enables asynchronous programming for non-blocking operations.<br>import os  # Provides a way to interact with the operating system, like accessing environment variables.<br>import sys  # Offers access to system-specific parameters and functions, such as command-line arguments.<br>import json  # Facilitates working with JSON (JavaScript Object Notation) data.<br>from typing import Optional  # Used for type hinting, indicating that a variable can hold a value or be None.<br><br># Imports the ClientSession class from the &#39;mcp&#39; package.<br># This class is responsible for managing the communication session with the MCP server.<br>from mcp import ClientSession<br><br># Imports the &#39;sse_client&#39; helper from the &#39;mcp.client.sse&#39; module.<br># It&#39;s assumed to be an asynchronous context manager for handling Server-Sent Events (SSE) connections.<br># It provides the streams (reader and writer) needed for SSE communication.<br>from mcp.client.sse import sse_client<br><br># Imports necessary components from the Google Gemini SDK for AI functionalities.<br># These include generating content, defining tools, and configuring the generation process.<br>from google import genai<br>from google.genai import types<br>from google.genai.types import Tool, FunctionDeclaration<br>from google.genai.types import GenerateContentConfig<br><br><br>class MCPClient:<br>    def __init__(self):<br>        &quot;&quot;&quot;<br>        Initializes the MCP client.<br><br>        This constructor performs the following setup:<br>        - Initializes the Gemini AI client using the API key sourced from environment variables.<br>        - Creates placeholders for the MCP client session and the SSE stream context manager.<br><br>        The Gemini client is used for generating content based on user queries and has the capability<br>        to request the invocation of external tools.<br>        &quot;&quot;&quot;<br>        # Placeholder for the MCP session object, which will manage communication with the MCP server.<br>        self.session: Optional[ClientSession] = None<br><br>        # Context managers for managing the lifecycle of the SSE connection and the MCP session.<br>        self._streams_context = None  # Manages the establishment and termination of the SSE stream.<br>        self._session_context = None  # Manages the lifecycle of the MCP client session.<br><br>        # Retrieves the Gemini API key.<br>        # In a production environment, it&#39;s recommended to fetch this from environment variables or a secure configuration.<br>        gemini_api_key = &quot;xxx&quot;<br>        if not gemini_api_key:<br>            raise ValueError(&quot;GEMINI_API_KEY not found. Please ensure it is properly configured.&quot;)<br><br>        # Initializes the Gemini client with the provided API key.<br>        # This client object will be used to interact with the Gemini AI models.<br>        self.genai_client = genai.Client(api_key=gemini_api_key)<br><br>    async def connect_to_sse_server(self, server_url: str):<br>        &quot;&quot;&quot;<br>        Establishes a connection to an MCP server utilizing Server-Sent Events (SSE) for communication.<br><br>        This asynchronous function performs the following steps:<br>        1. Opens an SSE connection to the specified server URL.<br>        2. Obtains the reader and writer streams from the SSE connection.<br>        3. Creates an MCP ClientSession instance using these streams.<br>        4. Initializes the MCP session to establish communication with the server.<br>        5. Retrieves and displays the list of tools available on the MCP server.<br><br>        Args:<br>            server_url (str): The URL of the MCP server that supports SSE.<br>        &quot;&quot;&quot;<br>        # 1. Initiates an SSE connection to the server using the provided URL.<br>        #    The &#39;sse_client&#39; function acts as an asynchronous context manager,<br>        #    yielding the input and output streams for data exchange.<br>        self._streams_context = sse_client(url=server_url)<br>        # Enters the asynchronous context to acquire the communication streams.<br>        # This ensures proper setup and teardown of the SSE connection.<br>        streams = await self._streams_context.__aenter__()<br>        # &#39;streams&#39; is expected to be a tuple containing the reader and writer objects<br>        # that will be used by the ClientSession for communication.<br><br>        # 2. Creates an MCP ClientSession instance, passing the communication streams.<br>        #    The ClientSession is responsible for handling the MCP protocol over the established streams.<br>        self._session_context = ClientSession(*streams)<br>        self.session: ClientSession = await self._session_context.__aenter__()<br><br>        # 3. Initializes the MCP session with the server.<br>        #    This step typically involves sending an initial message to the server<br>        #    to negotiate communication parameters and establish the protocol.<br>        await self.session.initialize()<br><br>        # 4. Retrieves and displays the list of tools exposed by the MCP server.<br>        #    This confirms a successful connection and provides information about available functionalities.<br>        print(&quot;Initialized SSE client...&quot;)<br>        print(&quot;Listing tools...&quot;)<br>        response = await self.session.list_tools()<br>        tools = response.tools<br>        print(&quot;\nConnected to server with tools:&quot;, [tool.name for tool in tools])<br><br>        # 5. Converts the retrieved MCP tool definitions into a format compatible with Gemini&#39;s function calling feature.<br>        self.function_declarations = convert_mcp_tools_to_gemini(tools)<br><br>    async def cleanup(self):<br>        &quot;&quot;&quot;<br>        Releases resources by gracefully closing the SSE session and stream contexts.<br><br>        Since asynchronous context managers were used for managing the session and streams,<br>        their exit methods need to be explicitly called to ensure proper cleanup.<br>        This guarantees that network connections and other resources are closed when the client is done.<br>        &quot;&quot;&quot;<br>        # If the MCP session context exists, exit it to close the session.<br>        if self._session_context:<br>            await self._session_context.__aexit__(None, None, None)<br>        # If the SSE stream context exists, exit it to close the underlying SSE connection.<br>        if self._streams_context:<br>            await self._streams_context.__aexit__(None, None, None)<br><br>    async def process_query(self, query: str) -&gt; str:<br>        &quot;&quot;&quot;<br>        Processes a user query using the Gemini API.<br><br>        If Gemini&#39;s response includes a request to call a tool (function calling),<br>        this function will invoke the corresponding tool on the MCP server and then<br>        send the tool&#39;s result back to Gemini to generate a final response.<br><br>        Steps involved:<br>        1. Formats the user&#39;s query into a structured content object for Gemini.<br>        2. Sends the query to the Gemini model, including the definitions of available MCP tools.<br>        3. Checks if Gemini&#39;s response contains a function call. If so, it executes the tool<br>           on the MCP server and prepares a function response.<br>        4. If a tool was called, it sends the original query, the function call details,<br>           and the tool&#39;s response back to Gemini for the final answer generation.<br>        5. Returns the final text response from Gemini.<br><br>        Args:<br>            query (str): The user&#39;s input query.<br><br>        Returns:<br>            str: The final text response generated by the Gemini model.<br>        &quot;&quot;&quot;<br>        # 1. Constructs a Gemini Content object representing the user&#39;s query.<br>        #    This object specifies the &#39;user&#39; role and contains the query text.<br>        user_prompt_content = types.Content(<br>            role=&#39;user&#39;,<br>            parts=[types.Part.from_text(text=query)]<br>        )<br><br>        # 2. Sends the user&#39;s query to the Gemini model for processing.<br>        #    The &#39;tools&#39; parameter in the configuration provides Gemini with the<br>        #    declarations of the available MCP tools, enabling function calling.<br>        response = self.genai_client.models.generate_content(<br>            model=&#39;gemini-2.0-flash&#39;,  # Specifies the Gemini model to be used.<br>            contents=[user_prompt_content],<br>            config=types.GenerateContentConfig(<br>                tools=self.function_declarations,  # Passes the list of MCP tools formatted for Gemini.<br>            ),<br>        )<br><br>        # Initializes an empty list to accumulate the text parts of the final response.<br>        final_text = []<br><br>        # 3. Iterates through each candidate response provided by Gemini.<br>        for candidate in response.candidates:<br>            if candidate.content.parts:  # Checks if the candidate response has any content parts.<br>                for part in candidate.content.parts:<br>                    # Detects if the current part of the response is a function call request from Gemini.<br>                    if part.function_call:<br>                        # Extracts the name of the requested tool and its arguments.<br>                        tool_name = part.function_call.name<br>                        tool_args = part.function_call.args<br>                        print(f&quot;\n[Gemini requested tool call: {tool_name} with args {tool_args}]&quot;)<br><br>                        # Attempts to invoke the requested tool on the MCP server.<br>                        try:<br>                            result = await self.session.call_tool(tool_name, tool_args)<br>                            # Formats the tool&#39;s result into a dictionary with the key &quot;result&quot;.<br>                            function_response = {&quot;result&quot;: result.content}<br>                        except Exception as e:<br>                            # If an error occurs during tool execution, captures the error message.<br>                            function_response = {&quot;error&quot;: str(e)}<br><br>                        # Creates a Gemini function response part containing the result of the tool call.<br>                        function_response_part = types.Part.from_function_response(<br>                            name=tool_name,<br>                            response=function_response<br>                        )<br><br>                        # Wraps the function response part in a Content object, specifying the &#39;tool&#39; role.<br>                        function_response_content = types.Content(<br>                            role=&#39;tool&#39;,<br>                            parts=[function_response_part]<br>                        )<br><br>                        # 4. Sends the original query, the function call, and the tool&#39;s response back to Gemini.<br>                        #    This allows Gemini to incorporate the tool&#39;s output into its final answer.<br>                        response = self.genai_client.models.generate_content(<br>                            model=&#39;gemini-2.0-flash-001&#39;,<br>                            contents=[<br>                                user_prompt_content,      # The initial user query.<br>                                part,                     # The function call requested by Gemini.<br>                                function_response_content, # The result from executing the tool.<br>                            ],<br>                            config=types.GenerateContentConfig(<br>                                tools=self.function_declarations,<br>                            ),<br>                        )<br><br>                        # Appends the text from the first part of Gemini&#39;s new response<br>                        # (which should incorporate the tool&#39;s result).<br>                        final_text.append(response.candidates[0].content.parts[0].text)<br>                    else:<br>                        # If the part is not a function call, it&#39;s regular text from Gemini, so append it.<br>                        final_text.append(part.text)<br><br>        # 5. Joins all the collected text parts into a single string, separated by newlines.<br>        return &quot;\n&quot;.join(final_text)<br><br>    async def chat_loop(self):<br>        &quot;&quot;&quot;<br>        Runs an interactive chat loop in the terminal.<br><br>        This function continuously prompts the user for input and processes each query<br>        using the &#39;process_query&#39; method. The loop continues until the user enters &#39;quit&#39;.<br>        The response from processing each query is then printed to the console.<br>        &quot;&quot;&quot;<br>        print(&quot;\nMCP Client Started! Type &#39;quit&#39; to exit.&quot;)<br><br>        while True:<br>            # Prompts the user to enter a query.<br>            query = input(&quot;\nQuery: &quot;).strip()<br>            if query.lower() == &#39;quit&#39;:<br>                break  # Exits the chat loop if the user types &#39;quit&#39;.<br><br>            # Processes the user&#39;s query, which may involve calling tools on the MCP server.<br>            response = await self.process_query(query)<br>            # Prints the final response received from Gemini.<br>            print(&quot;\n&quot; + response)<br><br><br>def clean_schema(schema):<br>    &quot;&quot;&quot;<br>    Recursively removes &#39;title&#39; fields from a JSON schema.<br><br>    Some JSON schemas include &#39;title&#39; fields that are not necessary for tool function calls.<br>    This function traverses the schema and removes any &#39;title&#39; entries, including those within nested structures.<br><br>    Args:<br>        schema (dict): A dictionary representing a JSON schema.<br><br>    Returns:<br>        dict: The cleaned JSON schema without any &#39;title&#39; fields.<br>    &quot;&quot;&quot;<br>    if isinstance(schema, dict):<br>        # Removes the &#39;title&#39; key from the current level of the dictionary if it exists.<br>        schema.pop(&quot;title&quot;, None)<br>        # If the schema has a &quot;properties&quot; key (common in JSON schema for defining object properties)<br>        # and its value is a dictionary, recursively process each property.<br>        if &quot;properties&quot; in schema and isinstance(schema[&quot;properties&quot;], dict):<br>            for key in schema[&quot;properties&quot;]:<br>                schema[&quot;properties&quot;][key] = clean_schema(schema[&quot;properties&quot;][key])<br>    return schema<br><br><br>def convert_mcp_tools_to_gemini(mcp_tools):<br>    &quot;&quot;&quot;<br>    Converts a list of MCP tool definitions into Gemini-compatible function declarations.<br><br>    Each MCP tool object contains metadata like its name, a description, and an input JSON schema.<br>    This function cleans the input schema by removing irrelevant fields (like &#39;title&#39;) and then<br>    constructs a Gemini &#39;FunctionDeclaration&#39; for each tool. These declarations are then wrapped<br>    within Gemini &#39;Tool&#39; objects.<br><br>    Args:<br>        mcp_tools (list): A list of MCP tool objects, each with attributes &#39;name&#39;, &#39;description&#39;, and &#39;inputSchema&#39;.<br><br>    Returns:<br>        list: A list of Gemini &#39;Tool&#39; objects, ready to be used for function calling.<br>    &quot;&quot;&quot;<br>    gemini_tools = []<br><br>    for tool in mcp_tools:<br>        # Cleans the input schema of the current MCP tool to remove unnecessary &#39;title&#39; fields.<br>        parameters = clean_schema(tool.inputSchema)<br><br>        # Creates a Gemini &#39;FunctionDeclaration&#39; that describes how Gemini can invoke this tool.<br>        function_declaration = FunctionDeclaration(<br>            name=tool.name,<br>            description=tool.description,<br>            parameters=parameters<br>        )<br><br>        # Wraps the function declaration within a Gemini &#39;Tool&#39; object.<br>        # Gemini&#39;s function calling mechanism expects tools to be provided in this format.<br>        gemini_tool = Tool(function_declarations=[function_declaration])<br>        gemini_tools.append(gemini_tool)<br><br>    return gemini_tools<br><br><br>async def main():<br>    &quot;&quot;&quot;<br>    The main entry point for the MCP client application.<br><br>    This asynchronous function:<br>    - Checks if the server URL is provided as a command-line argument.<br>    - Creates an instance of the MCPClient.<br>    - Establishes a connection to the MCP server using the provided SSE URL.<br>    - Starts an interactive chat loop to allow the user to send queries.<br>    - Ensures that all resources are properly cleaned up after the chat loop finishes or if an error occurs.<br><br>    Usage:<br>        python client_sse.py &lt;server_url&gt;<br>    &quot;&quot;&quot;<br>    if len(sys.argv) &lt; 2:<br>        print(&quot;Usage: python client_sse.py &lt;server_url&gt;&quot;)<br>        sys.exit(1)<br><br>    client = MCPClient()<br>    try:<br>        # Connects to the MCP server using the SSE URL provided as a command-line argument.<br>        await client.connect_to_sse_server(sys.argv[1])<br>        # Starts the interactive chat loop, allowing the user to communicate with the server via Gemini.<br>        await client.chat_loop()<br>    finally:<br>        # Ensures that resources (like network connections) are properly closed when the program finishes.<br>        await client.cleanup()<br><br>if __name__ == &quot;__main__&quot;:<br>    # Executes the main asynchronous function using the asyncio event loop.<br>    asyncio.run(main())<br><br># To run this file from the command line:<br># python client_sse.py http://127.0.0.1:8081/sse</pre><p>In the context of MCP, the LLM is a key component of the client, often referred to as the “Host.” In this example, we’re using Google’s Gemini, but the architecture is flexible enough to accommodate any LLM of your choice.</p><p>While the client code might initially appear complex, the underlying logic is quite elegant. This Python script essentially creates a bridge between you (the user), Google’s Gemini AI, and the external tools provided by our MCP server. The client establishes a connection with the MCP server, discovers the available tools, and then forwards your questions to Gemini. If Gemini determines that a specific tool is needed to answer your query effectively, the client instructs the MCP server to execute that tool and then feeds the results back to Gemini. This allows Gemini to generate more informed and accurate responses. The client manages all the underlying communication seamlessly and ensures proper cleanup when you finish your interaction.</p><p><strong>Final Words:</strong></p><p>While Server-Sent Events offer a compelling approach for real-time communication in MCP, it’s important to acknowledge potential challenges when deploying it in production environments. However, given the nascent nature of MCP, we can anticipate significant growth and refinement over time, likely addressing current limitations and paving the way for more robust implementations.</p><p><em>Resources consulted for the blog :</em></p><p><em>1. </em><a href="https://www.youtube.com/watch?v=s0YJNcT1XMA&amp;t=1379s&amp;ab_channel=theailanguage"><em>https://www.youtube.com/watch?v=s0YJNcT1XMA&amp;t=1379s&amp;ab_channel=theailanguage</em></a><em><br>2. </em><a href="https://www.kdnuggets.com/building-a-simple-mcp-server"><em>https://www.kdnuggets.com/building-a-simple-mcp-server</em></a><em><br>3. </em><a href="https://docs.anthropic.com/en/docs/agents-and-tools/mcp"><em>https://docs.anthropic.com/en/docs/agents-and-tools/mcp</em></a><em><br>4. </em><a href="https://www.philschmid.de/mcp-introduction#how-does-mcp-work"><em>https://www.philschmid.de/mcp-introduction#how-does-mcp-work</em></a><br><em>5. </em><a href="https://www.devshorts.in/p/how-to-host-your-mcp-server"><em>https://www.devshorts.in/p/how-to-host-your-mcp-server</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00b7cb9d75b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Object Tracking & Analysis using Qwen2.5 VL & SAMURAI]]></title>
            <link>https://medium.com/@indranil.rockin/object-tracking-analysis-using-vlm-samurai-d8b159fea005?source=rss-edafd884b9a7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8b159fea005</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[segment-anything-model]]></category>
            <dc:creator><![CDATA[Indranil Ganguly]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 17:05:26 GMT</pubDate>
            <atom:updated>2025-02-18T07:20:39.566Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PKqG6jy7FqEZs_YRCwKogg.jpeg" /></figure><p>I’ve always been fascinated by Vision Language Models (VLMs) and their power to merge multiple modalities for innovative solutions. Today, I’m excited to share one of my personal projects: <strong>Tracking &amp; Analyzing Objects and Their Behaviour in Video</strong>.</p><p>The idea struck me when I realized that, like many parents, I receive lengthy CCTV footage from my son’s daycare. With hours of video to sift through, I thought — why not create a system that automatically tracks and analyzes his behavior?</p><h3>The Challenges</h3><p>In developing this solution, I encountered four primary scenarios:</p><ol><li><strong>Variable Conditions:</strong><br>The video conditions aren’t consistent. Some days, poor weather means minimal sunlight (a common scenario in Bangalore), or there might be issues with the lighting. These variations can significantly impact the video quality.</li><li><strong>Similar Appearances:</strong><br>Since all the children are roughly the same age and wear similar uniforms, it will be a struggle to differentiate between them.</li><li><strong>Intermittent Visibility:</strong><br>Sometimes, the child exits the frame temporarily and then reappears. In these cases, the model might have difficulty re-identifying the target, leading to inconsistent results.</li><li><strong>Occlusion:</strong><br>Partial visibility occurs when the child or object is obscured by another object or child, making the object appear incomplete.</li></ol><p>Initially, I attempted to use a single VLM by providing specific descriptions of the object I wanted to track. However, this approach was suboptimal — the model frequently confused the target with other objects that matched the description.</p><h3>My Approach</h3><p>Given these challenges, I opted for a multi-model strategy:</p><ul><li><strong>Object Localization:</strong><br>Accurately isolating the object of interest is crucial for extracting meaningful information. I started with <strong>SAM 2.1</strong>, known for its impressive segmentation and zero-shot capabilities. (You can find more details on SAM 2.1 in <a href="https://github.com/facebookresearch/sam2">this GitHub repository</a>.) I also evaluated YOLOv11, but it didn’t quite meet my needs.</li><li><strong>Addressing Re-Identification Issues:</strong><br>SAM 2.1 sometimes failed to recognize the object when it left and then re-entered the frame — a problem known as re-identification. To overcome this, I integrated <strong>SAMURAI</strong> into my workflow. Built on top of SAM 2.1, SAMURAI is equipped with motion-aware memory that enhances its ability to re-identify objects reliably. (More on SAMURAI can be found in <a href="https://github.com/yangchris11/samurai">this GitHub repository</a>.)</li><li><strong>Frame Processing:</strong><br>Since SAMURAI requires all frames to be loaded into memory for processing, I converted the video into an MP4 file with bounding boxes. While you can process individual frames, this approach streamlined the workflow.</li><li><strong>Choosing the Right VLM:</strong><br>With the object segmented, the next step was selecting a VLM. I explored several open-source options — staying clear of closed-source models like Claude, Gemini, or GPT-4 — to maintain a fully open-source stack. I evaluated models such as LLaMA 3.2 11B Vision Instruct, Qwen 2 VL, Florence 2, and ultimately settled on <strong>Qwen 2.5 VL 7B</strong>. This model proved to be a remarkable upgrade, capturing nuanced details exceptionally well and performing superbly on video data. (For more details on Qwen 2.5 VL 7B, click <a href="https://github.com/QwenLM/Qwen2.5">here</a>.)</li><li><strong>Processing Strategies:</strong><br>Depending on the video length and hardware capabilities, you can either feed the entire video into the model or process it frame by frame. In my tests, shorter videos worked well when processed as a whole, while longer videos were more efficiently handled as individual frames.</li></ul><h3>The Outcome</h3><p>After integrating these models and approaches, I successfully built a system that reliably tracks and analyzes objects in video footage. The results have been promising, providing a robust solution for monitoring and understanding behaviour over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3hX900hnAcmIpZHaOHa_jQ.gif" /></figure><h3>Future Directions</h3><p>I’m eager to continue refining this system. In the future, I plan to explore models like RT-DETRv2 or DAB-DETR, which could offer even more accurate object detection and further enhance the system’s performance.</p><p>Stay tuned for more updates as I push the boundaries of what VLMs can achieve!</p><blockquote>Thanks for reading the article and for your engagement. Your follow and claps mean a lot.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8b159fea005" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>