Skip to main content
Glama
terisuke

MCP Weather Service

by terisuke

Метеорологическая служба MCP

Этот репозиторий представляет собой простую службу, которая предоставляет информацию о погоде с использованием протокола контекста модели (MCP). Вы можете получить информацию о погоде для нескольких городов (Фукуока, Токио, Осака, Москва, Нью-Йорк и т. д.).

оглавление

  1. Предпосылки

  2. Настройка проекта

  3. Как использовать

  4. Руководство по разработке

  5. Загрузить на GitHub

  6. Поиск неисправностей

Related MCP server: Weather MCP

Предпосылки

Для выполнения этого проекта вам понадобится следующее программное обеспечение:

  • Node.js (версия 18 и выше)

  • npm (обычно устанавливается вместе с Node.js)

  • Гит

Как установить

Установка Node.js и npm

  1. Загрузите установщик с официального сайта Node.js и установите его.

  2. После завершения установки проверьте ее, выполнив следующую команду в Терминале:

node -v
npm -v

Установка Git

  1. Загрузите установщик с официального сайта Git и установите его.

  2. После завершения установки проверьте ее, выполнив следующую команду в Терминале:

git --version

Настройка проекта

Создание нового проекта

  1. Создайте новый каталог и перейдите в него:

mkdir my-weather-mcp
cd my-weather-mcp
  1. Инициализируйте свой проект npm:

npm init -y
  1. Установите необходимые пакеты:

npm install @modelcontextprotocol/sdk axios zod typescript @types/node https-proxy-agent
npm install --save-dev ts-node
  1. Создайте файл конфигурации TypeScript:

npx tsc --init
  1. Отредактируйте файл tsconfig.json следующим образом:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "outDir": "./build",
    "strict": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}
  1. Отредактируйте раздел скриптов вашего файла package.json следующим образом:

"scripts": {
  "build": "tsc && node -e \"import('fs').then(fs => fs.default.chmodSync('build/index.js', '755'))\"",
  "start": "node build/index.js",
  "inspect": "npx @modelcontextprotocol/inspector build/index.js",
  "dev": "ts-node src/index.ts"
}
  1. Создайте структуру каталогов проекта:

mkdir -p src test

Клонировать существующий проект

Если вы хотите использовать существующий проект, клонируйте его:

git clone https://github.com/terisuke/my-weather-mcp.git
cd my-weather-mcp
npm install

Как использовать

Построить и запустить

Для сборки и запуска проекта используйте следующие команды:

npm run build && npm run start

Использование инспектора

Чтобы протестировать службу погоды с помощью MCP Inspector, выполните следующую команду:

npm run build && npm run inspect

После запуска Inspector вы можете взаимодействовать со службой погоды, перейдя по адресу http://127.0.0.1:6274 в своем браузере.

Получить информацию о погоде

С помощью Инспектора вы можете получить информацию о погоде в следующих городах:

  • Фукуока

  • Токио

  • Осака

  • Москва

  • Нью-Йорк

Можно указать и другие города, но они должны распознаваться API Open-Meteo.

Руководство по разработке

Структура файла

my-weather-mcp/
├── build/              # コンパイルされたJavaScriptファイル
├── src/                # TypeScriptソースコード
│   └── index.ts        # メインのアプリケーションコード
├── test/               # テストファイル
├── package.json        # プロジェクト設定
├── tsconfig.json       # TypeScript設定
└── README.md           # このファイル

Исправление кода

  1. Отредактируйте файл src/index.ts чтобы добавить или изменить функциональность.

  2. Чтобы проверить изменения, выполните следующую команду:

npm run build && npm run inspect
  1. Как только вы убедитесь, что изменения работают, зафиксируйте их.

Загрузить на GitHub

Создание вашего первого репозитория GitHub

  1. Перейдите на GitHub и создайте учетную запись или войдите в систему.

  2. Нажмите кнопку «+» в правом верхнем углу и выберите «Новый репозиторий».

  3. Введите имя репозитория (например, my-weather-mcp ) и добавьте необязательное описание.

  4. Сделайте свой репозиторий публичным или частным и нажмите «Создать репозиторий».

Инициализируйте и отправьте локальный репозиторий

  1. В локальном каталоге проекта инициализируйте репозиторий Git:

git init
  1. Добавьте изменения в область подготовки:

git add .
  1. Внесите изменения:

git commit -m "初回コミット:MCP天気サービスの実装"
  1. Добавьте удаленный репозиторий (используя URL-адрес репозитория из GitHub):

git remote add origin https://github.com/ユーザー名/my-weather-mcp.git
  1. Отправьте изменения в удаленный репозиторий:

git push -u origin main

Передача изменений в существующий репозиторий

  1. Добавьте изменения в область подготовки:

git add .
  1. Внесите изменения:

git commit -m "変更内容の説明"
  1. Отправьте изменения в удаленный репозиторий:

git push

Создание запроса на извлечение

  1. Перейдите на страницу репозитория на GitHub.

  2. Нажмите вкладку «Запросы на извлечение», а затем нажмите кнопку «Новый запрос на извлечение».

  3. Выберите базовую ветвь и ветвь сравнения.

  4. Нажмите кнопку «Создать запрос на извлечение».

  5. Введите название и описание вашего запроса на извлечение и нажмите кнопку «Создать запрос на извлечение».

Поиск неисправностей

Распространенные проблемы и решения

Ошибка ERR_PACKAGE_PATH_NOT_EXPORTED

Эта ошибка возникает, если путь импорта для пакета @modelcontextprotocol/sdk неверен. Пожалуйста, исправьте это следующим образом:

// 誤ったインポート
import { McpServer } from "@modelcontextprotocol/sdk";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/transports";

// 正しいインポート
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

Ошибка сетевого подключения

Если при выполнении вызова API возникает сетевая ошибка, проверьте настройки прокси-сервера. Вы можете использовать прокси, установив переменные среды HTTP_PROXY или HTTPS_PROXY :

export HTTP_PROXY=http://プロキシサーバー:ポート
export HTTPS_PROXY=https://プロキシサーバー:ポート

Другие вопросы

Если проблема не устранена, пожалуйста, создайте сообщение о проблеме, указав следующую информацию:

  • Сообщение об ошибке, которое произошло

  • Версию Node.js и npm, которую вы используете

  • Команда выполнена.

  • Ожидаемое и фактическое поведение

Available Tools

1 tool
get-weatherC

Get weather information for a city

NameRequiredDescriptionDefault
cityYesCity name to get weather for

TDQS

C2.9/5.0
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It only states the basic function without mentioning any behavioral traits such as rate limits, error handling, data freshness, or authentication requirements. For a tool with no annotations, this is a significant gap in transparency.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's purpose without any unnecessary words. It is appropriately sized and front-loaded, making it easy to understand at a glance. Every part of the sentence earns its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the lack of annotations and output schema, the description is incomplete. It doesn't cover behavioral aspects like performance, errors, or return format, which are crucial for a tool that fetches dynamic data like weather. The description alone is insufficient for full contextual understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, with the single parameter 'city' documented as 'City name to get weather for'. The description adds no additional semantic context beyond what the schema provides, such as format examples or constraints. With high schema coverage, the baseline score of 3 is appropriate.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('Get') and resource ('weather information') with the target ('for a city'). It's specific about what the tool does, but since there are no sibling tools, it doesn't need to differentiate from alternatives. It avoids tautology by not just restating the name.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives or any contextual prerequisites. It simply states the function without indicating scenarios, limitations, or comparisons to other tools. This leaves usage entirely implicit.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 1 tool update
    • First observedget-weather

TDQS

B3/5.0

Scored across 1 tool

Disambiguation5/5

With only one tool, there is no possibility of ambiguity or overlap between tools. The tool 'get-weather' has a clear, singular purpose that cannot be confused with any other tool in the set.

Naming Consistency5/5

The single tool name 'get-weather' follows a consistent verb_noun pattern, and with only one tool, there is no inconsistency or deviation to evaluate. The naming is straightforward and predictable.

Tool Count2/5

A single tool for a weather service is too few for the apparent scope, as it lacks basic operations like forecasts, historical data, or multi-location queries. This minimal set feels thin and incomplete for a typical weather domain.

Completeness1/5

The tool surface is severely incomplete for a weather service. It only provides current weather for a city, missing essential operations such as forecasts, alerts, historical data, or support for multiple locations, which are core to weather-related workflows.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    A Model Context Protocol server that retrieves current weather information for specified cities using the Open-Meteo API, requiring no API key.
    8
    1,939 PyPI
    60
    Apache 2.0
  • F
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol server that provides current weather information and 3-day forecasts for specified cities using the Open-Meteo API.
    1
    -
  • A
    license
    Not graded
    quality
    D
    maintenance
    A Model Context Protocol server that provides weather information using the Open-Meteo API, allowing users to get current weather for specific cities and retrieve weather data for date ranges.
    Apache 2.0

Appeared in Searches