In the rapidly evolving landscape of AI development, the integration between language models and real-world data has become a fundamental pillar of modern applications. Today, we'll dive deep into a sophisticated Weather MCP Server (Model Context Protocol) that transforms Claude Desktop from a static AI into a dynamic weather station, leveraging Clean Architecture principles, Redis Cache, and SOLID principles. This production-ready solution demonstrates how to create AI-powered applications that are scalable and maintainable, building a bridge between conversational AI and real-time data services.
The Model Context Protocol (MCP) represents a paradigm shift in how we expand AI capabilities, and few implementations demonstrate this potential as elegantly as the Weather MCP Server. Built with TypeScript, this project exemplifies modern software architecture principles while solving a practical problem: enabling Claude Desktop to access real-time weather information from anywhere in the world.
What makes this project special?
If you're curious about the depth and architectural decisions that shaped this project, let's explore what makes this Weather MCP Server an exceptional example of production-ready AI integration.
glaucia86
/
weather-mcp-server
A robust Weather MCP Server in TypeScript
๐ค๏ธ Weather MCP Server - Clean Architecture Edition [Docker + Redis]
Servidor MCP de Clima com Clean Architecture para Claude Desktop - Production Ready
Claude AI transformado em estaรงรฃo meteorolรณgica profissional usando princรญpios SOLID
๐ VERSรO ATUAL: 2.0.0 - Clean Architecture Completa โ Refatoraรงรฃo concluรญda โข โ Zero legacy code โข โ Production ready
๐ Status do Projeto
๐ CI/CD Pipeline
Este projeto implementa um pipeline CI/CD completo com GitHub Actions:
๐ Lint & Type Check โ ๐งช Tests โ ๐๏ธ Build โ ๐ Security โ ๐ณ Docker โ ๐ Deploy
Pipeline Stages:
- ๐ Lint & Type Check: ESLint + TypeScript compilation check
- ๐งช Tests: Unit tests com mocks + Integration tests com PostgreSQL/Redis
- ๐๏ธ Build: TypeScriptโฆ
The vision behind Clean Architecture
Clean Architecture is a concept aimed at creating software systems that are independent of frameworks, databases, and other external concerns. The goal is to allow business logic to remain intact even when underlying technologies change. In the context of the Weather MCP Server, this means the application can evolve and adapt to new needs without compromising its fundamental structure.
Glaucia Lemos, Software AI Engineer and ex-Microsoft, brought an approach that demonstrates how to create AI integrations that are:
Maintainable: clear separation of responsibilities between architectural layers, facilitating system maintenance and evolution.
Scalable: designed to handle growing demands and new functionalities.
Testable: comprehensive unit and integration testing strategies
Extensible: easy addition of new weather providers or data sources.
You can explore the complete source code and project documentation in the GitHub repository to better understand how these principles were applied in practice.
Unveiling the MCP Architecture
The Model Context Protocol (MCP) represents a revolutionary approach to expanding AI capabilities. Unlike traditional APIs that require constant prompting, MCP enables persistent and contextual interactions between AI models and external systems. This Weather MCP Server demonstrates how MCP can transform Claude Desktop from a conversational AI into a meteorological specialist.
Technical Anatomy of the MCP Server
Let's understand the code: WeatherMCPServer.ts
and how it contributes to the total functionality:
Fundamental imports and their responsibilities:
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ListResourcesRequestSchema,
ListPromptsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
The Server
is the main class that manages all MCP communications. It acts as the protocol's core, coordinating requests and responses between Claude Desktop and our weather server.
The StdioServerTransport
implements the communication protocol via STDIO (Standard Input/Output). This is the bridge that allows Claude Desktop to communicate with our server through standard input and output, eliminating the need for complex network protocols.
-
Request Schemas: each schema defines a specific type of interaction:
-
CallToolRequestSchema
: validates requests to execute specific tools. In this case, it ensures that calls to weather tools are properly formatted and contain all necessary information. -
ListToolsRequestSchema
: manages listing of available tools -
ListResourcesRequestSchema
: defines available static resources. -
ListPromptsRequestSchema
: configures predefined prompts for interactions.
-
Integration with Clean Architecture
import { DIContainer } from '../../infrastructure/di/DIContainer.js';
import { WeatherController } from '../controllers/WeatherController.js';
import { HistoryController } from '../controllers/HistoryController.js';
import { ILogger } from '../../infrastructure/logger/Logger.js';
These imports demonstrate the separation of concerns in Clean Architecture, where:
-
DIContainer
: Manages dependency injection, ensuring low coupling -
WeatherController
: Implements presentation logic for weather-related interactions -
HistoryController
: Manages interaction and data history -
ILogger
: Logging interface that allows different implementations
Server Construction and Initialization
constructor() {
this.server = new Server(
{
name: "weather-mcp",
version: "1.0.0",
},
{
capabilities: {
tools: {}, // Executable tools
resources: {}, // Static resources
prompts: {}, // Predefined prompts
},
}
);
MCP Capabilities Explained:
-
Tools
: Executable functions that Claude can call (e.g., fetch current weather) -
Resources
: Static or dynamic data that Claude can access (e.g., weather history) -
Prompts
: Predefined templates for structured interactions
Tool Registration System
private registerTools() {
// Register weather tools
const weatherTools = this.weatherController.getToolDefinitions();
weatherTools.forEach((tool) => {
this.tools.set(tool.name, tool);
});
// Register history tools
const historyTools = this.historyController.getToolDefinitions();
historyTools.forEach(tool => {
this.tools.set(tool.name, tool);
});
this.logger.debug(`[MCP] Registered ${this.tools.size} tools`);
}
This method demonstrates the dynamic registration pattern, where:
- Controllers define their own tools: Each controller is responsible for declaring its capabilities
- Centralized registration: All tools are stored in a Map for efficient access
- Observability: Detailed logging for debugging and monitoring
Specialized MCP Protocol Handlers
- 1. Tool Listing Handler:
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
const tools = Array.from(this.tools.values()).map(tool => ({
name: tool.name,
description: tool.description,
inputSchema: tool.inputSchema,
}));
return { tools };
});
This handler exposes tool metadata to Claude Desktop, allowing it to understand what weather operations are available.
- 2. Resource Handler:
this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
return {
resources: [
{
uri: "weather://current",
mimeType: "application/json",
name: "Current Weather",
description: "Get current weather for any city"
}
]
};
});
Defines accessible resources via custom URI, creating a "virtual file system" that Claude can explore.
- 3. Tool Execution Handler:
this.server.setRequestHandler(CallToolRequestSchema, async (request: any) => {
const { name, arguments: args } = request.params;
const tool = this.tools.get(name);
if(!tool) {
throw new Error(`Tool ${name} not found`);
}
try {
const result = await tool.handler(args);
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2)
}
]
};
} catch (error) {
this.logger.error(`[MCP] Error calling tool ${name}:`, error);
throw error;
}
});
Advanced Technical Features:
- Tool Validation: Verifies existence before execution
- Robust Error Handling: Captures and propagates errors in a structured way
- JSON Serialization: Standardizes responses to ensure compatibility
- Complete Observability: Detailed logs for debugging
Lifecycle and State Management
async start() {
try {
// Initialize infrastructure services
await this.container.initialize();
// Connect server to stdio
const transport = new StdioServerTransport();
await this.server.connect(transport);
this.logger.info('Weather MCP Server started successfully');
} catch (error) {
this.logger.error('Failed to start MCP server:', error);
throw error;
}
}
Initialization Sequence:
- Infrastructure Initialization: Database, cache, and external API connections
- Transport Configuration: Establishes STDIO communication channel
- Server Connection: Links server to transport
- Status Logging: Confirms successful initialization
This MCP architecture represents a significant evolution in how we build AI integrations, providing a solid foundation for applications that require dynamic access to external data while maintaining enterprise-level performance and reliability.
Architectural Excellence and Implementation
The project's architecture follows Clean Architecture principles, creating a robust foundation that separates business logic from external concerns:
๐๏ธ Domain Layer (Business Rules)
โโโ entities/ # Weather data models
โโโ repositories/ # Contract definitions
๐ง Application Layer (Use Cases)
โโโ usecases/ # Business operations
โโโ GetCurrentWeatherUseCase.ts
โโโ GetWeatherForecastUseCase.ts
โโโ GetWeatherHistoryUseCase.ts
โโโ GetCacheStatisticsUseCase.ts
๐๏ธ Infrastructure Layer (External Concerns)
โโโ repositories/ # Data access implementations
โ โโโ OpenWeatherMapApiRepository.ts
โ โโโ PostgreSQLWeatherRepository.ts
โ โโโ RedisCacheRepository.ts
โโโ logger/ # Logging infrastructure
โโโ di/ # Dependency injection
๐ฎ Presentation Layer (User Interface)
โโโ controllers/ # Request handling
โโโ servers/ # MCP server implementation
Technology Stack Integration:
- TypeScript: Type safety and modern JavaScript features
- Redis: Ultra-fast cache with 95% hit rate
- PostgreSQL: Reliable data persistence for weather history
- Docker: Containerized deployment and development
- OpenWeatherMap API: Comprehensive weather data source
Performance Revolution Through Intelligent Caching
One of the project's most impressive achievements is its caching strategy, which delivers remarkable performance improvements:
Metric | With Redis Cache | Without Cache | Improvement
--------------------- | ---------------- | ------------- | -----------
Response Time | 23ms | 315ms | 13.6x faster
Cache Hit Rate | 95% | 0% | Massive savings
API Calls | 5 (per 50 requests) | 50 | 90% reduction
Intelligent Cache Features:
- Differentiated TTL: 10 minutes for current weather, 1 hour for forecasts
- Smart Key Generation: Normalized city names prevent cache duplicates
- Graceful Fallback: System continues working even if Redis fails
- Automatic Statistics: Real-time monitoring of cache performance
Simplified Claude Desktop Integration
The project provides clear, step-by-step instructions for Claude Desktop integration:
Configuration Example:
{
"mcpServers": {
"weather-mcp": {
"command": "node",
"args": ["/path/to/weather-mcp-server/dist/mcp-entry.js"],
"env": {
"WEATHER_API_KEY": "your_openweathermap_key",
"DATABASE_URL": "postgresql://mcp_user:mcp_pass@localhost:5432/weather_mcp",
"REDIS_URL": "redis://localhost:6379"
}
}
}
}
Available MCP Tools:
- get_current_weather: Real-time weather for any city
- get_weather_forecast: Detailed 5-day forecasts
- get_weather_history: Query historical weather data
- get_cache_statistics: Monitor system performance
Contributing to the Future of AI Integration
This project represents more than just a weather serviceโit's a blueprint for building production-ready MCP servers that expand AI capabilities in meaningful ways.
Why You Should Explore This Project:
- Learn Clean Architecture: See SOLID principles applied in a real-world TypeScript project
- Master Caching Strategies: Understand how to implement high-performance Redis caching
- Explore MCP Development: Gain hands-on experience with the Model Context Protocol
- Study CI/CD Best Practices: Learn from a complete automated deployment pipeline
- Contribute to Innovation: Help improve and expand this fundamental MCP implementation
Getting Started and Contributing
The project welcomes contributions from developers of all skill levels. If you're interested in:
- Adding new weather data providers
- Implementing additional caching strategies
- Improving the CI/CD pipeline
- Enhancing documentation
- Creating new MCP tools
Your contributions can help shape the future of AI-data integration.
Quick Start:
# Clone the repository
git clone https://github.com/glaucia86/weather-mcp-server.git
# Install dependencies
npm install
# Start development environment
npm run docker:up (docker-compose up -d)
npm run build
npm run start
Additional Resources
To deepen your understanding of the technologies and patterns used in this project:
- Model Context Protocol Documentation
- Clean Architecture in TypeScript Guide
- Redis Caching Best Practices
- SOLID Principles Explained
- Docker Compose: Development environment for large-scale applications
Join the MCP Revolution! ๐
The Weather MCP Server project represents a significant step forward in AI-data integration. By combining Clean Architecture, intelligent caching, and production-ready practices, it demonstrates how to build AI extensions that are both powerful and maintainable.
โญ Star the Repository: github.com/glaucia86/weather-mcp-server
๐ด Fork and Contribute: Help improve this fundamental MCP implementation
๐ Learn and Apply: Use this project as a blueprint for your own MCP servers
Whether you're building your first MCP server or looking to enhance your existing AI integrations, this project offers valuable insights and practical patterns you can apply immediately. The future of AI development lies in these seamless integrations between language models and real-world dataโand this Weather MCP Server shows exactly how to build them right.
Ready to transform Claude Desktop into your personal weather station? Start exploring the code today! ๐ค๏ธ๐ค
Top comments (0)