Если Claude или Cursor должны query вашу базу, читать локальные файлы или вызывать internal APIs — но Function Calling заставлял переписывать интеграции при каждой смене модели — этот практический гайд ведёт от основ MCP протокола до рабочего Server на SDK июня 2026: окружение и Hello World, Tools, Resources и Prompts, HTTP transport плюс debug и тесты, и production deployment path с проектом knowledge base — дополняет deep dive по MCP протоколу и гайд Agent Skills.
01

Понять MCP до кода: эволюция, архитектура и преимущество над разовыми интеграциями

Model Context Protocol — открытый стандарт, который Anthropic опубликовал в ноябре 2024 для унификации discovery и invocation внешних capabilities AI-клиентов. Суть: один Server, подключение из Claude Desktop, Cursor или любого MCP-клиента — смена LLM без переписывания tool layer.

01

Era Function Calling: каждый LLM vendor — proprietary schemas. GPT, Claude и Gemini требовали отдельные адаптеры.

02

Волна Plugins: ChatGPT Plugins показали demand на live data, но остались OpenAI-specific и closed.

03

Стандарт MCP: Anthropic open-source vendor-neutral protocol; в 2026 OpenAI, Google и Microsoft adopt под Linux Foundation AAIF.

04

Design goal: стандартизировать AI-to-tool communication как HTTP стандартизировал web services — один wire format, runtime discovery, self-describing tools.

architecture
┌────────────────────┐         ┌─────────────────────┐
│   MCP Client       │ ◄─────► │   MCP Server        │
│  (Claude / Cursor) │  JSON   │  (вы строите это)   │
│                    │  -RPC   │                     │
└────────────────────┘         └─────────────────────┘
                                        │
                          ┌─────────────┼─────────────┐
                          ▼             ▼             ▼
                       Tools       Resources      Prompts
                    (действия)    (чтение data)  (шаблоны)
CapabilityРольПример
ToolsФункции, которые AI вызываетПоиск, вычисление, SQL, HTTP call
ResourcesДанные по URIКонфиг, профили, индекс заметок
PromptsReusable prompt templatesCode review, interview, debug assistant

Wire format — JSON-RPC 2.0. Lifecycle: initialize handshake → capability negotiation → request/response loop → graceful shutdown. Два transport modes: stdio (локальный subprocess, zero network deps) и HTTP + SSE (remote, multi-client, team-shared).

ИзмерениеMCPOpenAI Function CallingLangChain Tools
СтандартизацияОткрытый протоколVendor proprietaryFramework-bound
Transportstdio / HTTP+SSEТолько HTTPТолько HTTP
Cross-modelДаНетЧастично
Resources / PromptsNativeНе поддерживаетсяНе поддерживается
Экосистема (2026)10 000+ ServersMature но lockedMature но coupled

MCP — не ещё один wrapper вокруг Function Calling; это protocol layer, позволяющий AI discover, describe и invoke tools at runtime без hard-coded integration per model.

02

Окружение и Hello World: от venv до tool видимого в Cursor

Рабочий MCP Server за десять минут. Python с FastMCP — recommended starting path; TypeScript зеркалит концепции с @modelcontextprotocol/sdk.

ЯзыкSDKЛучше для
Pythonmcp (FastMCP)Backend / AI, fastest Hello World
TypeScript@modelcontextprotocol/sdkFrontend / full-stack на Node
bash
python -m venv .venv
source .venv/bin/activate
pip install mcp

npm init -y
npm install @modelcontextprotocol/sdk

Рекомендуемый layout проекта:

tree
my-mcp-server/
├── server.py
├── tools/
│   ├── calculator.py
│   └── web_search.py
├── resources/
│   └── file_reader.py
├── prompts/
│   └── templates.py
├── tests/
│   └── test_tools.py
└── pyproject.toml
python
from mcp.server.fastmcp import FastMCP

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

@mcp.tool()
def say_hello(name: str) -> str:
    return f"Hello, {name}! This is your first MCP tool."

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

Запуск и проверка через официальный MCP Inspector:

bash
python server.py
npx @modelcontextprotocol/inspector python server.py

Подключение клиентов: launch command в Claude Desktop claude_desktop_config.json или Cursor mcp.json. После restart — tool в списке и test invocation.

Примечание: STDIO Servers работают как subprocess пока client открыт. Absolute paths в config — самая частая причина Hello World failure.

03

Tools, Resources и Prompts: три capability layers вашего Server

Production Server регистрирует Tools для actions, Resources для readable data и Prompts для reusable templates. Function signatures и docstrings — AI-facing documentation без отдельного OpenAPI.

Tool structure: name из function, parameters из type hints, description из docstring. Pydantic models для complex inputs:

python
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description="Search keywords")
    max_results: int = Field(default=5, description="Max results")
    language: str = Field(default="en", description="Result language")

@mcp.tool()
def web_search(input: SearchInput) -> list[dict]:
    ...
Практический toolЧто делаетКлючевой pattern
CalculatorMath expressionsSafe eval или AST; return string
File read/writeLocal filesystem I/OWhitelist allowed directories
HTTP requestExternal APIsAsync с httpx; timeout + status
Database queryRead-only SQLParameterized queries; block DDL
Time / timezoneCurrent time, conversionISO 8601 strings
python
import httpx

@mcp.tool()
async def fetch_url(url: str) -> str:
    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.get(url)
        response.raise_for_status()
        return response.text

Error handling: structured error dicts для recoverable failures; raise только для unrecoverable. Timeouts на I/O tools. Validate permissions перед filesystem или database access.

Resources отличаются от Tools: Resources supply data via URI, Tools execute actions. Static resources — fixed URIs; dynamic — path parameters.

python
@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)
Resource typeMIMEUse case
Texttext/plain, application/jsonConfig, logs, structured data
Binaryimage/*, application/pdfDocuments, screenshots
StreamingEvent streamsLive metrics, file watch

Filesystem resource Server lists directories, reads files, subscribes to change events. Prompts ship pre-built conversation templates с dynamic parameter injection:

python
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"Review this {language} code for bugs, security, and performance:\n```{language}\n{code}\n```"
            )
        )
    ]

Multi-turn Prompts mix user и assistant roles — interview simulations, debug walkthroughs, onboarding flows с consistent structure.

04

HTTP transport, authentication, debugging и automated testing

Local STDIO для dev; team-shared или SaaS deployments нужен HTTP + SSE. FastMCP supports streamable-http с minimal code change.

TraitstdioHTTP + SSE
DeploymentLocal subprocessRemote server
LatencyNear zeroNetwork-dependent
Multi-clientOne client per processMany concurrent clients
Best forPersonal dev toolsTeam / production SaaS
python
mcp = FastMCP("remote-server", transport="streamable-http")

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

Production HTTP Servers нужны auth и guardrails: Bearer Token или API Key middleware, CORS restricted to known origins, rate limiting на tool endpoints с external APIs или databases.

MCP Inspector — primary debug UI: launch against Server command, call Tools interactively, inspect JSON-RPC pairs, simulate error paths перед wiring client.

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

@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"
ErrorCauseFix
Tool not visible in clientWrong config path or commandAbsolute path в mcp.json / claude_desktop_config.json
JSON serialization failureNon-serializable return typeReturn str или dict
Timeout disconnectBlocking I/O in sync toolSwitch to async; explicit timeout
Permission deniedPath outside whitelistConfigure allowed directories
05

Production deployment, knowledge-base project, ecosystem picks и six-step rollout

От Hello World к production: containerization, observability, version negotiation и reference project с real value. Capstone — personal knowledge-base MCP Server: semantic search over local Markdown notes в Cursor.

01

Inventory capabilities: database queries, file I/O, internal APIs, build triggers для Agents. Tag read-only или write.

02

Pick transport: STDIO для local dev; HTTP+SSE когда teammates или CI agents share Server на stable host.

03

Implement и Schema: register tools via official SDKs. JSON Schema для каждого parameter и return shape.

04

Configure clients: Cursor mcp.json или Claude Desktop config на launch command или remote URL. Document env vars.

05

Test discovery и invocation: tools/list returns full catalog. Sample tools/call chains; verify multi-step context.

06

Deploy to production host: Docker container; Railway/Render для quick starts, Cloud Run/Lambda для serverless, или dedicated cloud Mac для Apple toolchain и 24/7. См. цены аренды.

Deployment options: Docker wraps Python deps. Railway и Render — one-click deploys. AWS Lambda и Google Cloud Run для bursty serverless. Self-hosted VPS + Nginx для teams с existing infra. Structured logging, Prometheus metrics на tool calls, Sentry alerts, /health endpoint. Declare MCP protocol version, negotiate capabilities at handshake.

Knowledge-base project: Index local Markdown с ChromaDB или Qdrant, embed с text-embedding-3-small, watch changes via watchfiles. Три Tools — index notes, semantic search, write/update note — плюс Resource listing indexed files. В Cursor: «Что я писал про MCP на прошлой неделе?» — Agent calls search tool.

Community ServerCapability
mcp-server-filesystemDirectory listing, file read/write
mcp-server-githubRepo issues, PRs, code search
mcp-server-brave-searchWeb search via Brave API
mcp-server-postgresParameterized SQL queries
mcp-server-slackChannel messages и posting

В 2026 все major AI clients ship native MCP support. Marketplace directories — thousands of Servers; enterprise adoption drives OAuth 2.0 и security audits. Next steps: spec на modelcontextprotocol.io, publish first Server, combine MCP с Agent Skills.

A

MCP ecosystem scale (2026): Public MCP Server count exceeds 10 000, network effects comparable to early HTTP web growth (sources: openEuler / Jacar aggregates).

B

Integration cost reduction: MCP standardization cuts AI tool integration cost by 38–55 % versus per-vendor adapters (sources: Atlan / WorkOS).

C

Startup barrier drop: Standardized tool interfaces lower AI startup entry by roughly 62 %; traditional integrator work falls about 43 % (sources: industry surveys).

ApproachProduction MCP ServerMain gap
Laptop STDIOFast local devLid close kills process; no 24/7
Generic Linux VPSHTTP+SSE deployableNo Apple toolchain; iOS CI mismatch
Serverless (Lambda/Cloud Run)Low ops для bursty trafficCold start; stateful session limits
KVMNODE cloud Mac + MCPDedicated node, launchd, snapshot rollbackRequires rental planning

Сравните alternatives честно. HTTP+SSE на primary MacBook breaks при lid close и OS updates. Serverless без session affinity drops multi-step Agent context. Exposed MCP endpoints без auth — prompt-injection и unauthorized tool calls; ~1 000 unprotected Servers в 2026 audits. Для teams с Apple Silicon, 24/7 uptime и isolation между MCP Server, iOS CI и Agent Gateway workloads аренда dedicated KVMNODE Mac Mini M4 или M4 Pro — often better answer: flexible daily/weekly/monthly terms, launchd-managed processes, snapshot rollback. Tiers на странице цен, setup в центре помощи, provision через заказ когда MCP stack needs host that stays up after laptop close.