DEV Community

Glaucia Lemos
Glaucia Lemos

Posted on

Building a Production-Ready Weather MCP Server with Clean Architecture, Redis Cache, and SOLID Principles | Complete Guide

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.

GitHub logo glaucia86 / weather-mcp-server

A robust Weather MCP Server in TypeScript

GitHub release (latest by date) GitHub issues GitHub pull requests GitHub last commit GitHub repo size GitHub language count GitHub top language

๐ŸŒค๏ธ Weather MCP Server - Clean Architecture Edition [Docker + Redis]

TypeScript Node.js PostgreSQL Redis Docker Claude AI OpenWeatherMap MCP Clean Architecture SOLID DI License: MIT PRs Welcome

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

Aspecto Status Descriรงรฃo
Build Build Status TypeScript compilation + Docker build
Tests Tests Unit tests + Integration tests
Security Security Trivy vulnerability scan + npm audit
Docker Docker Multi-stage build otimizado
Deploy Deployment CI/CD pipeline automatizado

๐Ÿ”„ CI/CD Pipeline

Este projeto implementa um pipeline CI/CD completo com GitHub Actions:

๐Ÿ” Lint & Type Check โ†’ ๐Ÿงช Tests โ†’ ๐Ÿ—๏ธ Build โ†’ ๐Ÿ”’ Security โ†’ ๐Ÿณ Docker โ†’ ๐Ÿš€ Deploy
Enter fullscreen mode Exit fullscreen mode

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";
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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
      },
    }
  );
Enter fullscreen mode Exit fullscreen mode

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`);
}
Enter fullscreen mode Exit fullscreen mode

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 };
});
Enter fullscreen mode Exit fullscreen mode

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"
      }
    ]
  };
});
Enter fullscreen mode Exit fullscreen mode

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;
  }
});
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

Initialization Sequence:

  1. Infrastructure Initialization: Database, cache, and external API connections
  2. Transport Configuration: Establishes STDIO communication channel
  3. Server Connection: Links server to transport
  4. 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Additional Resources

To deepen your understanding of the technologies and patterns used in this project:

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)