Skip to main content
Glama
ngangu63
by ngangu63
README.md
# LangChain MCP Weather Application

A complete example demonstrating how to build and consume a **Model Context Protocol (MCP)** server using:

* Python
* FastMCP
* LangChain
* OpenAI
* Open-Meteo APIs

The project exposes weather information through an MCP server and allows a LangChain agent to discover and invoke weather tools dynamically.

---

# Features

The weather tool returns:

* Latitude
* Longitude
* Timezone
* Humidity
* Wind Speed
* Weather Conditions
* Sunrise Time
* Sunset Time
* 7-Day Forecast

The application demonstrates:

* Creating an MCP server with FastMCP
* Registering MCP tools
* Connecting to MCP servers with LangChain
* Discovering tools dynamically
* Building AI agents that invoke MCP tools
* Integrating external REST APIs

---

# Architecture

```text
+-------------------+
|   LangChain Agent |
+---------+---------+
          |
          v
+-------------------+
| MCP Client        |
| MultiServerMCP    |
+---------+---------+
          |
          | stdio
          |
          v
+-------------------+
| MCP Server        |
| FastMCP           |
+---------+---------+
          |
          v
+-------------------+
| Weather Service   |
+---------+---------+
          |
          v
+-------------------+
| Open-Meteo APIs   |
+-------------------+
```

---

# Project Structure

```text
project/
│
├── server.py
├── client.py
├── agent.py
├── weather_service.py
├── requirements.txt
├── .env
└── README.md
```

---

# Components

## 1. weather_service.py

Contains the business logic responsible for:

### Geocoding

Converts a city name into:

* Latitude
* Longitude
* Timezone

Uses:

```text
https://geocoding-api.open-meteo.com
```

### Weather Retrieval

Fetches:

* Current humidity
* Wind speed
* Weather conditions
* Sunrise
* Sunset
* 7-day forecast

Uses:

```text
https://api.open-meteo.com
```

### Example Output

```json
{
  "city": "Matadi",
  "latitude": -5.799,
  "longitude": 13.440,
  "timezone": "Africa/Kinshasa",
  "humidity": 82,
  "wind_speed": 12.4,
  "weather_conditions": 1,
  "sunrise": "2026-06-01T06:03",
  "sunset": "2026-06-01T17:58",
  "forecast": [
    {
      "date": "2026-06-01",
      "min_temp": 20.2,
      "max_temp": 29.1
    }
  ]
}
```

---

## 2. server.py

Creates the MCP server.

### MCP Server Initialization

```python
mcp = FastMCP("WeatherServer")
```

### Tool Registration

```python
@mcp.tool()
def weather(city: str):
    return get_weather(city)
```

### Start Server

```python
mcp.run()
```

The server exposes the weather tool to any MCP-compatible client.

---

## 3. client.py

Demonstrates connecting to the MCP server and discovering tools.

### Create MCP Client

```python
client = MultiServerMCPClient(
    {
        "weather_server": {
            "transport": "stdio",
            "command": "python",
            "args": ["server.py"]
        }
    }
)
```

### Discover Tools

```python
tools = await client.get_tools()
```

### Example Output

```text
TOOLS
[StructuredTool(name='weather', ...)]
```

---

## 4. agent.py

Builds an AI agent capable of invoking MCP tools.

### Load Environment Variables

```python
load_dotenv()
```

### Create OpenAI Model

```python
llm = ChatOpenAI(
    model="gpt-5-nano"
)
```

### Retrieve MCP Tools

```python
tools = await client.get_tools()
```

### Create Agent

```python
agent = create_agent(
    model=llm,
    tools=tools,
    system_prompt="You are a weather assistant."
)
```

### Invoke Agent

```python
result = await agent.ainvoke(
    {
        "messages": [
            {
                "role": "user",
                "content": "What is the weather in Matadi?"
            }
        ]
    }
)
```

---

# Installation

## Clone Repository

```bash
git clone https://github.com/your-org/weather-mcp.git

cd weather-mcp
```

---

## Create Virtual Environment

### Using venv

```bash
python -m venv .venv
```

Activate:

#### Linux / macOS

```bash
source .venv/bin/activate
```

#### Windows

```bash
.venv\Scripts\activate
```

---

## Install Dependencies

```bash
pip install -r requirements.txt
```

---

# requirements.txt

```text
mcp
langchain
langchain-openai
langchain-mcp-adapters
python-dotenv
requests
openai
```

---

# Environment Variables

Create a `.env` file:

```env
OPENAI_API_KEY=your_openai_api_key
```

---

# Running the Application

## Option 1: Run MCP Server

```bash
python server.py
```

The server starts and waits for MCP client requests.

---

## Option 2: Test MCP Client

```bash
python client.py
```

Example:

```text
TOOLS
[StructuredTool(name='weather', ...)]
```

---

## Option 3: Run LangChain Agent

```bash
python agent.py
```

Example:

```json
{
  "city": "Matadi",
  "latitude": -5.799,
  "longitude": 13.440,
  "timezone": "Africa/Kinshasa",
  "humidity": 82,
  "wind_speed": 12.4,
  "weather_conditions": 1,
  "sunrise": "2026-06-01T06:03",
  "sunset": "2026-06-01T17:58",
  "forecast": [
    {
      "date": "2026-06-01",
      "min_temp": 20.2,
      "max_temp": 29.1
    }
  ]
}
```

---

# MCP Workflow

```text
User Question
      |
      v
LangChain Agent
      |
      v
MCP Tool Discovery
      |
      v
Weather Tool
      |
      v
Open-Meteo APIs
      |
      v
Weather Data
      |
      v
Agent Response
```

---

# Example Queries

```text
What is the weather in Paris?
```

```text
What is the humidity in New York?
```

```text
Give me the 7-day forecast for Tokyo.
```

```text
When is sunrise in London?
```

```text
What is the wind speed in Matadi?
```

---

# Future Enhancements

* Multiple MCP servers
* Weather alerts
* Historical weather data
* Air quality information
* LangGraph integration
* Redis caching
* Azure deployment
* Streaming responses
* RAG integration
* Multi-agent orchestration

---

# Technologies Used

* Python
* FastMCP
* LangChain
* OpenAI
* Open-Meteo API
* AsyncIO
* MCP (Model Context Protocol)

---

# Learning Objectives

This project teaches:

1. MCP Server Development
2. MCP Tool Registration
3. MCP Client Integration
4. LangChain Tool Discovery
5. AI Agent Tool Calling
6. REST API Integration
7. Async Python Programming
8. OpenAI + LangChain Integration

---

# License

MIT License

Copyright (c) 2026

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files to deal in the Software without restriction.

Maintenance

ActivityInactive
ResponsivenessNo issues