Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: A Unique Way to Primary Key

      July 22, 2025

      BrowserStack launches Figma plugin for detecting accessibility issues in design phase

      July 22, 2025

      Parasoft brings agentic AI to service virtualization in latest release

      July 22, 2025

      Node.js vs. Python for Backend: 7 Reasons C-Level Leaders Choose Node.js Talent

      July 21, 2025

      The best CRM software with email marketing in 2025: Expert tested and reviewed

      July 22, 2025

      This multi-port car charger can power 4 gadgets at once – and it’s surprisingly cheap

      July 22, 2025

      I’m a wearables editor and here are the 7 Pixel Watch 4 rumors I’m most curious about

      July 22, 2025

      8 ways I quickly leveled up my Linux skills – and you can too

      July 22, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025
      Recent

      The Intersection of Agile and Accessibility – A Series on Designing for Everyone

      July 22, 2025

      Zero Trust & Cybersecurity Mesh: Your Org’s Survival Guide

      July 22, 2025

      Execute Ping Commands and Get Back Structured Data in PHP

      July 22, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025
      Recent

      A Tomb Raider composer has been jailed — His legacy overshadowed by $75k+ in loan fraud

      July 22, 2025

      “I don’t think I changed his mind” — NVIDIA CEO comments on H20 AI GPU sales resuming in China following a meeting with President Trump

      July 22, 2025

      Galaxy Z Fold 7 review: Six years later — Samsung finally cracks the foldable code

      July 22, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»Machine Learning»A Step-by-Step Coding Guide to Defining Custom Model Context Protocol (MCP) Server and Client Tools with FastMCP and Integrating Them into Google Gemini 2.0’s Function‑Calling Workflow

    A Step-by-Step Coding Guide to Defining Custom Model Context Protocol (MCP) Server and Client Tools with FastMCP and Integrating Them into Google Gemini 2.0’s Function‑Calling Workflow

    April 21, 2025

    In this Colab‑ready tutorial, we demonstrate how to integrate Google’s Gemini 2.0 generative AI with an in‑process Model Context Protocol (MCP) server, using FastMCP. Starting with an interactive getpass prompt to capture your GEMINI_API_KEY securely, we install and configure all necessary dependencies: the google‑genai Python client for calling the Gemini API, fastmcp for defining and hosting our MCP tools in‑process, httpx for making HTTP requests to the Open‑Meteo weather API, and nest_asyncio to patch Colab’s already‑running asyncio event loop. The workflow proceeds by spinning up a minimal FastMCP “weather” server with two tools, get_weather(latitude, longitude) for a three‑day forecast and get_alerts(state) for state‑level weather alerts, then creating a FastMCPTransport to connect an MCP client to that server. Finally, using the Gemini function‑calling feature, we send a natural‑language prompt to Gemini, have it emit a function call based on our explicit JSON schemas, and then execute that call via the MCP client, returning structured weather data into our notebook.

    Copy CodeCopiedUse a different Browser
    from getpass import getpass
    import os
    
    
    api_key = getpass("Enter your GEMINI_API_KEY: ")
    os.environ["GEMINI_API_KEY"] = api_key

    We securely prompt you to enter your Gemini API key (without displaying it on the screen) and then store it in the GEMINI_API_KEY environment variable, allowing the rest of your notebook to authenticate with Google’s API.

    Copy CodeCopiedUse a different Browser
    !pip install -q google-genai mcp fastmcp httpx nest_asyncio

    We install all the core dependencies needed for our Colab notebook in one go—google‑genai for interacting with the Gemini API, mcp and fastmcp for building and hosting our Model Context Protocol server and client, httpx for making HTTP requests to external APIs, and nest_asyncio to patch the event loop so our async code runs smoothly.

    Copy CodeCopiedUse a different Browser

    We apply the nest_asyncio patch to the notebook’s existing event loop, allowing us to run asyncio coroutines (like our MCP client interactions) without encountering “event loop already running” errors.

    Copy CodeCopiedUse a different Browser
    from fastmcp import FastMCP
    import httpx
    
    
    mcp_server = FastMCP("weather")
    
    
    @mcp_server.tool()
    def get_weather(latitude: float, longitude: float) -> str:
        """3‑day min/max temperature forecast via Open‑Meteo."""
        url = (
            f"https://api.open-meteo.com/v1/forecast"
            f"?latitude={latitude}&longitude={longitude}"
            "&daily=temperature_2m_min,temperature_2m_max&timezone=UTC"
        )
        resp = httpx.get(url, timeout=10)
        daily = resp.json()["daily"]
        return "n".join(
            f"{date}: low {mn}°C, high {mx}°C"
            for date, mn, mx in zip(
                daily["time"],
                daily["temperature_2m_min"],
                daily["temperature_2m_max"],
            )
        )
    
    
    @mcp_server.tool()
    def get_alerts(state: str) -> str:
        """Dummy US‑state alerts."""
        return f"No active weather alerts for {state.upper()}."

    We create an in‑process FastMCP server named “weather” and register two tools: get_weather(latitude, longitude), which fetches and formats a 3‑day temperature forecast from the Open‑Meteo API using httpx, and get_alerts(state), which returns a placeholder message for U.S. state weather alerts.

    Copy CodeCopiedUse a different Browser
    import asyncio
    from google import genai
    from google.genai import types
    from fastmcp import Client as MCPClient
    from fastmcp.client.transports import FastMCPTransport

    We import the core libraries for our MCP‑Gemini integration: asyncio to run asynchronous code, google‑genai and its types module for calling Gemini and defining function‑calling schemas, and FastMCP’s Client (aliased as MCPClient) with its FastMCPTransport to connect our in‑process weather server to the MCP client.

    Copy CodeCopiedUse a different Browser
    client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
    MODEL = "gemini-2.0-flash"
    transport = FastMCPTransport(mcp_server)
    

    We initialize the Google Gemini client using the GEMINI_API_KEY from your environment, specify the gemini-2.0-flash model for function‑calling, and set up a FastMCPTransport that connects the in‑process mcp_server to the MCP client.

    Copy CodeCopiedUse a different Browser
    function_declarations = [
        {
            "name": "get_weather",
            "description": "Return a 3‑day min/max temperature forecast for given coordinates.",
            "parameters": {
                "type": "object",
                "properties": {
                    "latitude": {
                        "type": "number",
                        "description": "Latitude of target location."
                    },
                    "longitude": {
                        "type": "number",
                        "description": "Longitude of target location."
                    }
                },
                "required": ["latitude", "longitude"]
            }
        },
        {
            "name": "get_alerts",
            "description": "Return any active weather alerts for a given U.S. state.",
            "parameters": {
                "type": "object",
                "properties": {
                    "state": {
                        "type": "string",
                        "description": "Two‑letter U.S. state code, e.g. 'CA'."
                    }
                },
                "required": ["state"]
            }
        }
    ]
    
    
    tool_defs = types.Tool(function_declarations=function_declarations)
    

    We manually define the JSON schema specifications for our two MCP tools, get_weather (which accepts latitude and longitude as numeric inputs) and get_alerts (which accepts a U.S. state code as a string), including names, descriptions, required properties, and data types. It then wraps these declarations in types. Tool object (tool_defs), which informs Gemini how to generate and validate the corresponding function calls.

    Copy CodeCopiedUse a different Browser
    async def run_gemini(lat: float, lon: float):
        async with MCPClient(transport) as mcp_client:
            prompt = f"Give me a 3‑day weather forecast for latitude={lat}, longitude={lon}."
            response = client.models.generate_content(
                model=MODEL,
                contents=[prompt],
                config=types.GenerateContentConfig(
                    temperature=0,
                    tools=[tool_defs]
                )
            )
    
    
            call = response.candidates[0].content.parts[0].function_call
            if not call:
                print("No function call; GPT said:", response.text)
                return
    
    
            print("🔧 Gemini wants:", call.name, call.args)
    
    
            result = await mcp_client.call_tool(call.name, call.args)
            print("n📋 Tool result:n", result)
    
    
    asyncio.get_event_loop().run_until_complete(run_gemini(37.7749, -122.4194))

    Finally, this async function run_gemini opens an MCP client session over our in‑process transport, sends a natural‑language prompt to Gemini asking for a 3‑day forecast at the given coordinates, captures the resulting function call (if any), invokes the corresponding MCP tool, and prints out the structured weather data, all of which is kicked off by running it in the notebook’s event loop with run_until_complete.

    In conclusion, we have a fully contained pipeline that showcases how to define custom MCP tools in Python, expose them via FastMCP, and seamlessly integrate them with Google’s Gemini 2.0 model using the google‑genai client. The key frameworks, FastMCP for MCP hosting, FastMCPTransport and MCPClient for transport and invocation, httpx for external API access, and nest_asyncio for Colab compatibility, work together to enable real‑time function calling without external processes or stdio pipes. This pattern simplifies local development and testing of MCP integrations in Colab and provides a template for building more advanced agentic applications that combine LLM reasoning with specialized domain tools.


    Here is the Colab Notebook. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 90k+ ML SubReddit.

    🔥 [Register Now] miniCON Virtual Conference on AGENTIC AI: FREE REGISTRATION + Certificate of Attendance + 4 Hour Short Event (May 21, 9 am- 1 pm PST) + Hands on Workshop

    The post A Step-by-Step Coding Guide to Defining Custom Model Context Protocol (MCP) Server and Client Tools with FastMCP and Integrating Them into Google Gemini 2.0’s Function‑Calling Workflow appeared first on MarkTechPost.

    Source: Read More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleServerless MCP Brings AI-Assisted Debugging to AWS Workflows Within Modern IDEs
    Next Article Stanford Researchers Propose FramePack: A Compression-based AI Framework to Tackle Drifting and Forgetting in Long-Sequence Video Generation Using Efficient Context Management and Sampling

    Related Posts

    Machine Learning

    How to Evaluate Jailbreak Methods: A Case Study with the StrongREJECT Benchmark

    July 22, 2025
    Machine Learning

    Boolformer: Symbolic Regression of Logic Functions with Transformers

    July 22, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-24291 – “Versa Networks Director Java Argument Injection Vulnerability”

    Common Vulnerabilities and Exposures (CVEs)

    Node.js Streams with TypeScript

    Development

    CVE-2025-47814 – GNU PSPP Zip-Reader Heap-Based Buffer Overflow

    Common Vulnerabilities and Exposures (CVEs)

    Top Cisco Authorized Reseller in India

    Web Development

    Highlights

    CVE-2025-54079 – WeGIA SQL Injection Vulnerability

    July 18, 2025

    CVE ID : CVE-2025-54079

    Published : July 18, 2025, 4:15 p.m. | 1 hour, 3 minutes ago

    Description : WeGIA is an open source web manager with a focus on the Portuguese language and charitable institutions. A SQL Injection vulnerability was identified in versions prior to 3.4.6 in the endpoint `/html/atendido/Profile_Atendido.php`, in the `idatendido` parameter. This vulnerability allow an authorized attacker to execute arbitrary SQL queries, allowing access to sensitive information. Version 3.4.6 fixes the issue.

    Severity: 0.0 | NA

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    First Copy Watches Online | FREE Shipping & COD Available

    June 2, 2025

    Playlifin – sync YouTube playlists to Jellyfin

    July 10, 2025

    The best anti-Prime Day deals 2025 from Best Buy, Walmart, & more: Top sales from Amazon’s competition

    June 18, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.