Skip to main content
Glama
AI2Enginex

MCP Server with Gemini

by AI2Enginex

MCP Server with Gemini — Model Context Protocol Tool Calling

A practical implementation of Model Context Protocol (MCP) using Python, uv, and Google's Gemini API.

This project demonstrates the complete MCP lifecycle:

User → Gemini LLM → Tool Selection → MCP Client → MCP Server → Tool Execution → Tool Result → Gemini → Final Response

The goal of this project is to understand how an LLM can dynamically discover and use external tools through an MCP server rather than having tool implementations directly embedded inside the LLM application.


📌 Project Overview

Large Language Models are powerful at understanding natural language, but they do not inherently have access to external systems such as:

  • APIs

  • Databases

  • Files

  • Web services

  • Internal enterprise systems

  • Custom Python functions

MCP provides a standardized way for an AI application to communicate with external tools and data sources.

In this project:

  1. An MCP Server exposes tools.

  2. An MCP Client connects to the server.

  3. The client retrieves the available tool definitions.

  4. Gemini receives the tool definitions.

  5. Gemini automatically determines whether a tool is required.

  6. The client invokes the selected MCP tool.

  7. The MCP server executes the tool.

  8. The result is returned to the client.

  9. The result is provided back to Gemini.

  10. Gemini generates the final natural-language response.


🏗️ Architecture

                         User
                           │
                           │ Natural Language Query
                           ▼
                  ┌─────────────────┐
                  │   Gemini LLM    │
                  │                 │
                  │ Tool Selection  │
                  └────────┬────────┘
                           │
                           │ Function / Tool Call
                           ▼
                  ┌─────────────────┐
                  │   MCP Client   │
                  │                 │
                  │ • Connects MCP  │
                  │ • Lists Tools   │
                  │ • Calls Tools   │
                  └────────┬────────┘
                           │
                           │ MCP Protocol
                           ▼
                  ┌─────────────────┐
                  │   MCP Server   │
                  │                 │
                  │ Tool Registry   │
                  └────────┬────────┘
                           │
                           ▼
                  ┌─────────────────┐
                  │  Tool Function  │
                  │                 │
                  │ External Logic  │
                  └────────┬────────┘
                           │
                           │ Tool Result
                           ▼
                  ┌─────────────────┐
                  │   MCP Client   │
                  └────────┬────────┘
                           │
                           │ Tool Result
                           ▼
                  ┌─────────────────┐
                  │   Gemini LLM    │
                  │                 │
                  │ Final Response  │
                  └────────┬────────┘
                           │
                           ▼
                         User

🔄 Complete MCP Lifecycle

The implementation demonstrates the following lifecycle.

Related MCP server: MCP Gemini CLI

1. Start MCP Server

The MCP server exposes one or more tools.

For example:

@mcp.tool()
def get_latest_news(company: str):
    ...

The MCP server does not decide when the tool should be used.

It simply exposes the capability.


2. MCP Client Connects to Server

The MCP client establishes a connection with the MCP server.

The client can then communicate with the server using the MCP protocol.

Conceptually:

MCP Client
    │
    │ MCP
    ▼
MCP Server

3. Discover Available Tools

The client asks the MCP server for its available tools.

For example:

Available Tools:

1. get_latest_news
   Description: Fetch latest news for a company

2. get_stock_price
   Description: Get the current stock price

3. calculate_sum
   Description: Add two numbers

The important point is that the client does not need to hard-code every tool.

The tools are discovered from the MCP server.


4. Send Tool Definitions to Gemini

The MCP client converts the discovered MCP tools into a format Gemini can understand as callable functions/tools.

Conceptually:

MCP Tool Definition
        │
        ▼
Function Declaration
        │
        ▼
Gemini

Gemini receives information such as:

Tool Name:
get_latest_news

Description:
Fetch the latest news for a company.

Parameters:
company: string

5. Gemini Automatically Selects a Tool

Suppose the user asks:

Fetch the latest news for HDFC Bank.

Gemini determines that the get_latest_news tool is appropriate.

Instead of generating a normal answer, Gemini produces a tool call similar to:

get_latest_news(
    company="HDFC Bank"
)

The important concept is:

The LLM decides which tool to use, while the MCP server decides how the tool is actually executed.


🛠️ Tool Execution

The MCP client receives Gemini's tool-call request.

It then invokes the corresponding MCP tool.

Gemini
   │
   │ get_latest_news("HDFC Bank")
   ▼
MCP Client
   │
   │ call_tool()
   ▼
MCP Server
   │
   │ Execute Python Function
   ▼
External API / Logic

The MCP server executes the actual function.


📤 Returning the Tool Result

After execution, the MCP server returns the result to the MCP client.

For example:

[
    {
        "title": "HDFC Bank reports...",
        "url": "...",
        "summary": "..."
    }
]

The client then sends this result back to Gemini.


🤖 Final LLM Response

Gemini receives the tool result and generates the final response.

For example:

Here are the latest HDFC Bank news updates:

1. HDFC Bank reported...
2. The bank announced...
3. Analysts expect...

Therefore, the complete flow becomes:

User Query
    ↓
Gemini
    ↓
Tool Selection
    ↓
MCP Client
    ↓
MCP Server
    ↓
Tool Execution
    ↓
Tool Result
    ↓
MCP Client
    ↓
Gemini
    ↓
Final Answer

📁 Project Structure

A recommended project structure is:

mcp-gemini-server/
│
├── src/
│   └── mcp_servers/
│       ├── __init__.py
│       └── ...
│
├── client.py
├── server.py
│
├── .env.example
├── .gitignore
├── README.md
├── pyproject.toml
└── uv.lock

server.py

Contains the MCP server implementation and exposed tools.

Example:

@mcp.tool()
def get_latest_news(company: str):
    ...

client.py

Responsible for:

  • Connecting to the MCP server

  • Discovering tools

  • Converting MCP tools into Gemini-compatible tool declarations

  • Sending user queries to Gemini

  • Processing Gemini tool calls

  • Invoking MCP tools

  • Sending tool results back to Gemini

  • Generating the final response

pyproject.toml

Defines project metadata and dependencies.

uv.lock

Contains the resolved dependency versions used by the project.

.env

Contains secrets such as API keys.

This file should never be committed to GitHub.

.env.example

Contains the required environment variables without exposing actual secrets.


🐍 Technology Stack

Technology

Purpose

Python 3.12

Application development

MCP

Standardized tool communication

Gemini API

LLM and tool selection

uv

Python project and dependency management

asyncio

Asynchronous MCP communication

dotenv

Environment variable management

Git/GitHub

Version control


📦 Why uv?

This project uses uv instead of managing the environment manually with pip and venv.

uv provides:

  • Fast dependency installation

  • Virtual environment management

  • Dependency resolution

  • Lock file generation

  • Reproducible environments

  • Convenient project execution

The important files are:

pyproject.toml
uv.lock

The local virtual environment:

.venv/

should not be committed.


🚀 Installation

Prerequisites

Make sure the following are installed:

  • Python 3.12+

  • uv

  • Git

  • Google Gemini API key


1. Clone the Repository

git clone https://github.com/<YOUR_USERNAME>/<YOUR_REPOSITORY>.git

Move into the project:

cd <YOUR_REPOSITORY>

2. Install Dependencies

Because this project uses uv, run:

uv sync

This will create the virtual environment and install the dependencies specified in:

pyproject.toml

using the versions resolved in:

uv.lock

🔐 Environment Variables

Create a .env file in the project root:

GOOGLE_API_KEY=your_gemini_api_key

Never commit the real .env file.

The repository should contain:

.env.example

with:

GOOGLE_API_KEY=

▶️ Running the Project

Start the MCP Server

Run:

uv run python server.py

The MCP server will start and wait for client connections.


Run the MCP Client

In another terminal:

uv run python client.py

The client will:

  1. Connect to the MCP server.

  2. Discover available tools.

  3. Display the available tools.

  4. Accept a user query.

  5. Send the query and tool definitions to Gemini.

  6. Allow Gemini to select a tool.

  7. Execute the selected MCP tool.

  8. Return the tool result to Gemini.

  9. Generate the final response.


🧠 Tool Calling Flow

Consider this example:

User:

Fetch the latest news for HDFC Bank.

Gemini analyzes the available tools.

If it finds:

get_latest_news(company: str)

it can generate:

Tool Call:

get_latest_news
company = "HDFC Bank"

The MCP client receives this request.

It then executes:

MCP Client
    ↓
call_tool("get_latest_news", ...)

The MCP server executes:

get_latest_news("HDFC Bank")

The result travels back:

MCP Server
    ↓
MCP Client
    ↓
Gemini

Gemini then produces the final response.


🔁 Multiple Tool Calls

The architecture can also support multiple tool calls.

For example, suppose the user asks:

Get the current stock price of HDFC Bank and
fetch the latest news about it.

Gemini may determine that two tools are required:

get_stock_price("HDFC Bank")
get_latest_news("HDFC Bank")

The client can execute the required MCP tools and provide their results back to Gemini.

Conceptually:

                    Gemini
                       │
              ┌────────┴────────┐
              │                 │
              ▼                 ▼
       get_stock_price    get_latest_news
              │                 │
              ▼                 ▼
         MCP Server         MCP Server
              │                 │
              └────────┬────────┘
                       ▼
                  Tool Results
                       │
                       ▼
                    Gemini
                       │
                       ▼
                 Final Answer

🎯 Key MCP Concepts Demonstrated

This project is designed to demonstrate the core MCP concepts.

MCP Server

The server exposes capabilities to AI applications.

MCP Server
    ↓
Tools

MCP Client

The client connects an AI application to the MCP server.

LLM Application
      ↓
MCP Client
      ↓
MCP Server

Tools

Tools are executable functions exposed by the MCP server.

Example:

@mcp.tool()
def calculate_sum(a: int, b: int) -> int:
    return a + b

Tool Discovery

The client can discover the tools exposed by the MCP server.

This makes the architecture more dynamic than hard-coding every available function inside the client.


Tool Selection

The LLM decides which tool is appropriate based on:

  • User request

  • Tool name

  • Tool description

  • Tool parameters


Tool Execution

The actual execution happens outside the LLM.

This is an important architectural principle.

LLM
 ↓
Decision
 ↓
Tool Call
 ↓
Application
 ↓
Tool Execution

The LLM does not directly execute Python code.


🔒 Security Considerations

Never expose API keys in source code.

Bad:

api_key = "AIza..."

Good:

import os

api_key = os.getenv("GOOGLE_API_KEY")

Use:

.env

for local secrets and ensure it is included in .gitignore.


🧩 MCP vs Traditional Function Calling

Traditional function calling often looks like:

Application
    │
    ├── Tool A
    ├── Tool B
    └── Tool C

The application itself owns the tools.

With MCP:

                  MCP Client
                      │
             MCP Protocol
                      │
        ┌─────────────┼─────────────┐
        ▼             ▼             ▼
   MCP Server A  MCP Server B  MCP Server C
        │             │             │
      Tools         Tools         Tools

This provides a more standardized architecture for connecting AI applications with external capabilities.


🧠 MCP and RAG

MCP can also be used alongside Retrieval-Augmented Generation (RAG).

For example, an MCP server could expose:

search_documents()
retrieve_chunks()
query_vector_database()
get_document_metadata()

The architecture could become:

                     Gemini
                        │
                        ▼
                 MCP Client
                        │
                        ▼
                 MCP Server
                        │
             ┌──────────┼──────────┐
             ▼          ▼          ▼
          Pinecone    MongoDB     APIs
             │
             ▼
        Relevant Chunks
             │
             ▼
           Gemini
             │
             ▼
        Final Response

This means MCP can act as a standardized interface between an LLM application and components of a RAG system.


🔗 MCP with LangChain / LangGraph

MCP is not a replacement for frameworks such as LangChain or LangGraph.

They solve different problems.

MCP

Focuses on:

Standardized communication
between AI applications and tools/data

LangChain

Provides abstractions for:

LLMs
Prompts
Retrievers
Tools
Agents
Chains
Vector Stores

LangGraph

Focuses on:

Stateful
multi-step
agent workflows

They can therefore be used together.

A possible architecture is:

                LangGraph
                    │
                    ▼
               LLM / Agent
                    │
                    ▼
                MCP Client
                    │
                    ▼
                MCP Server
                    │
          ┌─────────┼─────────┐
          ▼         ▼         ▼
       Vector DB   APIs    Databases

🧪 Example Use Cases

The MCP architecture demonstrated in this project can be extended to many real-world applications.

Financial AI Assistant

Expose tools such as:

get_stock_price()
get_financial_statements()
get_latest_news()
calculate_financial_ratio()

RAG Application

Expose:

search_documents()
retrieve_document()
search_vector_database()

Enterprise AI Assistant

Expose:

search_employee_data()
query_database()
search_internal_documents()
create_ticket()

Developer Assistant

Expose:

search_github()
get_issue()
create_issue()
search_repository()

📊 Project Learning Objectives

This project was created to understand:

  • What MCP is

  • Why MCP is required

  • MCP client/server architecture

  • MCP tool discovery

  • MCP tool definitions

  • Function declarations

  • LLM tool selection

  • Tool calling

  • Tool execution

  • Returning tool results to an LLM

  • Multiple tool calls

  • Gemini integration

  • Async MCP communication

  • uv project management

  • MCP integration patterns for RAG

  • MCP integration patterns for agentic applications


💡 Important Architectural Insight

The most important concept demonstrated by this project is the separation of responsibilities.

Gemini

Responsible for:

Understanding the user
        ↓
Deciding what capability is required
        ↓
Selecting the appropriate tool

MCP Client

Responsible for:

Connecting to MCP servers
        ↓
Discovering tools
        ↓
Sending tool definitions to Gemini
        ↓
Executing requested MCP tools
        ↓
Returning results to Gemini

MCP Server

Responsible for:

Exposing tools
        ↓
Executing tools
        ↓
Returning results

Therefore:

The LLM decides what should happen; the MCP server provides the capability to make it happen.


🛠️ Future Improvements

Possible extensions for this project include:

  • Add multiple MCP servers

  • Add database tools

  • Add web-search tools

  • Add filesystem tools

  • Add authentication

  • Add logging

  • Add error handling

  • Add retry mechanisms

  • Add structured tool responses

  • Add Pydantic validation

  • Add streaming responses

  • Add parallel tool execution

  • Add LangChain integration

  • Add LangGraph agent orchestration

  • Integrate MCP tools into a RAG pipeline

  • Add automated tests

  • Containerize the MCP server using Docker


📚 Project Architecture Summary

The complete architecture can be summarized as:

┌──────────────────────────────┐
│            User              │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│          Gemini LLM          │
│                              │
│  Understands user request    │
│  Selects appropriate tool    │
└──────────────┬───────────────┘
               │
               │ Tool Call
               ▼
┌──────────────────────────────┐
│         MCP Client           │
│                              │
│  • Tool Discovery            │
│  • Function Declarations     │
│  • Tool Invocation           │
│  • Result Handling           │
└──────────────┬───────────────┘
               │
               │ MCP Protocol
               ▼
┌──────────────────────────────┐
│         MCP Server           │
│                              │
│       Exposed Tools          │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│       External Systems       │
│                              │
│ APIs / Databases / Files /   │
│ RAG / Business Logic         │
└──────────────┬───────────────┘
               │
               │ Tool Result
               ▼
┌──────────────────────────────┐
│          Gemini LLM          │
│                              │
│     Generates final answer   │
└──────────────┬───────────────┘
               │
               ▼
┌──────────────────────────────┐
│            User              │
└──────────────────────────────┘

⭐ Conclusion

This project provides a practical implementation of the Model Context Protocol (MCP) and demonstrates how an LLM can interact with external tools through a standardized client-server architecture.

Rather than directly coupling Gemini with every application-specific function, MCP provides a reusable interface through which AI applications can discover and invoke capabilities.

The project demonstrates the complete lifecycle:

Discover Tools
      ↓
Provide Tools to LLM
      ↓
LLM Selects Tool
      ↓
MCP Client Invokes Tool
      ↓
MCP Server Executes Tool
      ↓
Result Returned
      ↓
LLM Generates Final Answer

This architecture can serve as a foundation for building more advanced Agentic AI, RAG, enterprise AI assistants, and tool-using LLM applications.

F
license - not found
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    C
    quality
    D
    maintenance
    A Model Context Protocol implementation that enables large language models to call external tools (like weather forecasts and GitHub information) through a structured protocol, with visualization of the model's reasoning process.
    2
    225
    2
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    Wraps Google's Gemini CLI to expose search, chat, and file analysis tools via the Model Context Protocol for AI assistants.
    107
    101
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Enables interaction with HexagonML ModelManager tools through the Model Context Protocol, allowing management of models via natural language.

View all related MCP servers

Related MCP Connectors

  • A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…

  • A Model Context Protocol server for Wix AI tools

  • Gateway between LLM agents and world data through eight tools and a bundled endpoint catalog.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/AI2Enginex/Python-MCP-Web-Search-Tool'

If you have feedback or need assistance with the MCP directory API, please join our Discord server