Перейти к содержанию

MCP vs Function Calling

~7 минут чтения

URL: PythonAlchemist, Composio, Medium, Anthropic Тип: mcp / function-calling / tool-use / model-context-protocol Дата: Январь-Февраль 2026 Сбор: Ralph Research ФАЗА 5


Предварительно: LLM-агенты

Зачем это нужно

LLM сама по себе не может позвонить в API, прочитать файл или выполнить код -- ей нужен механизм вызова внешних инструментов. Function Calling -- встроенный в каждого провайдера способ: ты описываешь функции в JSON-схеме, модель решает какую вызвать. Проблема: у OpenAI свой формат, у Anthropic свой, у Google свой. MCP (Model Context Protocol) -- открытый стандарт от Anthropic, который унифицирует подключение инструментов. Как USB-C для зарядки: один протокол вместо десяти проприетарных.

Part 1: Overview

Executive Summary

Key Insight:

Function calling is a vendor-specific capability for invoking tools. MCP (Model Context Protocol) is an open standard that provides a universal way to connect AI models to external data sources and tools. MCP is to AI tools what USB-C is to hardware — a universal connector.

2026 Protocol Landscape:

Protocol Type Provider Portability
Function Calling Native OpenAI, Anthropic, Google Vendor-specific
MCP Open Standard Anthropic-initiated Cross-platform
A2A Agent Protocol Google Agent-to-agent

Part 2: Function Calling Fundamentals

How It Works

User Query → LLM → Tool Selection → Tool Execution → LLM → Response
                     ↑                      ↓
              Tool Schema            Tool Result

Function Calling Flow

Step Description
1. Define tools Provide JSON schema for each function
2. LLM decides Model chooses which tool to call
3. Extract params Parse function arguments
4. Execute Run the function locally
5. Return result Feed result back to LLM
6. Generate response LLM incorporates tool output

Example: OpenAI Function Calling

from openai import OpenAI

client = OpenAI()

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            }
        }
    }
]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "What's the weather in SF?"}],
    tools=tools
)

# LLM returns tool call
tool_call = response.choices[0].message.tool_calls[0]
# Execute tool, return result...

Limitations of Function Calling

Limitation Impact
Vendor lock-in Different APIs per provider
No standard Each LLM has different schema
Manual orchestration Developer handles everything
No discovery Tools must be pre-defined

Part 3: MCP (Model Context Protocol)

What is MCP?

Aspect Description
Full name Model Context Protocol
Created by Anthropic (Nov 2024)
Status Open standard
Analogy USB-C for AI tools

MCP Architecture

graph TD
    HOST["MCP Host<br/>Claude Desktop / IDE / Custom App"] -->|MCP Protocol| S1["MCP Server<br/>Files"]
    HOST -->|MCP Protocol| S2["MCP Server<br/>GitHub"]
    HOST -->|MCP Protocol| S3["MCP Server<br/>Custom"]

    style HOST fill:#e8eaf6,stroke:#3f51b5
    style S1 fill:#e8f5e9,stroke:#4caf50
    style S2 fill:#e8f5e9,stroke:#4caf50
    style S3 fill:#e8f5e9,stroke:#4caf50

MCP Components

Component Description
Host Application using MCP (Claude Desktop, IDE)
Client MCP client in the host
Server Provides resources, tools, prompts
Transport stdio, HTTP/SSE

MCP Capabilities

Capability Description
Resources Read files, data from external sources
Tools Execute functions, actions
Prompts Pre-defined prompt templates
Sampling LLM can request completions

MCP Server Example

from mcp.server import Server
from mcp.types import Tool, TextContent

server = Server("example-server")

@server.list_tools()
async def list_tools():
    return [
        Tool(
            name="get_weather",
            description="Get current weather",
            inputSchema={
                "type": "object",
                "properties": {
                    "location": {"type": "string"}
                },
                "required": ["location"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name, arguments):
    if name == "get_weather":
        location = arguments["location"]
        # Fetch weather...
        return [TextContent(type="text", text=f"Weather in {location}")]

MCP Tool Discovery

# MCP provides automatic tool discovery
# No need to manually define all tools upfront

# List available tools from server
tools = await session.list_tools()

# Tools are dynamically discovered
for tool in tools.tools:
    print(f"Tool: {tool.name}")
    print(f"Description: {tool.description}")

Part 4: MCP vs Function Calling Comparison

Architecture Comparison

Aspect Function Calling MCP
Definition Vendor-specific Open standard
Transport In-process stdio/HTTP/SSE
Discovery Manual Automatic
Resources No Yes
Prompts No Yes
Sampling No Yes

Feature Matrix

Feature Function Calling MCP
Tool execution
Resource reading
Prompt templates
Dynamic discovery
Cross-platform
Stateful sessions
Server ecosystem ✅ (growing)

MCP не заменяет function calling

MCP и function calling работают на разных уровнях. Function calling -- механизм вызова инструмента внутри одного LLM-провайдера. MCP -- протокол подключения внешних серверов с инструментами. В production часто используют оба: MCP для внешних интеграций (GitHub, Slack, DB), function calling для внутренней логики приложения.

MCP -- не только для Claude

MCP -- открытый стандарт. Cursor IDE, Zed, Continue.dev, десятки open-source проектов -- все поддерживают MCP. Серверы MCP можно написать на Python, TypeScript, Go, Rust. Протокол не привязан к Anthropic API.

When to Use Each

Scenario Recommendation
Simple, single-provider app Function calling
Multi-provider support MCP
Need resource access MCP
Building tools for others MCP
Quick prototype Function calling
Production ecosystem MCP

Part 5: MCP Ecosystem (2026)

Server Purpose Stars
filesystem File access Built-in
github GitHub API Popular
postgres Database queries Popular
puppeteer Browser automation Growing
slack Slack integration Growing

MCP Hosts

Host Description
Claude Desktop First-party support
Cursor IDE MCP integration
Zed Editor support
Custom apps SDK available

MCP Tool Search (Anthropic)

Feature Description
Problem 30+ tools overwhelm LLM
Solution Tool search / dynamic loading
Benefit Better tool selection

Part 6: Implementation Patterns

Pattern 1: MCP Server for Business Logic

# Custom MCP server for your business
from mcp.server import Server

server = Server("business-tools")

@server.list_tools()
async def list_tools():
    return [
        Tool(name="create_order", ...),
        Tool(name="check_inventory", ...),
        Tool(name="process_payment", ...)
    ]

@server.call_tool()
async def call_tool(name, arguments):
    # Route to business logic
    ...

Pattern 2: Hybrid Approach

# Use MCP for external tools, function calling for internal
# Best of both worlds

# Internal: Direct function calls
internal_tools = get_internal_functions()

# External: MCP servers
external_tools = await mcp_client.list_tools()

all_tools = internal_tools + external_tools

Pattern 3: MCP Gateway

# Single MCP server that proxies to multiple backends
# Unified interface for all tools

class MCPGateway:
    def __init__(self):
        self.backends = {
            "github": GitHubBackend(),
            "slack": SlackBackend(),
            "jira": JiraBackend()
        }

    async def call_tool(self, name, arguments):
        backend = self.route_to_backend(name)
        return await backend.execute(name, arguments)

Part 7: Tool Selection Best Practices

Tool Naming

Good Bad
get_user_by_id getUser
create_order order
search_products find

Tool Descriptions

# Good description
{
    "name": "get_weather",
    "description": "Get current weather conditions for a location. Returns temperature, humidity, and conditions.",
    "parameters": {...}
}

# Bad description
{
    "name": "get_weather",
    "description": "Weather",
    "parameters": {...}
}

Parameter Design

Principle Example
Required params only location required, units optional
Clear types {"type": "string"} not {"type": "any"}
Enums for limited options {"enum": ["celsius", "fahrenheit"]}
Descriptions Each param has description

Part 8: Production Considerations

Error Handling

Error Type Handling
Tool not found Graceful fallback
Invalid params Clear error message
Timeout Retry with backoff
Rate limit Queue or throttle

Security

Concern Mitigation
Injection Validate all inputs
Data exfil Limit tool scope
Privilege escalation Least privilege
Audit Log all tool calls

Performance

Metric Target
Tool discovery <100ms
Tool execution Depends on tool
MCP overhead <10ms
Total latency <500ms for simple tools

Part 9: Interview-Relevant Numbers

MCP vs Function Calling Summary

Metric Function Calling MCP
Portability Single provider Cross-platform
Setup time Minutes Hours (server)
Ecosystem Vendor-specific Growing (100+ servers)
Overhead None Small (protocol)
Best for Quick integrations Production systems

Tool Execution Metrics

Operation Latency
Tool definition <1ms
LLM tool selection 100-500ms
Tool execution Varies
Result parsing <10ms

MCP Ecosystem Stats (2026)

Statistic Value
MCP servers 100+
Built-in servers 5+
Languages supported Python, TS, Go, Rust
Claude Desktop support Native

Interview Questions

1. Когда использовать MCP, а когда function calling?

❌ Red flag: "MCP всегда лучше, function calling устарел"

✅ Strong answer: "Function calling -- когда один провайдер, простая интеграция, быстрый прототип. Нет overhead протокола, всё in-process. MCP -- когда нужна кросс-платформенность (менять провайдера без переписывания tools), динамическое обнаружение инструментов, доступ к ресурсам (не только вызовы функций). В production часто hybrid: MCP для внешних интеграций (DB, GitHub, Slack), function calling для внутренней бизнес-логики."

2. Какие компоненты есть у MCP и чем они отличаются от function calling?

❌ Red flag: "MCP -- это просто стандартизированный function calling"

✅ Strong answer: "MCP дает 4 capability поверх tool calling: (1) Tools -- аналог function calling, но стандартизированный. (2) Resources -- чтение данных из внешних источников (файлы, БД, API). Function calling не имеет аналога. (3) Prompts -- предопределённые шаблоны промптов от сервера. (4) Sampling -- сервер может запрашивать у модели завершения. Архитектура: Host (приложение) → Client (протокол) → Server (инструменты). Transport: stdio для локальных, HTTP/SSE для удалённых."

3. Как MCP решает проблему tool overload?

❌ Red flag: "Просто передать все tools в промпт"

✅ Strong answer: "При 30+ инструментах LLM теряет качество выбора -- слишком много опций. MCP решает через dynamic tool discovery: вместо передачи всех инструментов, host делает list_tools() у каждого сервера и передаёт только релевантные. Можно реализовать tool search -- двухэтапный процесс: сначала поиск подходящего инструмента, потом его вызов. Claude Code использует ToolSearch с lazy loading -- инструменты загружаются по запросу, а не все сразу."


Sources

  1. PythonAlchemist — "MCP Protocol Guide (2026)"
  2. Composio — "Tool Calling Explained: The Core of AI Agents (2026 Guide)"
  3. Medium — "Function calling & MCP for LLMs"
  4. Anthropic — MCP Documentation
  5. PocketFlow Substack — "MCP Simply Explained"
  6. Reddit — "MCP vs Function Calling Discussion"

See Also