MCP Server с нуля: полное руководство для разработчиков

Протокол · FastMCP · Tools/Resources/Prompts · HTTP-деплой · knowledge-base project

MCP Server с нуля: полное руководство для разработчиков

LLM «недостаточно умны», потому что не имеют доступа к внешним tools и live data. Если нужно, чтобы Claude или GPT ходили в БД, дергали API и читали файлы — Model Context Protocol (MCP) это open-standard ответ. Гайд для backend- и AI-разработчиков с Python или TypeScript: от fundamentals протокола через setup окружения, регистрацию Tools, Resources и Prompts, отладку в MCP Inspector, HTTP+SSE remote deployment до personal knowledge-base project — в итоге production-ready MCP Server.

01

Что такое MCP? Разберите протокол до первой строки кода

Tool-calling прошёл путь Function Calling → Plugins → MCP. Anthropic спроектировал MCP как стандарт коммуникации AI с внешними системами — один Server, множество Clients без переписывания интеграций.

Архитектура: Client ↔ Server ↔ три capability

MCP Client (Claude Desktop, Cursor, custom client) общается с MCP Server (ваш код) по JSON-RPC 2.0. Server экспонирует Tools (callable functions: search, calc, SQL), Resources (read-only data: files, URLs, streams) и Prompts (reusable templates).

Transport layer: stdio (local subprocess, минимальная latency) или HTTP + SSE (remote, multi-client). Lifecycle: initialize handshake → capability negotiation → request/response → shutdown.

  1. 01

    Нет live data: training cutoff блокирует котировки и ticket status — нужны external API.

  2. 02

    Vendor lock-in: Plugins, Function Calling и Tool Use требуют отдельных adapter-слоёв под каждую модель.

  3. 03

    IDE fragmentation: Cursor, VS Code и Claude Desktop не делят tool assets между собой.

  4. 04

    Framework binding: LangChain Tools не портируются в CrewAI без rewrite.

  5. 05

    N×M cost: N models × M systems взрывает maintenance; MCP схлопывает это в один Server.

ИзмерениеMCPOpenAI Function CallingLangChain Tools
СтандартизацияOpen protocolVendor-specificFramework-bound
Transportstdio / HTTPHTTPHTTP
Cross-modelДаНетЧастично
Resources / PromptsNativeНе поддерживаетсяНе поддерживается
Экосистема10 000+ Server (2026)ЗрелаяЗрелая

До первого commit: MCP — не очередной SDK, а стандарт протокола для AI toolization. Владение им — core competency AI-инженера в 2026.

02

Setup окружения: выбор языка и layout проекта

Python (official SDK mcp + FastMCP) — fastest onboarding. TypeScript (@modelcontextprotocol/sdk) — для full-stack. Ниже Python как primary, TypeScript — reference.

bash · setup
python -m venv .venv
source .venv/bin/activate
pip install mcp

npm init -y
npm install @modelcontextprotocol/sdk

Рекомендуемая структура:

text · layout
my-mcp-server/
├── server.py
├── tools/
│   ├── calculator.py
│   └── web_search.py
├── resources/
│   └── file_reader.py
├── prompts/
│   └── templates.py
├── tests/
│   └── test_tools.py
├── pyproject.toml
└── README.md

Debug stack: MCP Inspector (npx @modelcontextprotocol/inspector), Claude Desktop (claude_desktop_config.json), Cursor MCP settings (Settings → MCP Servers). Spec: modelcontextprotocol.io.

03

Первый MCP Server: Hello World и интеграция с Cursor

Шестишаговый runbook — первый callable tool за ~30 минут.

python · server.py
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("my-first-server")

@mcp.tool()
def say_hello(name: str) -> str:
    """Приветствует пользователя по имени"""
    return f"Hello, {name}! Это ваш первый MCP tool."

if __name__ == "__main__":
    mcp.run()
  1. 01

    venv + install mcp: pip install mcp, Python ≥ 3.10.

  2. 02

    Регистрация say_hello: декоратор @mcp.tool(); docstring = tool description для LLM.

  3. 03

    Inspector: npx @modelcontextprotocol/inspector python server.py — тест tools/list и tools/call.

  4. 04

    Cursor MCP config: {"command":"python","args":["/absolute/path/to/server.py"]}, restart — tool в Agent context.

  5. 05

    Claude Desktop: правка ~/Library/Application Support/Claude/claude_desktop_config.json, формат идентичен Cursor.

  6. 06

    Verify: в Cursor — «вызови say_hello для VpsMesh»; Agent должен выбрать tool и вернуть result.

Hint: function signature — это документация. Типы параметров, return type и docstring напрямую попадают в LLM context и определяют, выберет ли Agent ваш tool.

04

Tools: пять production-примеров для AI

Naming: verb-first (search_web, query_database). Сложные inputs — через Pydantic:

python · pydantic input
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description="Поисковый запрос")
    max_results: int = Field(default=5, description="Макс. число результатов")
    language: str = Field(default="ru", description="Язык результатов")

@mcp.tool()
def web_search(input: SearchInput) -> list[dict]:
    """Выполняет web search, возвращает список результатов"""
    ...

Пять практических tools

  • Calculator: safe eval математических выражений, без naked eval.
  • File I/O: allowlist paths, read/write локальных Markdown и config.
  • HTTP client: GET/POST с unified timeout и retry policy.
  • Read-only SQL: parameterized queries, защита от injection.
  • Timezone utils: current time, conversion, business-day calc.
python · async tool
import httpx

@mcp.tool()
async def fetch_url(url: str) -> str:
    """Загружает содержимое URL"""
    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.get(url)
        return response.text

Error handling: structured errors с error_code и message для expected failures; network IO — обязательный timeout; write ops — permission check и audit log.

05

Resources и Prompts: data feeds и reusable templates

Resources: read-only dynamic content

Resource vs Tool: Resource — data provider (read-only), Tool — action executor. Addressing через URI: file://, http://, custom://.

python · static & dynamic resources
@mcp.resource("config://app-settings")
def get_app_settings() -> str:
    return json.dumps({"version": "1.0", "env": "production"})

@mcp.resource("user://{user_id}/profile")
def get_user_profile(user_id: str) -> str:
    user = db.query_user(user_id)
    return json.dumps(user)

MIME types: text/plain, application/json, binary (images, PDF), streaming live data. Filesystem resource server: list dir, read file, subscribe на изменения.

Prompts: parameterized templates

MCP Prompt — predefined fragment с dynamic parameter injection. Multi-turn templates с ролями user и assistant: code review, interview sim, debug assistant.

python · code review prompt
from mcp.types import PromptMessage, TextContent

@mcp.prompt()
def code_review_prompt(language: str, code: str) -> list[PromptMessage]:
    return [
        PromptMessage(
            role="user",
            content=TextContent(
                type="text",
                text=f"Проведи code review {language}-кода: quality, bugs, performance.\n```{language}\n{code}\n```"
            )
        )
    ]
06

HTTP transport, debugging и типовые ошибки

ХарактеристикаstdioHTTP + SSE
DeployLocal processRemote server
LatencyМинимальнаяNetwork-bound
Multi-clientНетДа
Use caseLocal toolsSaaS / team sharing
python · streamable-http
mcp = FastMCP("remote-server", transport="streamable-http")

if __name__ == "__main__":
    mcp.run(host="0.0.0.0", port=8000)

Remote security: Bearer token auth, API key middleware, CORS, rate limiting. Production: не кладите secrets в tool schema.

MCP Inspector и unit tests

Inspector — tools/call, JSON-RPC logs, error simulation. Unit tests через official Client SDK и stdio subprocess:

python · pytest
@pytest.mark.asyncio
async def test_calculator_tool():
    server_params = StdioServerParameters(command="python", args=["server.py"])
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            result = await session.call_tool("calculate", {"expression": "2 + 2"})
            assert result.content[0].text == "4"
ОшибкаПричинаFix
Tool не виден в AIНеверный path в configAbsolute path в command/args
JSON serialization failUnsupported return typeCast в str или dict
Timeout disconnectSlow tool executionasync + explicit timeout
Permission deniedPath outside allowlistConfigure allowed directories
07

Production deploy, knowledge-base project и экосистема MCP

Docker и cloud

dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "server.py"]

Deploy targets: Railway / Render (personal projects), AWS Lambda / Google Cloud Run (serverless), self-hosted VPS (Nginx reverse proxy). Observability: structured logs, Prometheus metrics, Sentry, health check endpoint. Declare MCP protocol version; backward-compatible tool upgrades.

Проект: personal knowledge-base MCP Server

Goal: semantic search по локальным Markdown, create/update notes. Stack: ChromaDB / Qdrant, text-embedding-3-small, watchfiles для file watch. Tools: index, semantic search, write; Resources: file serving. В Cursor: «Что я писал про MCP на прошлой неделе?» — Agent вызывает search tool.

Community Servers и тренды 2026

  • mcp-server-filesystem — file operations
  • mcp-server-github — repo operations
  • mcp-server-brave-search — web search
  • mcp-server-postgres — SQL queries
  • mcp-server-slack — messaging

2026: Cursor, Claude Desktop, VS Code, OpenAI, Gemini — native MCP support; Marketplace и enterprise security standards созревают. Next steps: spec deep dive, public Server publish, MCP + Agent orchestration, open-source contribution. SDK: Python, TypeScript, Inspector.

Hard data

  • Protocol: JSON-RPC 2.0; discovery через runtime tools/list.
  • Scale: 10 000+ MCP Servers к 2026 — network effect как у раннего HTTP.
  • Integration cost: unified MCP interface снижает dev cost на 38–55% (industry surveys).
  • Vendor backing: Q1–Q2 2026 — OpenAI, Google, Microsoft; governance в AAIF.

Laptop годится для MCP POC, но lid-close sleep и отсутствие macOS native toolchain + long-running daemon убивают 7×24. Pure Linux VPS тянет HTTP+SSE, но Keychain, Xcode и macOS-dependent MCP tools — pain. Командам, которые держат несколько MCP Server как always-on infrastructure и копят tool-call compound interest на неделях, VpsMesh Mac Mini M4 cloud rental упаковывает uptime, remote KVM и predictable OpEx. Тарифы: цены аренды Mac Mini M4, деплой: центр помощи, заказ: оформить заказ.

FAQ

Три частых вопроса

Python + official SDK mcp + FastMCP — fastest path для backend и AI-инженеров. TypeScript SDK @modelcontextprotocol/sdk — для frontend/full-stack. Protocol layer полностью compatible; logic мигрируется один к одному. Node-heavy team → TS; data/ML-heavy → Python.

Tools — action executors: меняют external state или запускают computation (search, write file, HTTP call). Resources — read-only data по URI: config://app-settings, user://{id}/profile. Rule of thumb: read → Resource, act → Tool.

HTTP+SSE на Railway, Cloud Run или Linux VPS покрывает многие сценарии. Если toolchain завязан на macOS native APIs, Keychain, или нужны Cursor Agent + несколько Server 7×24 без lid-close sleepMac Mini M4 monthly rental надёжнее. One-month trial для валидации tools/call latency curves: цены аренды, оформить заказ, центр помощи.