How to Build a Weather MCP Server with TypeScript

A practical, step-by-step guide to building a Weather Model Context Protocol (MCP) server using TypeScript, Node.js, and the Open-Meteo API, enabling AI assistants and agents to retrieve current weather conditions and forecasts.

By Mudasser Tufail · · 12 min read

  • MCP
  • TypeScript
  • Node.js
  • Open-Meteo
  • Weather API
  • Agentic AI

Introduction

AI assistants are becoming more capable of interacting with external systems, retrieving information, and performing tasks on behalf of users. However, an AI model does not automatically have access to external APIs, databases, or applications.

This is where the Model Context Protocol (MCP) comes in.

MCP provides a standardized way for AI applications to connect with external tools and data sources. Instead of building a separate integration for every AI application, developers can create an MCP server that exposes reusable capabilities to compatible clients.

In this tutorial, we will build a practical Weather MCP Server using TypeScript and Node.js. Our server will connect to the Open-Meteo API and expose weather information through MCP tools.

By the end of this tutorial, we will have an MCP server that allows an AI assistant to:

  • Retrieve current weather conditions for a city.
  • Get a weather forecast for the next seven days.
  • Access temperature, humidity, wind speed, and weather conditions.
  • Interact with the weather API through natural-language requests.

We will also connect the server to an MCP-compatible client and test it using MCP Inspector.

1. What Is a Weather MCP Server?

A Weather MCP Server is an application that exposes weather-related functionality through the Model Context Protocol.

It acts as a bridge between an AI application and a weather data provider.

For example, when a user asks:

What is the current weather in New York?

The AI assistant can identify that it needs weather information and call the appropriate MCP tool. The MCP server receives the request, communicates with the weather API, processes the response, and returns the result to the AI client.

The overall workflow looks like this:

User
  |
  | "What is the weather in New York?"
  v
AI Assistant
  |
  | MCP Tool Call
  v
Weather MCP Server
  |
  | HTTP Request
  v
Open-Meteo API
  |
  | Weather Data
  v
Weather MCP Server
  |
  | MCP Tool Response
  v
AI Assistant
  |
  v
User receives weather information

The MCP server does not need to contain an AI model. Its responsibility is to expose tools and provide reliable access to external weather data.

The AI application decides when and how to use those tools.

2. Understanding MCP Architecture

Before implementing the server, let's understand three important MCP concepts.

MCP Host

An MCP Host is the AI application that provides the environment in which a model interacts with MCP servers.

Examples include:

  • Claude Desktop
  • Claude Code
  • Cursor
  • VS Code
  • Custom AI applications

The host manages the connection to MCP servers and makes their available capabilities accessible to the AI model.

MCP Client

An MCP Client manages communication between the host and an MCP server.

It handles protocol-level operations such as initialization, capability discovery, and tool invocation.

MCP Server

An MCP Server exposes capabilities that an AI application can use.

MCP provides three important capability types:

CapabilityPurposeWeather Example
ToolsExecute operations or retrieve informationGet current weather
ResourcesExpose data that clients can readWeather information or location data
PromptsProvide reusable prompt templatesGenerate a weather summary

For this tutorial, we will focus on MCP Tools because they are the most direct way to let an AI assistant retrieve live weather information.

3. Technology Stack

We will use the following technologies:

TechnologyPurpose
TypeScriptMain programming language
Node.jsJavaScript runtime
Official MCP TypeScript SDKImplement MCP server capabilities
Open-Meteo APIRetrieve weather information
ZodValidate tool inputs
STDIOCommunication between the local MCP client and server
MCP InspectorTest and debug MCP tools

Why Open-Meteo?

For this tutorial, we will use Open-Meteo as our weather data provider.

Open-Meteo provides weather forecast data through HTTP APIs. Its free non-commercial service does not require an API key or registration, making it convenient for development and learning.

It provides information such as:

  • Current temperature
  • Apparent temperature
  • Relative humidity
  • Wind speed
  • Weather conditions
  • Daily minimum and maximum temperatures
  • Precipitation information

Important: Open-Meteo's free service has usage conditions, including non-commercial usage limits and attribution requirements. Review its licensing and pricing before using it in a commercial application.

Website: https://open-meteo.com/

4. Define the MCP Server Features

Before writing code, let's define the tools our Weather MCP Server will expose.

We will implement two tools.

Tool 1: get_current_weather

This tool retrieves current weather information for a given city.

Input:

{
  "city": "New York"
}

Expected response:

{
  "location": "New York",
  "country": "United States",
  "temperature": 18.5,
  "feelsLike": 17.2,
  "humidity": 55,
  "windSpeed": 12.4,
  "weatherCode": 2,
  "time": "2026-11-11T14:00"
}

The values above are illustrative. Actual values depend on the weather API response.

Tool 2: get_weather_forecast

This tool retrieves a daily weather forecast for a city.

Input:

{
  "city": "New York",
  "days": 7
}

Expected response:

{
  "location": "New York",
  "country": "United States",
  "forecast": [
    {
      "date": "2026-11-12",
      "maxTemperature": 19.5,
      "minTemperature": 11.2,
      "precipitation": 0,
      "weatherCode": 1
    }
  ]
}

The actual response will contain up to seven daily forecast entries.

These tools will allow an AI assistant to answer common weather-related questions without requiring the user to interact directly with the weather API.

5. Set Up the TypeScript Project

Let's start by creating a new Node.js project.

Make sure Node.js 20 or later is installed.

Check your Node.js version:

node --version

Create a project directory:

mkdir weather-mcp-server
cd weather-mcp-server

Initialize the project:

npm init -y

Configure the project to use ES modules:

npm pkg set type=module

Install the required dependencies:

npm install @modelcontextprotocol/server zod

Install TypeScript execution support:

npm install -D typescript tsx @types/node

We are using the official MCP TypeScript SDK v2 package, @modelcontextprotocol/server.

Create the following project structure:

weather-mcp-server/
│
├── src/
│   └── index.ts
│
├── package.json
└── tsconfig.json

Create the TypeScript configuration:

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "types": ["node"],
    "outDir": "dist"
  },
  "include": ["src/**/*.ts"]
}

Add a development script to package.json:

{
  "scripts": {
    "dev": "tsx src/index.ts"
  }
}

Our project is now ready for MCP server implementation.

6. Understand the Open-Meteo API

Before integrating the weather API, we need to understand how it retrieves weather information.

The Open-Meteo Forecast API requires geographical coordinates:

  • Latitude
  • Longitude

However, users generally provide city names rather than coordinates.

For example:

New York
London
Dubai
Tokyo

To support this, we will first use the Open-Meteo Geocoding API to convert a city name into geographical coordinates.

Step 1: Search for a city

The Geocoding API endpoint is:

https://geocoding-api.open-meteo.com/v1/search

Example request:

https://geocoding-api.open-meteo.com/v1/search?name=New%20York&count=1&language=en&format=json

The API returns location information, including latitude, longitude, country, and timezone.

Step 2: Retrieve weather information

Once we have the coordinates, we can call the Forecast API:

https://api.open-meteo.com/v1/forecast

For current weather, we will request:

current=temperature_2m,relative_humidity_2m,apparent_temperature,weather_code,wind_speed_10m

For the daily forecast, we will request:

daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_sum

We will also use:

timezone=auto

This allows the API to return times based on the location's timezone.

7. Implement the Weather MCP Server

Now let's implement our server.

Create the file:

src/index.ts

We will implement the following functionality:

  1. Initialize the MCP server.
  2. Register weather tools.
  3. Resolve city names into coordinates.
  4. Fetch current weather information.
  5. Fetch daily weather forecasts.
  6. Return results through MCP tool responses.

Step 1: Import dependencies

Add the following imports:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

We use:

  • McpServer to create our MCP server.
  • serveStdio to expose the server through the STDIO transport.
  • zod to define and validate tool input schemas.

Step 2: Define API interfaces

We will define TypeScript interfaces for the API responses.

interface GeocodingResult {
  name: string;
  latitude: number;
  longitude: number;
  country?: string;
  admin1?: string;
  timezone?: string;
}

interface GeocodingResponse {
  results?: GeocodingResult[];
}

interface CurrentWeather {
  time: string;
  temperature_2m: number;
  relative_humidity_2m: number;
  apparent_temperature: number;
  weather_code: number;
  wind_speed_10m: number;
}

interface DailyWeather {
  time: string[];
  weather_code: number[];
  temperature_2m_max: number[];
  temperature_2m_min: number[];
  precipitation_sum: number[];
}

interface ForecastResponse {
  current?: CurrentWeather;
  daily?: DailyWeather;
}

These interfaces describe the fields we need from the Geocoding and Forecast APIs.

Step 3: Create a location lookup function

We need a reusable function that converts a city name into geographical coordinates.

async function getLocation(city: string): Promise<GeocodingResult> {
  const url = new URL("https://geocoding-api.open-meteo.com/v1/search");

  url.searchParams.set("name", city);
  url.searchParams.set("count", "1");
  url.searchParams.set("language", "en");
  url.searchParams.set("format", "json");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Geocoding API failed with status ${response.status}`);
  }

  const data = (await response.json()) as GeocodingResponse;

  if (!data.results || data.results.length === 0) {
    throw new Error(`Location not found: ${city}`);
  }

  return data.results[0];
}

This function:

  1. Accepts a city name.
  2. Sends a request to the Geocoding API.
  3. Retrieves the location coordinates.
  4. Returns the first matching result.
  5. Throws an error if the location cannot be found or the API request fails.

For a production application, consider returning multiple matching locations so users can distinguish between cities with the same name.

Step 4: Create a current weather function

Now we will create a function to retrieve current weather information.

async function getCurrentWeather(city: string) {
  const location = await getLocation(city);

  const url = new URL("https://api.open-meteo.com/v1/forecast");

  url.searchParams.set("latitude", String(location.latitude));

  url.searchParams.set("longitude", String(location.longitude));

  url.searchParams.set(
    "current",
    [
      "temperature_2m",
      "relative_humidity_2m",
      "apparent_temperature",
      "weather_code",
      "wind_speed_10m",
    ].join(","),
  );

  url.searchParams.set("timezone", "auto");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Weather API failed with status ${response.status}`);
  }

  const data = (await response.json()) as ForecastResponse;

  if (!data.current) {
    throw new Error("Current weather data is unavailable");
  }

  return {
    location: location.name,
    country: location.country,
    current: data.current,
  };
}

This function performs two API calls:

First API call: Resolve the city name into coordinates.

Second API call: Use those coordinates to retrieve current weather conditions.

The returned data includes temperature, humidity, apparent temperature, wind speed, and weather code.

Step 5: Create a weather forecast function

Next, let's implement the seven-day forecast.

async function getWeatherForecast(city: string, days: number) {
  const location = await getLocation(city);

  const url = new URL("https://api.open-meteo.com/v1/forecast");

  url.searchParams.set("latitude", String(location.latitude));

  url.searchParams.set("longitude", String(location.longitude));

  url.searchParams.set(
    "daily",
    [
      "weather_code",
      "temperature_2m_max",
      "temperature_2m_min",
      "precipitation_sum",
    ].join(","),
  );

  url.searchParams.set("forecast_days", String(days));
  url.searchParams.set("timezone", "auto");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Weather API failed with status ${response.status}`);
  }

  const data = (await response.json()) as ForecastResponse;

  if (!data.daily) {
    throw new Error("Weather forecast is unavailable");
  }

  const forecast = data.daily.time.map((date, index) => ({
    date,
    weatherCode: data.daily!.weather_code[index],
    maxTemperature: data.daily!.temperature_2m_max[index],
    minTemperature: data.daily!.temperature_2m_min[index],
    precipitation: data.daily!.precipitation_sum[index],
  }));

  return {
    location: location.name,
    country: location.country,
    forecast,
  };
}

The function retrieves daily weather information and transforms the API response into a simpler structure.

We use the array index to associate each date with its corresponding temperature, weather code, and precipitation values.

Step 6: Initialize the MCP server

Now that our API integration is ready, let's create the MCP server.

function createServer() {
  const server = new McpServer({
    name: "weather-mcp-server",
    version: "1.0.0",
  });

  return server;
}

The server has a name and version that identify it to the MCP client.

Step 7: Register the current weather tool

We will register our first MCP tool using registerTool().

function registerWeatherTools(server: McpServer) {
  server.registerTool(
    "get_current_weather",
    {
      description:
        "Get the current weather conditions for a city, including temperature, humidity, feels-like temperature, and wind speed.",

      inputSchema: {
        city: z
          .string()
          .min(1)
          .describe("City name, for example New York or London"),
      },
    },
    async ({ city }) => {
      try {
        const result = await getCurrentWeather(city);

        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text:
                error instanceof Error
                  ? error.message
                  : "Unable to retrieve current weather",
            },
          ],
          isError: true,
        };
      }
    },
  );
}

Let's understand what is happening here.

Tool name

"get_current_weather";

This is the name the MCP client will discover and make available to the AI model.

Tool description

description: "Get the current weather conditions for a city...";

The description helps the model understand when this tool should be used.

Input schema

inputSchema: {
  city: z.string().min(1);
}

The input schema defines the arguments the tool accepts. The MCP SDK uses this schema to validate incoming tool calls.

Tool handler

async ({ city }) => {
  const result = await getCurrentWeather(city);
};

The handler receives the validated city name and calls our weather API integration.

Finally, it returns the result in an MCP text content block.

Step 8: Register the weather forecast tool

Now let's register our second tool.

Add the following code inside the registerWeatherTools() function:

server.registerTool(
  "get_weather_forecast",
  {
    description:
      "Get the daily weather forecast for a city for up to seven days, including minimum and maximum temperature and precipitation.",

    inputSchema: {
      city: z.string().min(1).describe("City name"),

      days: z
        .number()
        .int()
        .min(1)
        .max(7)
        .default(7)
        .describe("Number of forecast days, from 1 to 7"),
    },
  },
  async ({ city, days }) => {
    try {
      const result = await getWeatherForecast(city, days);

      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(result, null, 2),
          },
        ],
      };
    } catch (error) {
      return {
        content: [
          {
            type: "text",
            text:
              error instanceof Error
                ? error.message
                : "Unable to retrieve weather forecast",
          },
        ],
        isError: true,
      };
    }
  },
);

We have now exposed two tools:

  • get_current_weather
  • get_weather_forecast

The AI client can discover both tools and select the appropriate one based on the user's request.

8. Complete MCP Server Implementation

Let's combine the code into one file so we can run the server.

src/index.ts

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

interface GeocodingResult {
  name: string;
  latitude: number;
  longitude: number;
  country?: string;
  admin1?: string;
  timezone?: string;
}

interface GeocodingResponse {
  results?: GeocodingResult[];
}

interface CurrentWeather {
  time: string;
  temperature_2m: number;
  relative_humidity_2m: number;
  apparent_temperature: number;
  weather_code: number;
  wind_speed_10m: number;
}

interface DailyWeather {
  time: string[];
  weather_code: number[];
  temperature_2m_max: number[];
  temperature_2m_min: number[];
  precipitation_sum: number[];
}

interface ForecastResponse {
  current?: CurrentWeather;
  daily?: DailyWeather;
}

async function getLocation(city: string): Promise<GeocodingResult> {
  const url = new URL("https://geocoding-api.open-meteo.com/v1/search");

  url.searchParams.set("name", city);
  url.searchParams.set("count", "1");
  url.searchParams.set("language", "en");
  url.searchParams.set("format", "json");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Geocoding API failed: HTTP ${response.status}`);
  }

  const data = (await response.json()) as GeocodingResponse;

  if (!data.results?.length) {
    throw new Error(`Location not found: ${city}`);
  }

  return data.results[0];
}

async function getCurrentWeather(city: string) {
  const location = await getLocation(city);

  const url = new URL("https://api.open-meteo.com/v1/forecast");

  url.searchParams.set("latitude", String(location.latitude));

  url.searchParams.set("longitude", String(location.longitude));

  url.searchParams.set(
    "current",
    [
      "temperature_2m",
      "relative_humidity_2m",
      "apparent_temperature",
      "weather_code",
      "wind_speed_10m",
    ].join(","),
  );

  url.searchParams.set("timezone", "auto");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Weather API failed: HTTP ${response.status}`);
  }

  const data = (await response.json()) as ForecastResponse;

  if (!data.current) {
    throw new Error("Current weather data is unavailable");
  }

  return {
    location: location.name,
    country: location.country,
    current: data.current,
  };
}

async function getWeatherForecast(city: string, days: number) {
  const location = await getLocation(city);

  const url = new URL("https://api.open-meteo.com/v1/forecast");

  url.searchParams.set("latitude", String(location.latitude));

  url.searchParams.set("longitude", String(location.longitude));

  url.searchParams.set(
    "daily",
    [
      "weather_code",
      "temperature_2m_max",
      "temperature_2m_min",
      "precipitation_sum",
    ].join(","),
  );

  url.searchParams.set("forecast_days", String(days));
  url.searchParams.set("timezone", "auto");

  const response = await fetch(url, {
    signal: AbortSignal.timeout(10000),
  });

  if (!response.ok) {
    throw new Error(`Weather API failed: HTTP ${response.status}`);
  }

  const data = (await response.json()) as ForecastResponse;

  if (!data.daily) {
    throw new Error("Weather forecast is unavailable");
  }

  const daily = data.daily;

  const forecast = daily.time.map((date, index) => ({
    date,
    weatherCode: daily.weather_code[index],
    maxTemperature: daily.temperature_2m_max[index],
    minTemperature: daily.temperature_2m_min[index],
    precipitation: daily.precipitation_sum[index],
  }));

  return {
    location: location.name,
    country: location.country,
    forecast,
  };
}

function createServer() {
  const server = new McpServer({
    name: "weather-mcp-server",
    version: "1.0.0",
  });

  server.registerTool(
    "get_current_weather",
    {
      description: "Get current weather conditions for a city.",

      inputSchema: {
        city: z
          .string()
          .min(1)
          .describe("City name, for example New York or London"),
      },
    },
    async ({ city }) => {
      try {
        const result = await getCurrentWeather(city);

        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text:
                error instanceof Error
                  ? error.message
                  : "Unable to retrieve current weather",
            },
          ],
          isError: true,
        };
      }
    },
  );

  server.registerTool(
    "get_weather_forecast",
    {
      description:
        "Get a daily weather forecast for a city for up to seven days.",

      inputSchema: {
        city: z.string().min(1).describe("City name"),

        days: z
          .number()
          .int()
          .min(1)
          .max(7)
          .default(7)
          .describe("Number of forecast days"),
      },
    },
    async ({ city, days }) => {
      try {
        const result = await getWeatherForecast(city, days);

        return {
          content: [
            {
              type: "text",
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text:
                error instanceof Error
                  ? error.message
                  : "Unable to retrieve weather forecast",
            },
          ],
          isError: true,
        };
      }
    },
  );

  return server;
}

void serveStdio(createServer);

console.error("Weather MCP Server is running");

Our Weather MCP Server implementation is now complete.

9. Run the MCP Server

We can start the server using:

npm run dev

Alternatively:

npx tsx src/index.ts

You should see:

Weather MCP Server is running

The server is now waiting for an MCP client to establish a connection.

Why are we using STDIO?

STDIO is a transport mechanism that allows a local MCP client to launch the server as a child process and communicate through standard input and output.

The communication flow looks like this:

MCP Client
    |
    | JSON-RPC messages
    |
    v
Standard Input
    |
    v
Weather MCP Server
    |
    v
Standard Output
    |
    | JSON-RPC responses
    |
    v
MCP Client

Important: STDIO uses standard output for protocol communication. Avoid using console.log() for debugging because it can corrupt the JSON-RPC message stream.

Use console.error() for logs instead.

10. Test the MCP Server Using MCP Inspector

Before connecting the server to an AI assistant, we should verify that its tools are working correctly.

MCP Inspector is a development tool that allows us to inspect MCP servers, discover their capabilities, and invoke their tools.

Run:

npx @modelcontextprotocol/inspector npx tsx src/index.ts

The Inspector will open a local web interface.

Follow these steps:

  1. Connect to the Weather MCP Server.
  2. Open the Tools section.
  3. Find get_current_weather.
  4. Provide a city name.
  5. Execute the tool.
  6. Inspect the returned weather information.

For example:

Tool: get_current_weather

Input:

{
  "city": "New York"
}

You should receive a response containing the current weather data returned by Open-Meteo.

Next, test the forecast tool.

Tool: get_weather_forecast

Input:

{
  "city": "New York",
  "days": 7
}

The server should return daily forecast information for the requested location.

11. Connect the Weather MCP Server to Claude Desktop

Now that our server is working, let's connect it to an AI application.

For this example, we will use Claude Desktop.

Open the Claude Desktop configuration file.

On macOS, the configuration file is typically located at:

~/Library/Application Support/Claude/claude_desktop_config.json

Add the following MCP server configuration:

{
  "mcpServers": {
    "weather": {
      "command": "npx",
      "args": ["tsx", "/absolute/path/to/weather-mcp-server/src/index.ts"]
    }
  }
}

Replace /absolute/path/to/weather-mcp-server with the actual absolute path to your project.

Save the configuration and restart Claude Desktop.

Claude Desktop should now be able to discover the tools exposed by our Weather MCP Server.

The same server can also be connected to other MCP-compatible applications, although their configuration formats and setup processes may differ.

12. Test It with Natural-Language Queries

Let's see how the AI assistant can use our server.

Example 1: Current weather

User:

What is the current weather in New York?

AI assistant workflow:

  1. Understands that the user needs current weather information.
  2. Identifies get_current_weather as the appropriate tool.
  3. Calls the MCP tool with the city name.
  4. Receives the API response.
  5. Presents the information in natural language.

Illustrative assistant response:

The current weather in New York is:

Temperature: 18.5°C
Feels like: 17.2°C
Humidity: 55%
Wind speed: 12.4 km/h

Conditions: Partly cloudy

These values are examples, not live readings.

Example 2: Seven-day forecast

User:

Show me the weather forecast for New York
for the next seven days.

The AI assistant can invoke:

{
  "city": "New York",
  "days": 7
}

The get_weather_forecast tool retrieves the daily forecast, and the AI assistant summarizes the results.

Example 3: Compare weather conditions

User:

Is New York warmer than London today?

Our current implementation does not have a dedicated comparison tool. However, the AI assistant can call get_current_weather separately for both cities and compare their temperatures.

This demonstrates how an AI assistant can combine multiple MCP tool calls to answer a single user question.

13. Understanding How MCP Tools Work with AI Agents

One of the most important concepts to understand is that an MCP server does not independently decide when to execute its tools.

The AI application and model are responsible for determining which available tool is relevant to the user's request.

Consider this example:

User:
"What is the weather in New York?"

        |
        v

AI Model:
Understands the user's request.

        |
        v

Tool Selection:
get_current_weather

        |
        v

MCP Client:
Sends the tool call.

        |
        v

Weather MCP Server:
Executes the registered handler.

        |
        v

Open-Meteo API:
Returns weather information.

        |
        v

MCP Client:
Receives the tool result.

        |
        v

AI Model:
Generates a natural-language response.

        |
        v

User:
Receives the weather information.

This separation is important:

  • The AI model handles language understanding and tool selection.
  • The MCP client manages communication.
  • The MCP server implements the available functionality.
  • The external API provides the underlying weather data.

This architecture allows the same MCP server to be reused by different compatible AI applications.

14. Production Best Practices

The implementation above is suitable for learning and local development. Before using it in production, consider the following improvements.

1. Handle ambiguous locations

A city name can refer to multiple places.

For example, there may be multiple cities named Springfield.

Instead of always choosing the first geocoding result, return multiple matches and allow the user or AI assistant to select the correct location.

2. Add caching

Weather information does not always need to be retrieved from the external API for every request.

You can cache responses for a short period to reduce unnecessary API calls and improve performance.

3. Add request timeouts

External APIs can become slow or temporarily unavailable.

Our implementation already uses AbortSignal.timeout(10000) to prevent requests from waiting indefinitely.

For production, consider retry policies with appropriate backoff and limits.

4. Improve error handling

Handle different error scenarios separately:

  • Invalid city name
  • No matching location
  • External API unavailable
  • Request timeout
  • Invalid API response
  • External API rate limiting

Return clear, useful error messages to the MCP client without exposing internal implementation details.

5. Validate tool inputs

Use Zod to validate incoming tool arguments.

For example, the forecast tool restricts the number of requested days to a value between one and seven.

Input validation helps prevent unexpected requests from reaching your application logic.

6. Use structured logging

Use a proper logging library for production applications.

Log useful operational information such as:

  • Tool name
  • Request duration
  • External API status
  • Error details
  • Request correlation ID

Never write application logs to STDIO standard output when using the STDIO transport.

7. Choose the appropriate transport

STDIO is useful for local integrations where an MCP client launches the server.

For remote deployments, multiple clients, or shared infrastructure, consider Streamable HTTP.

The official MCP TypeScript SDK supports both approaches.

8. Follow the weather data licensing requirements

Review the Open-Meteo terms, usage limits, and attribution requirements before deploying the integration commercially.

For production workloads, choose a plan or provider that supports your expected traffic and business use case.

15. Possible Enhancements

Once the basic Weather MCP Server is working, we can extend it with additional capabilities.

FeatureDescription
Hourly forecastRetrieve temperature and precipitation by hour
Weather alertsRetrieve alerts where the provider supports them
Multiple locationsRetrieve weather for several cities in one request
Weather comparisonCompare temperatures and conditions between cities
Air qualityIntegrate an air-quality data provider
Historical weatherRetrieve historical weather information
Weather recommendationsProvide suggestions based on forecast conditions

We can also expose read-only weather data as MCP Resources and add reusable Prompts for common weather-related tasks.

This would make the server more capable and demonstrate additional parts of the MCP specification.

Conclusion

Building a Weather MCP Server is a practical way to understand how the Model Context Protocol connects AI applications with external services.

In this tutorial, we created a TypeScript-based MCP server that integrates with Open-Meteo and exposes two tools:

  • get_current_weather
  • get_weather_forecast

We also explored MCP architecture, tool registration, input validation, STDIO communication, MCP Inspector, and integration with Claude Desktop.

The most important takeaway is that MCP separates the AI application from the external functionality it needs. Rather than implementing a custom weather integration inside every AI application, we can build one reusable MCP server and expose its capabilities through a standardized protocol.

The same approach can be applied to much larger integrations, including GitHub, Jira, Slack, PostgreSQL, payment systems, and enterprise applications.

Start with a small MCP server, understand how tools are discovered and invoked, and gradually extend it into a production-ready integration.

References

Let's work together

Looking to discuss a project or explore potential collaboration? Reach out anytime.