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
| Измерение | MCP | OpenAI Function Calling | LangChain Tools |
|---|---|---|---|
| Стандартизация | Открытая спецификация | Vendor-private | Framework-bound |
| Transport | stdio / HTTP | HTTP only | HTTP (ad hoc) |
| Cross-model | Да | Нет | Частично |
| Resources / Prompts | First-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.
# 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/
├── 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
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()
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.
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
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://.
@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.
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
| Характеристика | stdio | HTTP + SSE |
|---|---|---|
| Deploy target | Local child process | Remote server / K8s pod |
| Latency | Минимальная (pipe) | Network-bound |
| Multi-client | 1:1 process binding | N clients → 1 Server |
| Use case | Dev, single-user IDE | SaaS, team shared tools |
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 пакета mcp — 5M+/month (Q2 2026).
08Отладка и тестирование
MCP Inspector — interactive UI для tools/list, tools/call, JSON-RPC trace. Unit tests — spawn Server subprocess, ClientSession over stdio:
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 cause | Fix |
|---|---|---|
| Tool не виден в Host | Неверный path в config | Проверить command/args и working directory |
| JSON serialization error | Non-serializable return type | Cast to str / dict / list |
| Session timeout | Blocking sync I/O в tool | Async + explicit timeout |
| Permission denied | Path outside allowlist | Configure sandbox roots |
09Production deploy: Docker, cloud, observability
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_notestool — scan directory, chunk, embed, upsert vectorssemantic_searchtool — query → Top-K chunks с source pathwrite_notetool — create/append Markdown в sandbox dirnote://{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
-
01
Выбор transport: local dev — stdio; team shared / remote Claude Code — HTTP+SSE с centralized API key на Server layer.
-
02
Провижининг облачного Mac: консоль NUKCLOUD — tier 16 ГБ+ RAM (32 ГБ при parallel MCP child processes); почасовой pilot на странице цен.
-
03
Bootstrap runtime: SSH →
pip install mcp httpx pydantic; smoke через MCP Inspector на stdio path. -
04
HTTP deploy + expose:
mcp.run(host="0.0.0.0", port=8000); Bearer middleware, CORS allowlist, firewall rule на 8000/TCP. -
05
Client integration verify: Cursor
.cursor/mcp.json→ remote URL; smoketools/list+tools/callend-to-end. -
06
launchdresidency + 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.