Skip to content

Как построить AI Agent с MCP

Коротко:

MCP (Model Context Protocol) от Anthropic — standard для exposing tools к LLM agents. Server implements tools → Client (Claude Desktop, Zed, custom) connects → LLM invokes tools через structured calls. Simpler чем custom function calling. Implementations: Python @modelcontextprotocol/sdk, TypeScript, Go. Use cases: file system access, GitHub operations, database query, custom APIs.

Ниже: пошаговая инструкция, рабочие примеры, типичные ошибки, FAQ.

Попробовать бесплатно →

Пошаговая настройка

  1. Install MCP SDK: pip install mcp или npm install @modelcontextprotocol/sdk
  2. Define tools: name, description, input schema (JSON Schema)
  3. Implement handler: для каждого tool функция, возвращающая result
  4. Start MCP server: stdio transport (для local) или SSE (для remote)
  5. Connect client: Claude Desktop config, Zed settings, или custom agent
  6. Test: LLM автоматически разрешит available tools
  7. Deploy: self-host server или публикуйте как open-source

Рабочие примеры

СценарийКонфиг
Python MCP serverfrom mcp.server.fastmcp import FastMCP mcp = FastMCP('Enterno MCP') @mcp.tool() def check_dns(domain: str) -> dict: """Check DNS records for a domain.""" return {'a': resolve_a(domain), 'mx': resolve_mx(domain)} if __name__ == '__main__': mcp.run()
Claude Desktop config# ~/Library/Application Support/Claude/claude_desktop_config.json { "mcpServers": { "enterno": { "command": "python", "args": ["/path/to/enterno_mcp.py"] } } }
TypeScript MCP serverimport { Server } from '@modelcontextprotocol/sdk/server/index.js'; const server = new Server({ name: 'my-mcp', version: '1.0.0' }, { capabilities: { tools: {} } }); server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{ name: 'echo', description: 'Echo', inputSchema: { type: 'object', properties: { text: { type: 'string' } } } }] })); server.setRequestHandler(CallToolRequestSchema, async (req) => ({ content: [{ type: 'text', text: req.params.arguments.text }] }));
Claude Agent SDK (Python)from anthropic import Anthropic client = Anthropic() # Claude Opus 4.7 with MCP tools support response = client.messages.create( model='claude-opus-4-7', mcp_servers=[{'url': 'stdio://path/to/mcp.py'}], messages=[{'role':'user','content':'Check DNS for google.com'}] )
MCP over HTTP (remote)# Start SSE-based MCP server mcp = FastMCP('Enterno Remote', host='0.0.0.0', port=8000) # Connect client via https://mcp.example.com/sse

Типичные ошибки

  • Tool descriptions vague — LLM не знает когда вызвать. Пишите precise: "Get weather for a specific city, returns JSON"
  • Input schema пропустил required fields — LLM пропустит args. JSON Schema required обязателен
  • No error handling — LLM получает exception string, confused. Return structured error: {error: "msg"}
  • Long-running tools (>10s) — LLM timeout. Async с progress updates
  • Not sandboxing — MCP server с shell access = RCE если prompt injection

Больше по теме

Часто задаваемые вопросы

MCP vs OpenAI function calling?

MCP: standard, works с multiple clients (Claude, Zed, others). OpenAI functions: specific к OpenAI API. MCP — более универсально.

MCP servers market 2026?

Официальная коллекция: filesystem, git, GitHub, Slack, Postgres, Google Drive. Community — десятки больше (Figma, Linear, Sentry).

Security?

Claude Desktop prompts user перед каждым tool call. Для automated agents — нужен manual review пайп, sandbox, whitelist tools.

Deploy MCP remotely?

SSE transport над HTTPS. Auth через OAuth. Пример — Sentry MCP server (opens at https://mcp.sentry.dev).