Use this file to discover all available pages before exploring further.
The Model Context Protocol (MCP) is an open standard that streamlines the integration of AI assistants with external data sources, tools, and systems. MCP provides a standardized interface for AI models to connect with diverse external systems and services.
Create a custom MCP server to expose your tools to Gemini:
Weather Server
Database Server
API Integration
Here’s a complete weather server example:
server/weather_server.py
import jsonimport httpxfrom mcp.server.fastmcp import FastMCPfrom geopy.geocoders import Nominatim# Initialize FastMCP servermcp = FastMCP("weather")# ConfigurationBASE_URL = "https://api.weather.gov"USER_AGENT = "weather-agent"http_client = httpx.AsyncClient( base_url=BASE_URL, headers={"User-Agent": USER_AGENT, "Accept": "application/geo+json"}, timeout=20.0)geolocator = Nominatim(user_agent=USER_AGENT)# Helper functionasync def get_weather_response(endpoint: str): try: response = await http_client.get(endpoint) response.raise_for_status() return response.json() except Exception: return None# Tool: Get weather alerts@mcp.tool()async def get_alerts(state: str) -> str: """ Get active weather alerts for a specific US state. Args: state: Two-letter US state code (e.g., CA, NY, TX) """ if not isinstance(state, str) or len(state) != 2: return "Invalid state code. Provide two-letter code (e.g., CA)." state_code = state.upper() endpoint = f"/alerts/active/area/{state_code}" data = await get_weather_response(endpoint) if not data or not data.get("features"): return f"No active weather alerts found for {state_code}." alerts = [] for feature in data["features"]: props = feature.get("properties", {}) alert = f""" Event: {props.get('event', 'N/A')} Area: {props.get('areaDesc', 'N/A')} Severity: {props.get('severity', 'N/A')} Headline: {props.get('headline', 'N/A')} """ alerts.append(alert.strip()) return "\n---\n".join(alerts)# Tool: Get forecast by coordinates@mcp.tool()async def get_forecast(latitude: float, longitude: float) -> str: """ Get weather forecast for a location. Args: latitude: Latitude (-90 to 90) longitude: Longitude (-180 to 180) """ if not (-90 <= latitude <= 90 and -180 <= longitude <= 180): return "Invalid coordinates." # Get NWS gridpoint point_endpoint = f"/points/{latitude:.4f},{longitude:.4f}" points_data = await get_weather_response(point_endpoint) if not points_data: return "Unable to retrieve gridpoint information." forecast_url = points_data["properties"].get("forecast") if not forecast_url: return "Could not find forecast endpoint." # Get forecast response = await http_client.get(forecast_url) forecast_data = response.json() periods = forecast_data["properties"].get("periods", []) if not periods: return "No forecast periods found." forecasts = [] for period in periods[:5]: # First 5 periods forecast = f""" {period.get('name', 'N/A')} Temperature: {period.get('temperature', 'N/A')}°{period.get('temperatureUnit', 'F')} Wind: {period.get('windSpeed', 'N/A')} {period.get('windDirection', 'N/A')} {period.get('detailedForecast', 'N/A')} """ forecasts.append(forecast.strip()) return "\n---\n".join(forecasts)# Tool: Get forecast by city name@mcp.tool()async def get_forecast_by_city(city: str, state: str) -> str: """ Get weather forecast for a US city. Args: city: City name (e.g., "Los Angeles") state: Two-letter state code (e.g., CA) """ if not city or not isinstance(city, str): return "Invalid city name." if len(state) != 2: return "Invalid state code." # Geocode the city query = f"{city.strip()}, {state.strip().upper()}, USA" try: location = geolocator.geocode(query, timeout=10) except Exception: return f"Could not find coordinates for {city}, {state}." if not location: return f"Location not found: {city}, {state}" # Use the forecast function return await get_forecast(location.latitude, location.longitude)# Run the serverif __name__ == "__main__": mcp.run(transport="stdio")
Create an MCP server for database queries:
server/database_server.py
from mcp.server.fastmcp import FastMCPimport sqlite3mcp = FastMCP("database")# Initialize database connectionconn = sqlite3.connect('app.db')@mcp.tool()async def query_users(filter_active: bool = True) -> str: """ Query users from database. Args: filter_active: Only return active users """ cursor = conn.cursor() if filter_active: cursor.execute("SELECT * FROM users WHERE active = 1") else: cursor.execute("SELECT * FROM users") results = cursor.fetchall() return json.dumps(results)@mcp.tool()async def get_user_by_id(user_id: int) -> str: """ Get a specific user by ID. Args: user_id: The user ID to look up """ cursor = conn.cursor() cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,)) result = cursor.fetchone() if not result: return f"User {user_id} not found" return json.dumps(result)if __name__ == "__main__": mcp.run(transport="stdio")
Wrap external APIs as MCP tools:
server/api_server.py
from mcp.server.fastmcp import FastMCPimport httpxmcp = FastMCP("external-api")@mcp.tool()async def search_products(query: str, max_results: int = 10) -> str: """ Search products in the catalog. Args: query: Search query max_results: Maximum number of results """ async with httpx.AsyncClient() as client: response = await client.get( "https://api.example.com/products/search", params={"q": query, "limit": max_results} ) return response.text@mcp.tool()async def get_product_details(product_id: str) -> str: """ Get detailed information about a product. Args: product_id: The product ID """ async with httpx.AsyncClient() as client: response = await client.get( f"https://api.example.com/products/{product_id}" ) return response.textif __name__ == "__main__": mcp.run(transport="stdio")
async def main(): # Server parameters server_params = StdioServerParameters( command="python", args=["server/weather_server.py"], env=None ) # Connect to MCP server async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: # Initialize the session await session.initialize() # Run agent with user query result = await gemini_agent_with_mcp( user_query="What's the weather forecast for Los Angeles, CA?", session=session ) print(f"Final Answer: {result}")# Run the agentawait main()
import asynciofrom mcp import ClientSession, StdioServerParametersfrom mcp.client.stdio import stdio_clientfrom google import genaifrom google.genai import types# Initialize GeminiPROJECT_ID = "your-project-id"client = genai.Client(vertexai=True, project=PROJECT_ID, location="us-central1")async def run_weather_query(): # Connect to weather MCP server server_params = StdioServerParameters( command="python", args=["server/weather_server.py"] ) async with stdio_client(server_params) as (read, write): async with ClientSession(read, write) as session: await session.initialize() # List available tools tools = await session.list_tools() print(f"Available tools: {[t.name for t in tools.tools]}") # Run query result = await gemini_agent_with_mcp( "What are the weather alerts in California and what's the " "forecast for San Francisco?", session ) print(f"\nGemini's Answer:\n{result}")await run_weather_query()
Many MCP servers are available from the community:
File System
Access and manipulate local files
GitHub
Interact with GitHub repositories and issues
Google Drive
Search and read Google Drive documents
PostgreSQL
Query PostgreSQL databases
Install and use pre-built servers:
# Install using uvx (recommended)uvx install mcp-server-filesystem# Or use npm for Node.js-based serversnpm install -g @modelcontextprotocol/server-github
Connect to pre-built servers:
# Using filesystem serverserver_params = StdioServerParameters( command="uvx", args=["mcp-server-filesystem", "/path/to/allowed/directory"])# Using GitHub serverserver_params = StdioServerParameters( command="npx", args=["-y", "@modelcontextprotocol/server-github"], env={"GITHUB_TOKEN": "your-token"})