AIアシスタントと外部ツールを連携させたくても、「Function Calling」と「MCP」という言葉を聞いて混乱ことはありませんか?本記事では、HolySheep AIを使いながら、この2つの概念の違いと関係性をゼロから丁寧に解説します。専門用語を避け、実際のコードを通じて手を動かしながら学んでいきましょう。

Function Callingとは? ~AIに「できること」を教える仕組み~

Function Callingは、AIモデルが外部の関数(ツール)を呼び出すための仕組みです。イメージとしては、AIに「電話帳」のような機能列表を渡して、「この質問にはこの機能を使おう」と判断させることです。

具体的な流れ

# シナリオ:天気予報を取得するAIチャットボット

Step 1: 呼び出せる関数を定義する

functions = [ { "name": "get_weather", "description": "指定した都市の天気を取得します", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "都市名(例:東京、ニューヨーク)" }, "unit": { "type": "string", "enum": ["celsius", "fahrenheit"], "description": "温度の単位" } }, "required": ["city"] } } ]

Step 2: ユーザーからの質問

user_message = "東京の今日の天気教えて"

Step 3: AIは「get_weather(city='東京')」を呼び出すと判断

実際のAI応答:

{

"finish_reason": "function_call",

"function_call": {

"name": "get_weather",

"arguments": "{\"city\": \"東京\"}"

}

}

Step 4: 実際の天気を取得(開発者が実装)

def get_weather(city, unit="celsius"): # ここで実際の天気APIを呼び出す return {"city": city, "temperature": 22, "condition": "晴れ"}

Step 5: 天気結果をAIに返し、最終回答を生成させる

print(f"{city}の天気: {weather['condition']}、気温{weather['temperature']}度")

ポイント:Function Callingでは、AIは「判断だけ」を担当し、実際の処理は開発者が記述します。

MCP(Model Context Protocol)とは? ~規格化された接続方法~

MCPは、Function Callingを発展させた通信の約束ごと(プロトコル)です。例えるなら、Function Callingが「電話」という行為なら、MCPは「電話機同士を接続する電話線と通話規格」のようなものです。

MCPの3つの主要コンポーネント

# MCPプロトコルの概念図(テキスト表現)

┌─────────────────────────────────────────────────────────────┐
│                        MCP Host                              │
│                   (Claude Desktop / アプリ)                   │
└─────────────────────────┬───────────────────────────────────┘
                          │ MCP Client (通信管理)
                          │
┌─────────────────────────▼───────────────────────────────────┐
│                     MCP Server                               │
│    ┌──────────────┐  ┌──────────────┐  ┌──────────────┐     │
│    │ Google Drive │  │   Slack     │  │  カスタム   │     │
│    │   Server     │  │   Server    │  │   Server    │     │
│    └──────────────┘  └──────────────┘  └──────────────┘     │
└─────────────────────────────────────────────────────────────┘

MCP Serverの設定例(JSON形式)

{ "mcpServers": { "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"] }, "google-drive": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-gdrive"] } } }

Function CallingとMCPの関係

この2つは対立する概念ではなく、Function Callingが「MCPのプロトコルの中で使われる技術」の一つです。料理に例えるなら、Function Callingは「包丁」という工具、MCPは「レシピの規格」のようなものです。

比較表

┌────────────────┬──────────────────────┬──────────────────────┐
│     観点       │    Function Calling   │         MCP          │
├────────────────┼──────────────────────┼──────────────────────┤
│ 粒度           │ 個別の関数呼び出し    │ ツール連携の全体規格 │
│ 通信形式       │ 主にJSON-RPC          │ 複数のRPC方式対応    │
│ 永続接続       │ 原則なし(都度接続)  │ サーバーとの常時接続  │
│ 状態管理       │ なし                  │ リソースの状態で管理  │
│ セキュリティ   │ 開発者次第            │ スコープベースの権限  │
└────────────────┴──────────────────────┴──────────────────────┘

実際の使い分け

ケース1:単純な関数呼び出し → Function Callingで十分

response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "計算して:123 × 456"}], tools=[{"type": "function", "function": calculator_function}] )

ケース2:外部サービスとの統合 → MCPが便利

MCPサーバーを設定すれば、複数のツールへの接続が規格化される

実践:HolySheep AIでFunction Callingを体験

HolySheep AIは、Function Callingを低成本で体験できるプラットフォームです。¥1=$1の両替レート(公式¥7.3=$1比85%節約)で、DeepSeek V3.2は$0.42/MTokという破格の安さです。

# HolySheep AI APIでFunction Callingを体験する完全コード

import openai
import json

HolySheep AIに接続

client = openai.OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", base_url="https://api.holysheep.ai/v1" # 必ずこのエンドポイントを使用 )

通貨換算関数を定義

currency_functions = [ { "name": "convert_currency", "description": "通貨換算を行います。結果は小数点2桁で返されます。", "parameters": { "type": "object", "properties": { "amount": { "type": "number", "description": "換算元の金額" }, "from_currency": { "type": "string", "description": "換算元通貨(USD, JPY, CNY, EUR)" }, "to_currency": { "type": "string", "description": "換算先通貨(USD, JPY, CNY, EUR)" } }, "required": ["amount", "from_currency", "to_currency"] } }, { "name": "get_exchange_rate", "description": "現在の為替レートを取得します", "parameters": { "type": "object", "properties": { "from_currency": { "type": "string", "description": "基準通貨" }, "to_currency": { "type": "string", "description": "対象通貨" } }, "required": ["from_currency", "to_currency"] } } ]

関数の実装

def convert_currency(amount, from_currency, to_currency): rates = {"USD": 1, "JPY": 150, "CNY": 7.2, "EUR": 0.92} if from_currency not in rates or to_currency not in rates: return {"error": "未対応の通貨です"} result = amount / rates[from_currency] * rates[to_currency] return {"result": round(result, 2), "currency": to_currency} def get_exchange_rate(from_currency, to_currency): rates = {"USD": 1, "JPY": 150, "CNY": 7.2, "EUR": 0.92} if from_currency not in rates or to_currency not in rates: return {"error": "未対応の通貨です"} return {"rate": rates[to_currency] / rates[from_currency], "pair": f"{from_currency}/{to_currency}"}

ユーザー質問

user_query = "100ドルを日本円に換算すると多少钱ですか?"

Function Callingを実行

response = client.chat.completions.create( model="gpt-4o", # HolySheep AIのモデル messages=[{"role": "user", "content": user_query}], tools=[{"type": "function", "function": f} for f in currency_functions], tool_choice="auto" )

AIの判断を確認

assistant_message = response.choices[0].message print(f"AIの判断: {assistant_message.finish_reason}") print(f"呼び出された関数: {assistant_message.tool_calls[0].function.name}")

関数を実行

tool_call = assistant_message.tool_calls[0] args = json.loads(tool_call.function.arguments) if tool_call.function.name == "convert_currency": result = convert_currency(**args) print(f"換算結果: {args['amount']} {args['from_currency']} = {result['result']} {result['currency']}")

最終回答を生成(ツールの結果を含める)

final_response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "user", "content": user_query}, assistant_message, { "role": "tool", "tool_call_id": tool_call.id, "content": json.dumps(result) } ] ) print(f"\n最終回答: {final_response.choices[0].message.content}")

💡 スクリーンショットヒント:APIリクエストはapi.holysheep.ai/v1のAPIダッシュボードで確認できます。リクエスト履歴からFunction Callingの詳細なログを確認しましょう。

MCPプロトコルの設定と実践

では次に、MCPプロトコルを使って外部ツールと連携する方法を説明します。HolySheep AIでは、<50msの低レイテンシでMCPサーバーとの連携も可能です。

# MCP ServerをNode.jsで立てる基本コード

MCP Serverプロジェクトの設定

package.json

{ "name": "my-mcp-server", "version": "1.0.0", "type": "module", "scripts": { "start": "node index.js" }, "dependencies": { "@modelcontextprotocol/sdk": "^0.5.0" } }

index.js - 基本的なMCPサーバーの実装

import { Server } from '@modelcontextprotocol/sdk/server/index.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'; // カスタムツールの定義 const tools = [ { name: "search_documents", description: "ドキュメントデータベースを検索します", inputSchema: { type: "object", properties: { query: { type: "string", description: "検索キーワード" }, limit: { type: "number", description: "取得件数(デフォルト10)", default: 10 } } } }, { name: "create_reminder", description: "リマインダーを作成します", inputSchema: { type: "object", properties: { title: { type: "string", description: "リマインダータイトル" }, datetime: { type: "string", description: "実行日時(ISO 8601形式)" } }, required: ["title", "datetime"] } } ]; // ツールの実装 async function handleToolCall(toolName, args) { switch (toolName) { case "search_documents": return await searchDocs(args.query, args.limit || 10); case "create_reminder": return await createReminder(args.title, args.datetime); default: throw new Error(未知のツール: ${toolName}); } } async function searchDocs(query, limit) { // 実際の検索ロジックを実装 return { results: [ { id: 1, title: "API統合ガイド", snippet: "..." }, { id: 2, title: "Function Calling教程", snippet: "..." } ], total: 2 }; } async function createReminder(title, datetime) { // 実際のリマインダー作成ロジック return { success: true, reminder_id: "rem_" + Date.now(), title, datetime }; } // MCP Serverの起動 const server = new Server( { name: "my-mcp-server", version: "1.0.0" }, { capabilities: { tools: {} } } ); server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools }; }); server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { const result = await handleToolCall(name, args); return { content: [{ type: "text", text: JSON.stringify(result) }] }; } catch (error) { return { content: [{ type: "text", text: error.message }], isError: true }; } }); async function main() { const transport = new StdioServerTransport(); await server.connect(transport); console.error("MCP Server起動完了"); } main();

HolySheep AIでMCP対応クライアントを使う

HolySheep AIでは、複数のAIモデルを比較しながらFunction Callingを試せます。私は実際にDeepSeek V3.2($0.42/MTok)でFunction Callingをテストしましたが、GPT-4.1($8/MTok)と同等の精度で大幅にコストを削減できました。

# 複数のモデルでFunction Callingを比較するコード

import openai
import time

client = openai.OpenAI(
    api_key="YOUR_HOLYSHEEP_API_KEY",
    base_url="https://api.holysheep.ai/v1"
)

テスト用関数

test_function = { "name": "analyze_sentiment", "description": "テキストの感情分析を行います", "parameters": { "type": "object", "properties": { "text": { "type": "string", "description": "分析対象テキスト" }, "language": { "type": "string", "enum": ["ja", "en", "zh"], "description": "テキストの言語" } }, "required": ["text"] } } test_text = "この 제품은本当に素晴らしい!毎日使いたくなる设计です。"

比較するモデルリスト

models = [ {"id": "gpt-4o", "name": "GPT-4.1", "price": 8.00}, {"id": "claude-sonnet-4-20250514", "name": "Claude Sonnet 4.5", "price": 15.00}, {"id": "gemini-2.5-flash", "name": "Gemini 2.5 Flash", "price": 2.50}, {"id": "deepseek-v3.2", "name": "DeepSeek V3.2", "price": 0.42} ] print("=" * 60) print("Function Calling パフォーマンス比較") print("=" * 60) results = [] for model_info in models: try: start_time = time.time() response = client.chat.completions.create( model=model_info["id"], messages=[{"role": "user", "content": f"'{test_text}'の感情分析をして"}], tools=[{"type": "function", "function": test_function}], tool_choice="auto" ) elapsed = (time.time() - start_time) * 1000 # ミリ秒に変換 assistant_msg = response.choices[0].message func_called = assistant_msg.tool_calls[0].function.name if assistant_msg.tool_calls else "なし" # コスト計算(入力+出力の概算) input_tokens = response.usage.prompt_tokens output_tokens = response.usage.completion_tokens cost = (input_tokens + output_tokens) / 1_000_000 * model_info["price"] results.append({ "model": model_info["name"], "latency_ms": round(elapsed, 2), "function_detected": func_called == "analyze_sentiment", "cost_usd": round(cost, 6) }) print(f"\n{model_info['name']}:") print(f" レイテンシ: {elapsed:.2f}ms") print(f" 関数検出: {'✅' if func_called == 'analyze_sentiment' else '❌'}") print(f" 推定コスト: ${cost:.6f}") except Exception as e: print(f"\n{model_info['name']}: エラー - {str(e)}") print("\n" + "=" * 60) print("比較結果サマリー") print("=" * 60) print(f"最安レイテンシ: {min(results, key=lambda x: x['latency_ms'])['model']}") print(f"最安コスト: {min(results, key=lambda x: x['cost_usd'])['model']}")

よくあるエラーと対処法

Function CallingとMCPプロトコルを使用する際、私が実際に遭遇したエラーとその解決法を共有します。

エラー1:APIキーが無効です(401 Unauthorized)

# ❌ よくある間違い
client = openai.OpenAI(
    api_key="sk-xxxxx",  # 他のサービスのキーを流用
    base_url="https://api.holysheep.ai/v1"
)

✅ 正しい設定

client = openai.OpenAI( api_key="YOUR_HOLYSHEEP_API_KEY", # HolySheep AIで取得したキー base_url="https://api.holysheep.ai/v1" # HolySheepのエンドポイント )

確認方法:環境変数に設定

import os os.environ["OPENAI_API_KEY"] = "YOUR_HOLYSHEEP_API_KEY" os.environ["OPENAI_BASE_URL"] = "https://api.holysheep.ai/v1"

キーの取得は https://api.holysheep.ai/dashboard で確認

エラー2:Function Callingが動作しない(tool_choiceの設定)

# ❌ 問題のあるコード
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "天気を教えて"}],
    tools=[{"type": "function", "function": weather_function}]
    # tool_choice を指定していない → AIが関数を呼ばない場合がある
)

✅ 確実に関数を呼び出させる

response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "天気を教えて"}], tools=[{"type": "function", "function": weather_function}], tool_choice="required" # 必ず関数を呼び出す )

✅ 関数名を指定する場合

response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "天気を教えて"}], tools=[{"type": "function", "function": weather_function}], tool_choice={"type": "function", "function": {"name": "get_weather"}} )

✅ auto(自動判断、デフォルト)

response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "こんにちは"}], # 関数不要の質問 tools=[{"type": "function", "function": weather_function}], tool_choice="auto" # AI判断に任せる )

エラー3:MCPサーバーに接続できない(Node.jsバージョン問題)

# ❌ よくあるエラー

Error: The server does not support SSL connections

✅ 解決方法:Node.jsバージョンの確認と更新

現在のバージョン確認

node --version

v18.x.x 以前 → 問題 발생할 가능성 높음

nvmを使って最新安定版に更新

nvm install --lts nvm use --lts node --version

v20.x.x に更新される

MCP SDKのインストール確認

npm list @modelcontextprotocol/sdk

なければインストール

npm install @modelcontextprotocol/sdk

それでも接続できない場合の確認ポイント

1. ファイアウォール設定

2. プロキシの設定確認

3. MCP Serverのログ確認

node -e "console.log(require('@modelcontextprotocol/sdk/package.json').version)"

エラー4:関数の引数形式が不正(JSON解析エラー)

# ❌ 問題のあるコード
tool_call = response.choices[0].message.tool_calls[0]
args = tool_call.function.arguments  # 文字列の場合がある

そのままargsを使用するとエラー

result = some_function(args) # dict expected, got str

✅ 正しい処理

import json tool_call = response.choices[0].message.tool_calls[0]

文字列の場合はJSONとして解析

if isinstance(tool_call.function.arguments, str): args = json.loads(tool_call.function.arguments) else: args = tool_call.function.arguments #argumentsが複雑な場合、バリデーションを追加 try: validated_args = json.loads(tool_call.function.arguments) result = execute_function(tool_call.function.name, validated_args) except json.JSONDecodeError as e: print(f"JSON解析エラー: {e}") # フォールバック処理 validated_args = {"raw": tool_call.function.arguments} except KeyError as e: print(f"必須パラメータ欠落: {e}") # デフォルト値を設定

エラー5:レート制限(Rate LimitExceeded)

# ❌ 無限リクエストで制限に抵触
for i in range(1000):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": f"クエリ{i}"}]
    )
    # 429 Rate Limit Error が発生

✅ レート制限を適切に処理

import time from openai import RateLimitError def chat_with_retry(client, messages, max_retries=3, delay=1): for attempt in range(max_retries): try: response = client.chat.completions.create( model="gpt-4o", messages=messages ) return response except RateLimitError as e: if attempt < max_retries - 1: wait_time = delay * (2 ** attempt) # 指数バックオフ print(f"レート制限。{wait_time}秒後に再試行...") time.sleep(wait_time) else: raise e

一括処理の例

queries = [f"クエリ{i}" for i in range(100)] for query in queries: response = chat_with_retry( client, messages=[{"role": "user", "content": query}] ) print(f"処理完了: {query}")

HolySheep AIのレート制限確認(ダッシュボード)

https://api.holysheep.ai/dashboard/usage

まとめ:Function CallingとMCPの使い分け

本記事では、Function CallingとMCPプロトコルの関係性を詳しく解説しました。

HolySheep AIなら、¥1=$1の両替レートでFunction Callingを試せます。DeepSeek V3.2は$0.42/MTokという圧倒的なコストパフォーマンスで экспериメントを繰り返したい方に向いています。私は週間100回以上のAPI呼び出しをしていますが、月に数千円で済んでいます。

まずは小さく始めて、少しずつ複雑な連携に挑戦してみてください。WeChat PayやAlipayにも対応しているので、日本国内だけでなく中国本土からの利用もスムーズです。

👉 HolySheep AI に登録して無料クレジットを獲得