mcp-server-python-mt9e4j8z
MCP Server Template (Python)
Минимальный шаблон сервера Model Context Protocol для Render. Форкните его, добавьте свои инструменты и разверните.
Что входит
Рабочий MCP-сервер на базе MCP Python SDK с транспортом Streamable HTTP
Аутентификация по Bearer-токену через
MCP_API_TOKEN(автоматически генерируется при развертывании)Один пример инструмента (
hello) для демонстрации паттернаЭндпоинт
/healthдля проверок работоспособности RenderBlueprint
render.yamlдля развертывания в один кликФайл
AGENTS.md, чтобы ИИ-ассистенты для программирования могли создавать новые инструменты за вас
Примечание: Этот шаблон по умолчанию развертывается на бесплатном тарифе. Бесплатные сервисы отключаются после 15 минут бездействия, что вызывает холодный старт на 30-60 секунд при следующем запросе. MCP-клиенты могут выйти из-за тайм-аута во время этой задержки. Для надежного использования перейдите на платный тариф в Render Dashboard — тариф Starter обеспечивает непрерывную работу вашего сервиса.
Related MCP server: MCP Server Template (TypeScript)
Начало работы локально
git clone https://github.com/render-examples/mcp-server-python.git
cd mcp-server-python
pip install -r requirements.txt
python server.pyСервер запускается на http://localhost:10000. MCP-эндпоинт находится по адресу /mcp.
Запуск тестов
pip install -r requirements.txt
pytestАутентификация
Сервер аутентифицирует запросы с помощью Bearer-токена. Blueprint Render автоматически генерирует случайный MCP_API_TOKEN при первом развертывании.
Чтобы найти свой токен после развертывания, перейдите в Render Dashboard > ваш сервис > Environment и скопируйте значение MCP_API_TOKEN.
Клиенты должны включать токен в заголовок Authorization:
Authorization: Bearer YOUR_TOKENКогда MCP_API_TOKEN не задан (например, при локальной разработке), аутентификация отключена, и все запросы пропускаются.
Управление токеном
После первоначального развертывания токен находится в вашем управлении:
Ротируйте его, обновив
MCP_API_TOKENв Render Dashboard в разделе Environment. Сервис автоматически перезапустится с новым значением.Сгенерируйте новый токен любым из этих способов:
openssl rand -base64 32python3 -c "import secrets; print(secrets.token_urlsafe(32))"Генератор менеджера паролей (1Password, Bitwarden и т. д.)
Не коммитьте токены в систему контроля версий. Используйте переменные окружения или файлы
.env(они находятся в.gitignore).Для многопользовательских или продакшн-сред рассмотрите возможность перехода на OAuth 2.1.
Подключение к вашему MCP-серверу
После развертывания на Render ваш MCP-эндпоинт доступен по адресу:
https://your-service-name.onrender.com/mcpCursor
Добавьте в .cursor/mcp.json вашего проекта:
{
"mcpServers": {
"my-mcp-server": {
"url": "https://your-service-name.onrender.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_TOKEN"
}
}
}
}Claude Desktop
Добавьте в конфигурацию Claude Desktop:
{
"mcpServers": {
"my-mcp-server": {
"type": "streamable-http",
"url": "https://your-service-name.onrender.com/mcp",
"headers": {
"Authorization": "Bearer YOUR_TOKEN"
}
}
}
}Codex
codex mcp add --transport streamable-http \
--url https://your-service-name.onrender.com/mcp \
--header "Authorization: Bearer YOUR_TOKEN" \
my-mcp-serverИли добавьте в .codex/config.toml:
[mcp_servers.my-mcp-server]
url = "https://your-service-name.onrender.com/mcp"
http_headers = { Authorization = "Bearer YOUR_TOKEN" }Добавление инструментов
Добавляйте инструменты в server.py, декорируя функцию с помощью @mcp.tool():
@mcp.tool()
def fetch_weather(city: str, units: str = "celsius") -> str:
"""Get the current weather for a city."""
# your implementation here
return f"Weather for {city}"Docstring становится описанием инструмента, которое MCP-клиенты показывают LLM. Всегда пишите понятное описание.
В этом репозитории есть файл
AGENTS.md. Если вы используете ИИ-ассистента для программирования (Cursor, Copilot, Codex, Windsurf и т. д.), вы можете попросить его «добавить новый инструмент», и он автоматически будет следовать соглашениям изAGENTS.md.
Структура проекта
server.py MCP server with example tool and health check
requirements.txt Python dependencies
render.yaml Render Blueprint for deployment
.env.example Environment variable reference
tests/test_server.py Test suite (auth, health, tool calls)
pyproject.toml pytest configuration
AGENTS.md Instructions for AI coding assistants
CLAUDE.md Pointer to AGENTS.md for Claude CodeУзнать больше
This server cannot be deployed
Maintenance
Related MCP Connectors
Model Context Protocol server for the Apideck Unified API. Connect any MCP-compatible agent framework to 100+ accounting systems, HRIS platforms, file storage providers, and more through one integration. More information https://www.apideck.com/mcp-server
A Model Context Protocol server for Wix AI tools
Enable secure connectivity between Sentry issues and debugging data, and LLM clients, using a Model Context Protocol (MCP) server.
A comprehensive Model Context Protocol (MCP) server that enables AI assistants to interact with yo…
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA minimal template for deploying Model Context Protocol servers on Render with Streamable HTTP transport, bearer token authentication, and an example hello tool.-
- FlicenseNot gradedqualityCmaintenanceA minimal Model Context Protocol server template deployable on Render, providing Streamable HTTP transport, bearer token authentication, and a pattern for adding custom tools.-
- FlicenseNot gradedqualityCmaintenanceA minimal Model Context Protocol server template for Render with bearer token authentication, an example tool, and a health check endpoint. Enables deploying custom MCP tools quickly on Render.-
- FlicenseNot gradedqualityCmaintenanceThis template enables developers to quickly scaffold, deploy, and extend a Model Context Protocol server on Render, with bearer-token authentication and a streamable HTTP endpoint, by adding custom tools via Python.-