Примеры кода
25+ готовых примеров для разных задач
Запустите первый MCP сервер за 5 минут — пошаговое руководство для начинающих
Это руководство поможет вам создать и запустить первый MCP сервер за 5 минут. Выберите ваш язык программирования и следуйте инструкциям.
Простой MCP сервер с двумя инструментами:
add — сложение двух чиселgreet — приветствие по имениСоздайте папку проекта
mkdir my-mcp-server && cd my-mcp-serverУстановите зависимости
pip install mcpСоздайте файл server.py
from mcp.server.fastmcp import FastMCP
# Создаём серверmcp = FastMCP("my-first-server")
@mcp.tool()def add(a: int, b: int) -> int: """Сложить два числа""" return a + b
@mcp.tool()def greet(name: str) -> str: """Поприветствовать по имени""" return f"Привет, {name}!"
@mcp.resource("info://about")def get_about() -> str: """Информация о сервере""" return "Мой первый MCP сервер!"
if __name__ == "__main__": mcp.run(transport="stdio")Запустите сервер
python server.pyПротестируйте с MCP Inspector
npx @modelcontextprotocol/inspector python server.pyОткройте http://localhost:6274 в браузере.
Создайте папку проекта
mkdir my-mcp-server && cd my-mcp-servernpm init -yУстановите зависимости
npm install @modelcontextprotocol/sdknpm install -D typescript ts-node @types/nodeСоздайте файл server.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import { ListToolsRequestSchema, CallToolRequestSchema,} from "@modelcontextprotocol/sdk/types.js";
const server = new McpServer({ name: "my-first-server", version: "1.0.0",});
// Регистрируем инструментыserver.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [ { name: "add", description: "Сложить два числа", inputSchema: { type: "object" as const, properties: { a: { type: "number", description: "Первое число" }, b: { type: "number", description: "Второе число" }, }, required: ["a", "b"], }, }, { name: "greet", description: "Поприветствовать по имени", inputSchema: { type: "object" as const, properties: { name: { type: "string", description: "Имя" }, }, required: ["name"], }, }, ],}));
// Обрабатываем вызовыserver.setRequestHandler(CallToolRequestSchema, async (request) => { switch (request.params.name) { case "add": { const a = request.params.arguments?.a as number; const b = request.params.arguments?.b as number; return { content: [{ type: "text", text: String(a + b) }] }; } case "greet": { const name = request.params.arguments?.name as string; return { content: [{ type: "text", text: `Привет, ${name}!` }] }; } default: throw new Error(`Unknown tool: ${request.params.name}`); }});
// Запускаем серверconst transport = new StdioServerTransport();await server.connect(transport);Добавьте скрипт в package.json
{ "type": "module", "scripts": { "start": "ts-node server.ts" }}Запустите и протестируйте
npx @modelcontextprotocol/inspector npm startСоздайте проект
mkdir my-mcp-server && cd my-mcp-servergo mod init my-mcp-servergo get github.com/mark3labs/mcp-goСоздайте файл main.go
package main
import ( "context" "fmt"
"github.com/mark3labs/mcp-go/mcp" "github.com/mark3labs/mcp-go/server")
func main() { s := server.NewMCPServer( "my-first-server", "1.0.0", )
// Инструмент сложения addTool := mcp.NewTool("add", mcp.WithDescription("Сложить два числа"), mcp.WithNumber("a", mcp.Required(), mcp.Description("Первое число")), mcp.WithNumber("b", mcp.Required(), mcp.Description("Второе число")), )
s.AddTool(addTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { a := req.Params.Arguments["a"].(float64) b := req.Params.Arguments["b"].(float64) return mcp.NewToolResultText(fmt.Sprintf("%.0f", a+b)), nil })
// Инструмент приветствия greetTool := mcp.NewTool("greet", mcp.WithDescription("Поприветствовать по имени"), mcp.WithString("name", mcp.Required(), mcp.Description("Имя")), )
s.AddTool(greetTool, func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) { name := req.Params.Arguments["name"].(string) return mcp.NewToolResultText(fmt.Sprintf("Привет, %s!", name)), nil })
// Запуск if err := server.ServeStdio(s); err != nil { panic(err) }}Запустите
go run main.goПротестируйте
npx @modelcontextprotocol/inspector go run main.goПосле запуска MCP Inspector:
adda = 5, b = 38Примеры кода
25+ готовых примеров для разных задач
Инструменты
MCP Inspector и CLI — полное руководство
Настройка клиентов
Production Checklist
14 пунктов перед деплоем
stdio транспорт?Stdio (standard input/output) — способ коммуникации через stdin/stdout. Клиент запускает ваш сервер как subprocess и общается через потоки ввода/вывода. Это самый простой и надёжный способ для локальной разработки.
npx перед командой?npx @modelcontextprotocol/inspector запускает MCP Inspector без установки. Inspector — это веб-интерфейс для тестирования вашего сервера.
В Python (FastMCP):
@mcp.tool()def my_tool(param1: str, param2: int = 10) -> str: """Описание инструмента (будет видно в Claude)""" return f"Результат: {param1}, {param2}"Описание в docstring автоматически становится description инструмента.
См. раздел Настройка клиентов — там пошаговые инструкции для всех платформ.