Unit Converter MCP Server
API конвертера единиц измерения + руководство по MCP
собирает приложение FastAPI, оборачивает его с помощью FastMCP, монтирует конечные точки MCP HTTP/SSE, регистрирует ресурсы и подсказки, а также запускает uvicorn.
requirements.txt – зависимости Python.
Предварительные требования
Python 3.10+ (протестировано на 3.12).
Виртуальное окружение.
Инспектор npm ниже.
⸻
Related MCP server: mcp-units
Настройка из этой папки
python -m venv .venv
# Mac or Gitbash
source .venv/bin/activate
# Windows powershell:
.venv\Scripts\activate
python -m pip install -r requirements.txt⸻
Запуск HTTP + MCP сервера
# start the server
python converter_streamable_http_server.py
# or
python -m converter_streamable_http_server
Вы увидите:
Swagger UI: http://localhost:8003/docs
ReDoc: http://localhost:8003/redoc
Конечные точки MCP, обслуживаемые FastMCP:
streamable-http: http://localhost:8003/mcp
⸻
Попробуйте HTTP-конечные точки (curl)
curl -X POST "http://localhost:8003/miles-to-kilometers?miles=3.1" \
-H "Authorization: Bearer 143f4a46d74fee0d7918b2857577868cb3daf9e6e50ee91c2f7975ba26fdb8f7"
# If we use pydantic models
curl -X POST "http://localhost:8003/miles-to-kilometers" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer Y658139cf61948208ed76a4b36122b9552ec5c3f6da5e02f7c5d85d995dede17dE" \
-d "3.1"# Celsius → Fahrenheit
curl -X POST "http://localhost:8003/celsius-to-fahrenheit" \
-H "Content-Type: application/json" \
-d "25"# Fahrenheit → Celsius
curl -X POST "http://localhost:8003/fahrenheit-to-celsius" \
-H "Content-Type: application/json" \
-d "86"# Kilometers → Miles
curl -X POST "http://localhost:8003/kilometers-to-miles" \
-H "Content-Type: application/json" \
-d "5"# Miles → Kilometers (rejects negative values)
curl -X POST "http://localhost:8003/miles-to-kilometers" \
-H "Content-Type: application/json" \
-d "3.1"Каждая конечная точка возвращает JSON вида:
{ "result": , "operation": "..." } или { "error": "..." } для неверного ввода.
Заголовки и аутентификация (общие для всех)
Добавьте тип контента JSON (и при необходимости ваш токен аутентификации)
-H "Content-Type: application/json"
-H "Authorization: Bearer "
Наш сервер пока не требует аутентификации, мы можем опустить заголовок Authorization.
Использование с MCP (пример для VS Code)
Запустите сервер, как описано выше.
Укажите вашему MCP-клиенту процесс.
// Example VS Code .vscode/mcp.json entry:
{
"servers": {
"UnitConverter": {
"command": "python",
"args": ["converter_api_tutorial.py"]
}
}
}В MCP-клиенте выведите список артефактов. Вы должны увидеть:
Инструменты: celsius_to_fahrenheit, fahrenheit_to_celsius, kilometers_to_miles, miles_to_kilometers
Ресурсы: resource://unit_reference, resource://troubleshooting_guide
Подсказки: explain_conversion, api_usage
⸻
Проверка с помощью инспектора npm MCP
исследуйте всё (инструменты, ресурсы, подсказки) в браузере.
при условии, что сервер уже запущен на http://localhost:8003
# If env error appears
npx @modelcontextprotocol/inspector@latest -e DUMMY=1 --url http://localhost:8003/mcp --transport streamable-http
# If you want to test the older HTTP:
npx @modelcontextprotocol/inspector@latest -e DUMMY=1 --url http://localhost:8003/mcp --transport http
# If you want to test the deprecated SSE:
npx @modelcontextprotocol/inspector@latest -e DUMMY=1 --url http://localhost:8003/sse --transport sseЗапуск только STDIO-сервера
# If venv is ".venv", change to .\.venv\Scripts\python.exe
npx @modelcontextprotocol/inspector python converter_stdio_server.pyИнтерфейс по умолчанию работает на localhost:5173.
Измените порт интерфейса, если нужно: CLIENT_PORT=8080 npx @modelcontextprotocol/inspector --url http://localhost:8003/mcp --transport http
Добавьте заголовки, если требуется: --header "Authorization: Bearer TOKEN".
Примеры JSON-RPC для подсказок и ресурсов
Список всех подсказок
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"prompts/list","params":{},"id":1}'⸻
Получить конкретную подсказку
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"prompts/get","params":{"name":"summarize"},"id":2}'⸻
Отрисовать/выполнить подсказку с переменными
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"prompts/render","params":{"name":"summarize","variables":{"text":"This is the content to summarize","tone":"neutral"}},"id":3}'Список доступных ресурсов
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"resources/list","params":{},"id":4}'Чтение ресурса по URI
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"resources/read","params":{"uri":"file:///data/report.pdf"},"id":5}'Поиск ресурсов (если поддерживается)
curl -s -X POST <SERVER_URL> \
-H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","method":"resources/search","params":{"query":"error OR exception","limit":50},"id":6}'⸻
Обработка ошибок
Ошибка парсинга (-32700)
Неверный запрос (-32600)
Метод не найден (-32601)
Неверные параметры (-32602)
Внутренняя ошибка (-32603)
Примечания
macOS/Linux (bash/zsh) • Приведенные выше примеры будут работать как есть.
# Windows PowerShell
curl -Method POST <SERVER_URL> ` -Headers @{ "Content-Type"="application/json" }`
-Body '{"jsonrpc":"2.0","method":"prompts/list","params":{},"id":1}'Windows CMD
curl -s -X POST <SERVER_URL> -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"method\":\"prompts/list\",\"params\":{},\"id\":1}"Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Unofficial OpenWeather MCP — wraps the OpenWeatherMap API (openweathermap.org)
Remote MCP for JSON repair, hashing, formatting, IDs, dates, units, and other small tools.
Baking unit conversion (cups/grams/temp/recipe scaling). convert_amount, convert_temperature
60+ units, live FX, timezones, and date arithmetic for AI agents.
Related MCP Servers
- AlicenseAqualityDmaintenanceMCP server for converting cooking measurements (volume, weight, temperature) between common units like ml, cup, g, oz, and Celsius/Fahrenheit.31MIT
- AlicenseAqualityDmaintenanceAn MCP server that provides deterministic unit conversions backed by Pint, enabling exact unit conversions, compatibility checks, and parsing of quantities for LLMs.5MIT
- FlicenseNot gradedqualityDmaintenanceProvides a set of everyday utility tools via MCP, including greetings, calculations, time, UUID generation, secure passwords, BMI/age calculation, and unit conversion.-
- AlicenseNot gradedqualityDmaintenanceA deterministic unit conversion MCP server with fixed tables, offering tools to convert length, mass, temperature, and volume, list units, and compare quantities. Designed for judge-friendly schema clarity and no network I/O.MIT