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

К 2026 году в экосистеме MCP зарегистрировано свыше 10 000 Server; Cursor, Claude Desktop и VS Code поддерживают протокол нативно. Ниже — от wire contract до Tools / Resources / Prompts, HTTP remote deploy, персональной knowledge base и production-ready Docker stack.

LLM не имеет прямого доступа к вашей БД, internal API и файловой системе — нужен стандартизированный data/tool plane. Model Context Protocol (MCP), открытый Anthropic в ноябре 2024, даёт Claude / GPT / Cursor единый JSON-RPC контракт для discovery и invocation вашего Server. Статья для backend- и AI-инженеров с Python или TypeScript: ① архитектура MCP и lifecycle сессии; ② bootstrap окружения и Hello World; ③ реализация Tools, Resources, Prompts; ④ HTTP transport и production deploy; ⑤ end-to-end проект personal knowledge base. Протокол — в глубоком разборе MCP; Skills vs MCP — в гиде по Cursor Agent Skills.

00Зачем AI нужен MCP: от Function Calling к открытому протоколу

Root cause «слабости» LLM в production — отсутствие deterministic bridge во внешние системы. Вы хотите, чтобы Claude читал Postgres, GPT дергал billing API, Cursor писал в sandbox filesystem — без MCP каждый Host изобретает свой adapter layer.

Эволюция tool calling: Function Calling → Plugins → MCP. Function Calling — vendor lock-in на один API shape. Plugins — закрытые marketplaces без reuse между IDE. MCP — cross-model, cross-client wire spec: один Server, N Host'ов.

Целевая функция MCP — снять N×M интеграционный долг (N моделей × M инструментов). После этой статьи вы сможете самостоятельно собрать, отладить и задеплоить production MCP Server.

БольИнтеграция без MCP: где ломается инженерный процесс

  • Дублирование glue code: отдельная filesystem-обвязка для Cursor, Claude Desktop и VS Code — три config schema, три security review.
  • Vendor migration = rewrite: смена Claude на GPT или Gemini переписывает integration layer, а не меняет endpoint в конфиге.
  • Function Calling не покрывает context plane: нет нативного read-only resource channel и reusable prompt templates — только side-effectful calls.
  • Debug black box: без единого Inspector и JSON-RPC trace tool invocation failures превращаются в «модель галлюцинирует».

01Архитектура MCP: Client, Server и три capability

Client — Host-side (Claude Desktop, Cursor, custom agent runtime). Server — ваш capability provider. Transport: JSON-RPC 2.0 over stdio (local child process) или HTTP + SSE / Streamable HTTP (remote). Lifecycle: initialize handshake → capability negotiation → request/response loop → graceful shutdown.

Server экспонирует три примитива:

  • Tools — side-effectful или compute operations (search, SQL, HTTP proxy)
  • Resources — read-only data plane (files, configs, streams) по URI
  • Prompts — parameterized prompt templates для multi-turn consistency
ИзмерениеMCPOpenAI Function CallingLangChain Tools
СтандартизацияОткрытая спецификацияVendor-privateFramework-bound
Transportstdio / HTTPHTTP onlyHTTP (ad hoc)
Cross-modelДаНетЧастично
Resources / PromptsFirst-classНетНет
Экосистема10 000+ Server (2026)ЗрелаяЗрелая

02Подготовка окружения: Python primary, TypeScript reference

Python (рекомендуется для старта): официальный SDK mcp, декораторный FastMCP API, минимальный boilerplate. TypeScript (frontend / fullstack): SDK @modelcontextprotocol/sdk, тот же wire contract. Ниже — Python primary path; TS — parity notes.

Bootstrap
# Python
python -m venv .venv
source .venv/bin/activate
pip install mcp httpx pydantic

# TypeScript (reference)
npm init -y
npm install @modelcontextprotocol/sdk

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

my-mcp-server/
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 (official UI), Claude Desktop local integration, Cursor через .cursor/mcp.json. Спека: modelcontextprotocol.io.

03Первый MCP Server: Hello World

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()
Запуск и smoke test
python server.py
npx @modelcontextprotocol/inspector python server.py

В .cursor/mcp.json (Cursor) или claude_desktop_config.json (Claude Desktop) укажите command + args на python server.py. После restart Host'а проверьте tools/list — tool должен появиться в planner context.

04Tools: функции, которые модель может вызвать

Tool contract: type hints + docstring → JSON Schema для LLM planner. Naming — snake_case. Errors — structured payload, не raw stack trace в client-visible channel. Secrets — только на Server layer.

Pydantic input schema
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, возвращает список результатов."""
    ...

Пять reference tools для прокачки skill set:

  • Calculator — eval math expressions (sandbox обязателен, не naked eval)
  • File I/O — read/write в allowlisted directory
  • HTTP proxy — REST calls к external API
  • SQL read-only — parameterized queries, no DDL
  • Datetime — now(), timezone conversion
Async tool (I/O bound)
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)
        response.raise_for_status()
        return response.text

Production checklist: timeout 30s default, RBAC на tool level, rate limiting, audit log каждого tools/call. Credentials никогда не попадают в client config — только Server-side env / secret manager.

05Resources: read-only data plane для модели

Resource vs Tool: Resource — пассивный data provider (read); Tool — action executor (write, compute, side effects). Addressing — URI scheme: file://, http://, custom://.

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 (PDF, images), streaming resources для live feeds. Filesystem server pattern: list directory → read file → optional subscription на file change events для invalidation cache в Host.

06Prompts: переиспользуемые prompt templates

MCP Prompt — parameterized template с injection точками; снижает drift между сессиями и командами. Поддерживает multi-turn shape (user / assistant roles) — code review, interview sim, debug assistant.

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}. Фокус: security, perf, idioms.\n\n{code}"
            )
        )
    ]

07HTTP transport: remote MCP Server

ХарактеристикаstdioHTTP + SSE
Deploy targetLocal child processRemote server / K8s pod
LatencyМинимальная (pipe)Network-bound
Multi-client1:1 process bindingN clients → 1 Server
Use caseDev, single-user IDESaaS, team shared tools
Streamable HTTP mode
mcp = FastMCP("remote-server", transport="streamable-http")

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

Production hardening: Bearer Token auth middleware, API key validation, CORS allowlist, rate limit per tenant. Centralized secret rotation на Server — не scatter keys в mcp.json каждого разработчика.

Reference metric 1: к июню 2026 в каталогах и реестрах — свыше 10 000 MCP Server.

Reference metric 2: enterprise adoption MCP снижает cost tool integration layer на 38–55% (industry survey band).

Reference metric 3: PyPI downloads пакета mcp5M+/month (Q2 2026).

08Отладка и тестирование

MCP Inspector — interactive UI для tools/list, tools/call, JSON-RPC trace. Unit tests — spawn Server subprocess, ClientSession over stdio:

pytest smoke
from mcp.client.session import ClientSession
from mcp.client.stdio import StdioServerParameters, stdio_client

async with stdio_client(StdioServerParameters(
    command="python", args=["server.py"]
)) 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"
СимптомRoot causeFix
Tool не виден в HostНеверный path в configПроверить command/args и working directory
JSON serialization errorNon-serializable return typeCast to str / dict / list
Session timeoutBlocking sync I/O в toolAsync + explicit timeout
Permission deniedPath outside allowlistConfigure sandbox roots

09Production deploy: Docker, cloud, observability

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

Deploy targets: Railway / Render (solo pilot), Cloud Run / Lambda (serverless с cold-start tradeoff), self-hosted VPS + Nginx reverse proxy + TLS termination. Observability: structured JSON logs per RPC method, Prometheus counters на tools/call latency/error rate, Sentry для unhandled exceptions, /health endpoint для load balancer. Versioning: declare MCP protocol version; backward-compatible tool schema evolution — additive fields only.

10Reference project: personal knowledge base MCP Server

Requirements: semantic search по local Markdown notes, create/update notes, expose full document через Resource URI.

Stack: vector store ChromaDB / Qdrant; embeddings text-embedding-3-small; file watcher watchfiles для incremental reindex.

  • index_notes tool — scan directory, chunk, embed, upsert vectors
  • semantic_search tool — query → Top-K chunks с source path
  • write_note tool — create/append Markdown в sandbox dir
  • note://{path} resource — full note body для context injection

Demo flow в Cursor: «Что я писал про MCP на прошлой неделе?» → planner вызывает semantic_search → релевантные chunks попадают в context window → coherent answer с citations.

11Экосистема MCP и вектор 2026

Reference community Servers: mcp-server-filesystem, mcp-server-github, mcp-server-brave-search, mcp-server-postgres, mcp-server-slack.

2026 trajectory: OpenAI, Google, Microsoft — native MCP support; governance в Linux Foundation AAIF; MCP Marketplace acceleration; OAuth 2.1 для enterprise auth — в active roadmap.

Next steps: прочитать protocol spec; опубликовать public Server; compose MCP + Agent orchestration; contribute в Python SDK, TypeScript SDK, Inspector.

12Шестишаговый runbook: MCP Server 7×24 на облачном Mac

  1. 01
    Выбор transport: local dev — stdio; team shared / remote Claude Code — HTTP+SSE с centralized API key на Server layer.
  2. 02
    Провижининг облачного Mac: консоль NUKCLOUD — tier 16 ГБ+ RAM (32 ГБ при parallel MCP child processes); почасовой pilot на странице цен.
  3. 03
    Bootstrap runtime: SSH → pip install mcp httpx pydantic; smoke через MCP Inspector на stdio path.
  4. 04
    HTTP deploy + expose: mcp.run(host="0.0.0.0", port=8000); Bearer middleware, CORS allowlist, firewall rule на 8000/TCP.
  5. 05
    Client integration verify: Cursor .cursor/mcp.json → remote URL; smoke tools/list + tools/call end-to-end.
  6. 06
    launchd residency + capacity lock: ~/Library/LaunchAgents/com.team.mcp-server.plist для 7×24; после validated pilot — страница заказа для monthly tier. Детали провижининга — NUKCLOUD production runbook.

На локальном MacBook и shared VPS типичны sleep kill stdio session, SSE reconnect storm при jitter, port contention на shared host. Для Cursor Background Agents и personal KB Server с persistent HTTP endpoint мультирегиональные bare-metal Mac / облачные Mac NUKCLOUD дают tenant isolation и spec elasticity, aligned с MCP workload — стартуйте почасово, фиксируйте monthly после pilot.

13Частые вопросы

Python или TypeScript для MCP Server?
Старт — Python + FastMCP: минимальный boilerplate, rich ecosystem для data tools. Fullstack teams — TypeScript SDK, единый toolchain с Node infra. Wire layer идентичен; выбор — по stack команды.
Tools vs Resources vs Prompts — как разделить?
Tools — actions (write DB, call API). Resources — read-only context (configs, files). Prompts — reusable templates. Три примитива покрывают полный Agent context extension surface.
stdio или HTTP?
Single-user local IDE — stdio. Team shared, SaaS, multi-client remote — HTTP+SSE. Сравнение — в секции 07.
Чем эта статья отличается от протокольного разбора?
MCP deep dive — архитектура и N×M-аналогия. Эта статья — hands-on tutorial: код, deploy, KB project, runbook.
Какой MCP Server вы строите первым?
Internal API gateway, read-only DB explorer и personal KB — три highest-ROI starter projects. MCP — baseline competency для AI engineer в 2026; protocol literacy открывает reuse across every MCP-capable Host.