Chào bạn! Nếu bạn đang bắt đầu hành trình tìm hiểu về lập trình AI — đặc biệt là cách giúp chatbot hoặc ứng dụng trí tuệ nhân tạo thực hiện các tác vụ thực tế như tra cứu thời tiết, quản lý database, hay kết nối với các dịch vụ bên ngoài — thì bài viết này dành cho bạn hoàn toàn. Tôi đã dành hơn 3 năm làm việc với các hệ thống AI và trong quá trình đó, tôi đã thử nghiệm gần như tất cả các phương pháp tích hợp. Bài viết này sẽ giúp bạn hiểu rõ MCP (Model Context Protocol) và Function Calling là gì, chúng khác nhau ra sao, và quan trọng nhất — nên chọn cái nào cho phù hợp với dự án của mình.
Gợi ý ảnh chụp màn hình: Sơ đồ kiến trúc tổng quan so sánh MCP và Function Calling
MCP và Function Calling Là Gì? Giải Thích Đơn Giản Cho Người Mới
Function Calling — "Cầu nối" Trực Tiếp
Trước tiên, hãy nghĩ về Function Calling như một "người phiên dịch" giữa AI và máy tính của bạn. Khi bạn hỏi chatbot một câu hỏi cần thông tin thực tế (ví dụ: "Hà Nội hôm nay mưa không?"), Function Calling giúp AI "gọi điện" cho một đoạn code cụ thể để lấy dữ liệu đó.
Gợi ý ảnh chụp màn hình: Minh họa luồng hoạt động của Function Calling từ user input đến API response
MCP — "Đường Cao Tốc" Chuẩn Hóa
Còn MCP (Model Context Protocol) giống như việc bạn xây một hệ thống đường cao tốc có trạm thu phí tiêu chuẩn. Thay vì mỗi lần AI muốn giao tiếp với một dịch vụ lại phải thiết lập kết nối riêng, MCP tạo ra một giao thức chung để mọi thứ kết nối với nhau dễ dàng hơn. Đây là công nghệ được phát triển bởi Anthropic và đang ngày càng phổ biến.
Gợi ý ảnh chụp màn hình: Kiến trúc MCP server-client với các tool được đăng ký
So Sánh Chi Tiết: MCP vs Function Calling
| Tiêu chí | Function Calling | MCP |
|---|---|---|
| Kiến trúc | Tích hợp trực tiếp vào API của model | Layer trung gian (proxy/bridge) |
| Độ phức tạp setup | Thấp — chỉ cần định nghĩa JSON schema | Trung bình — cần thiết lập MCP server |
| Quản lý tools | Phải code thủ công cho mỗi function | Tự động discover và quản lý tools |
| Multi-source data | Khó khăn khi cần nhiều nguồn | Hỗ trợ tốt, mở rộng dễ dàng |
| State management | Ứng dụng tự quản lý | Có cơ chế context riêng |
| Security | Tùy vào cách implement | Có chuẩn bảo mật riêng |
| Hỗ trợ model | OpenAI, Anthropic, Google, v.v. | Đang mở rộng, chủ yếu Claude |
| Chi phí | Phụ thuộc vào provider | Chi phí infrastructure thêm |
Phù Hợp / Không Phù Hợp Với Ai
✅ Khi Nào Nên Chọn Function Calling?
- Dự án nhỏ, MVP: Khi bạn cần prototype nhanh và không có thời gian setup hạ tầng phức tạp
- Team thiên về backend: Nếu đội của bạn quen làm việc với REST API và JSON
- Chỉ cần 1-5 functions đơn giản: Không cần quản lý nhiều tool phức tạp
- Đã có codebase ổn định: Không muốn refactor toàn bộ hệ thống
- Ngân sách hạn chế: Không muốn đầu tư thêm infrastructure
❌ Khi Nào Nên Tránh Function Calling?
- Hệ thống enterprise lớn: Cần quản lý hàng chục tools và nhiều team
- Data sources đa dạng: Cần kết nối database, file system, API bên thứ 3 cùng lúc
- Yêu cầu sandboxing bảo mật cao: Cần kiểm soát chặt chẽ quyền truy cập
- Dự án cần scale nhanh: Sẽ tốn công refactor sau này
✅ Khi Nào Nên Chọn MCP?
- AI agents phức tạp: Cần nhiều tool hoạt động cùng nhau
- Multi-database/data warehouse: Truy vấn nhiều nguồn dữ liệu khác nhau
- Team lớn, nhiều developers: Cần chuẩn hóa cách tích hợp
- Long-running AI workflows: Cần maintain state giữa các bước
- Đang xây dựng ecosystem: Muốn bên thứ ba dễ dàng tích hợp
❌ Khi Nào Nên Tránh MCP?
- Dự án cá nhân đơn giản: Overkill, thêm độ phức tạp không cần thiết
- Không có DevOps support: Cần người vận hành infrastructure
- Deadline sát: Thời gian setup MCP đáng kể
- Chỉ dùng một model cố định: Không tận dụng được lợi ích cross-platform
Triển Khai Thực Tế: Code Mẫu Chi Tiết
Dưới đây là phần quan trọng nhất — tôi sẽ hướng dẫn bạn implement cả hai phương pháp từ đầu. Tất cả code sử dụng HolySheep AI với chi phí tiết kiệm đến 85% so với các provider lớn.
Ví Dụ 1: Function Calling Với HolySheep AI
Đầu tiên, chúng ta sẽ tạo một ứng dụng đơn giản cho phép người dùng hỏi về thời tiết và chuyển đổi đơn vị tiền tệ:
// File: weather_currency_functions.py
// Hàm chuyển đổi đơn vị tiền tệ với tỷ giá thực từ HolySheep AI
import requests
import json
=== CẤU HÌNH HOLYSHEEP AI ===
BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY" # Thay bằng API key của bạn
=== ĐỊNH NGHĨA CÁC FUNCTIONS ===
functions = [
{
"name": "get_weather",
"description": "Lấy thông tin thời tiết của một thành phố",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "Tên thành phố (ví dụ: Hanoi, Tokyo, New York)"
},
"units": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Đơn vị nhiệt độ"
}
},
"required": ["city"]
}
},
{
"name": "convert_currency",
"description": "Chuyển đổi giữa các đơn vị tiền tệ",
"parameters": {
"type": "object",
"properties": {
"amount": {
"type": "number",
"description": "Số tiền cần chuyển đổi"
},
"from_currency": {
"type": "string",
"description": "Tiền tệ nguồn (USD, EUR, CNY, VND, JPY)"
},
"to_currency": {
"type": "string",
"description": "Tiền tệ đích (USD, EUR, CNY, VND, JPY)"
}
},
"required": ["amount", "from_currency", "to_currency"]
}
}
]
def get_weather(city, units="celsius"):
"""Mock function - trong thực tế gọi weather API thật"""
# Giả lập dữ liệu thời tiết
weather_data = {
"Hanoi": {"temp": 28, "condition": "Nắng", "humidity": 75},
"Tokyo": {"temp": 22, "condition": "Mây rải rác", "humidity": 60},
"New York": {"temp": 18, "condition": "Mưa nhẹ", "humidity": 82}
}
data = weather_data.get(city, {"temp": 25, "condition": "Không rõ", "humidity": 50})
unit_symbol = "°C" if units == "celsius" else "°F"
temp = data["temp"] if units == "celsius" else data["temp"] * 9/5 + 32
return f"Thời tiết {city}: {temp}{unit_symbol}, {data['condition']}, độ ẩm {data['humidity']}%"
def convert_currency(amount, from_currency, to_currency):
"""Mock function - trong thực tế gọi exchange rate API"""
# Tỷ giá giả lập (USD làm chuẩn)
rates_to_usd = {"USD": 1, "EUR": 0.92, "CNY": 7.24, "VND": 24500, "JPY": 149}
if from_currency not in rates_to_usd or to_currency not in rates_to_usd:
return f"Lỗi: Không hỗ trợ tiền tệ {from_currency} hoặc {to_currency}"
usd_amount = amount / rates_to_usd[from_currency]
result = usd_amount * rates_to_usd[to_currency]
return f"{amount} {from_currency} = {result:.2f} {to_currency}"
=== XỬ LÝ CUỘC GỌI FUNCTION ===
def handle_function_call(function_name, arguments):
"""Điều phối các function calls"""
function_map = {
"get_weather": get_weather,
"convert_currency": convert_currency
}
if function_name in function_map:
return function_map[function_name](**arguments)
return f"Lỗi: Function {function_name} không tồn tại"
=== MAIN: GỌI HOLYSHEEP AI ===
def chat_with_holysheep(user_message):
"""Gửi message đến HolySheep AI với function calling"""
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": "gpt-4o-mini",
"messages": [
{"role": "user", "content": user_message}
],
"tools": [{"type": "function", "function": f} for f in functions],
"tool_choice": "auto"
}
response = requests.post(
f"{BASE_URL}/chat/completions",
headers=headers,
json=payload
)
if response.status_code != 200:
print(f"Lỗi API: {response.status_code}")
print(response.text)
return None
return response.json()
=== DEMO ===
if __name__ == "__main__":
# Test câu hỏi cần function call
test_questions = [
"Thời tiết ở Hà Nội thế nào?",
"100 đô Mỹ bằng bao nhiêu tiền Việt?",
"Hôm nay Tokyo có mưa không?"
]
for question in test_questions:
print(f"\n👤 User: {question}")
result = chat_with_holysheep(question)
if result:
print(f"📋 Response: {json.dumps(result, indent=2, ensure_ascii=False)}")
Gợi ý ảnh chụp màn hình: Kết quả chạy đoạn code trên với các câu hỏi về thời tiết và tiền tệ
Ví Dụ 2: MCP Server Đơn Giản Với Python
Bây giờ chúng ta sẽ xây dựng một MCP server cơ bản. Đây là cách tiếp cận chuẩn hóa hơn cho các hệ thống phức tạp:
// File: mcp_server_basic.js
// MCP Server đơn giản cho phép AI truy cập database và file system
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const {
CallToolRequestSchema,
ListToolsRequestSchema,
} = require('@modelcontextprotocol/sdk/types.js');
class SimpleMCPServer {
constructor() {
this.server = new Server(
{
name: "holy-sheep-data-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
// Đăng ký tất cả tools
this.server.setRequestHandler(ListToolsRequestSchema, this.handleListTools.bind(this));
this.server.setRequestHandler(CallToolRequestSchema, this.handleCallTool.bind(this));
}
// === ĐỊNH NGHĨA TOOLS ===
handleListTools() {
return {
tools: [
{
name: "query_database",
description: "Truy vấn dữ liệu từ database - hỗ trợ SELECT, INSERT, UPDATE",
inputSchema: {
type: "object",
properties: {
sql: {
type: "string",
description: "Câu lệnh SQL (chỉ hỗ trợ SELECT)"
}
},
required: ["sql"]
}
},
{
name: "read_file",
description: "Đọc nội dung file từ hệ thống",
inputSchema: {
type: "object",
properties: {
path: {
type: "string",
description: "Đường dẫn file cần đọc"
},
lines: {
type: "number",
description: "Số dòng cần đọc (mặc định: 100)"
}
},
required: ["path"]
}
},
{
name: "search_documents",
description: "Tìm kiếm trong thư viện tài liệu",
inputSchema: {
type: "object",
properties: {
query: {
type: "string",
description: "Từ khóa tìm kiếm"
},
category: {
type: "string",
enum: ["all", "invoice", "contract", "report"],
description: "Loại tài liệu"
}
},
required: ["query"]
}
},
{
name: "get_exchange_rate",
description: "Lấy tỷ giá hối đoái cập nhật realtime",
inputSchema: {
type: "object",
properties: {
from_currency: {
type: "string",
description: "Tiền tệ nguồn (USD, EUR, CNY, JPY)"
},
to_currency: {
type: "string",
description: "Tiền tệ đích"
}
},
required: ["from_currency", "to_currency"]
}
}
]
};
}
// === XỬ LÝ TOOL CALLS ===
async handleCallTool(name, arguments) {
try {
switch (name) {
case "query_database":
return await this.queryDatabase(arguments.sql);
case "read_file":
return await this.readFile(arguments.path, arguments.lines || 100);
case "search_documents":
return await this.searchDocuments(arguments.query, arguments.category);
case "get_exchange_rate":
return await this.getExchangeRate(arguments.from_currency, arguments.to_currency);
default:
return {
content: [{ type: "text", text: Tool ${name} không được hỗ trợ }]
};
}
} catch (error) {
return {
content: [{ type: "text", text: Lỗi: ${error.message} }],
isError: true
};
}
}
// === IMPLEMENTATION CÁC TOOLS ===
async queryDatabase(sql) {
// TODO: Kết nối database thật
// Ví dụ với PostgreSQL:
// const client = new Client({ connectionString: process.env.DATABASE_URL });
// await client.connect();
// const result = await client.query(sql);
// Mock data
const mockResults = [
{ id: 1, name: "Đơn hàng #001", amount: 2500000, status: "completed" },
{ id: 2, name: "Đơn hàng #002", amount: 1800000, status: "pending" },
{ id: 3, name: "Đơn hàng #003", amount: 3200000, status: "completed" }
];
return {
content: [{
type: "text",
text: JSON.stringify(mockResults, null, 2)
}]
};
}
async readFile(path, lines) {
// TODO: Implement đọc file thật
// const fs = require('fs').promises;
// const content = await fs.readFile(path, 'utf-8');
// const lineArray = content.split('\n').slice(0, lines);
return {
content: [{
type: "text",
text: 📄 File: ${path}\n[Mock content - ${lines} dòng đầu tiên]
}]
};
}
async searchDocuments(query, category) {
// TODO: Implement tìm kiếm thật với Elasticsearch hoặc similar
const mockDocuments = [
{ id: "INV-2024-001", title: "Hóa đơn tháng 1/2024", date: "2024-01-15", category: "invoice" },
{ id: "CON-2024-012", title: "Hợp đồng dịch vụ ABC", date: "2024-02-20", category: "contract" }
].filter(doc => category === "all" || doc.category === category);
return {
content: [{
type: "text",
text: 🔍 Kết quả tìm kiếm "${query}" (${category}):\n${JSON.stringify(mockDocuments, null, 2)}
}]
};
}
async getExchangeRate(from_currency, to_currency) {
// Gọi API HolySheep AI để lấy tỷ giá realtime
const response = await fetch('https://api.holysheep.ai/v1/exchange', {
headers: {
'Authorization': Bearer ${process.env.HOLYSHEEP_API_KEY},
'Content-Type': 'application/json'
},
body: JSON.stringify({ from: from_currency, to: to_currency })
});
const data = await response.json();
return {
content: [{
type: "text",
text: 💱 Tỷ giá: 1 ${from_currency} = ${data.rate} ${to_currency}\nCập nhật: ${data.timestamp}
}]
};
}
// === KHỞI ĐỘNG SERVER ===
async start() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error("🟢 MCP Server đang chạy...");
}
}
// Chạy server
const server = new SimpleMCPServer();
server.start().catch(console.error);
Gợi ý ảnh chụp màn hình: MCP server khởi động thành công và nhận tool request
Ví Dụ 3: Client Kết Nối HolySheep Với MCP
Code phía client để kết nối với MCP server và gửi request đến HolySheep AI:
// File: mcp_client_holysheep.py
// Client kết nối MCP server với HolySheep AI
import asyncio
import json
import subprocess
from openai import OpenAI
=== CẤU HÌNH ===
HOLYSHEEP_BASE_URL = "https://api.holysheep.ai/v1"
API_KEY = "YOUR_HOLYSHEEP_API_KEY"
class MCPClient:
def __init__(self):
self.client = OpenAI(
api_key=API_KEY,
base_url=HOLYSHEEP_BASE_URL
)
self.mcp_process = None
self.tools = []
# === KHỞI TẠO MCP SERVER ===
async def connect_to_mcp(self, server_script):
"""Kết nối đến MCP server"""
print("🔄 Đang khởi động MCP Server...")
# Chạy MCP server như subprocess
self.mcp_process = subprocess.Popen(
["node", server_script],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
# TODO: Implement protocol handshake với MCP server
# Đợi server ready
await asyncio.sleep(1)
print("✅ MCP Server connected!")
# === XỬ LÝ TOOL CALLS ===
async def execute_tool(self, tool_name, arguments):
"""Thực thi tool thông qua MCP server"""
# Gửi request đến MCP server
request = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": tool_name,
"arguments": arguments
}
}
# TODO: Implement giao tiếp với MCP server qua stdin/stdout
# Đây là mock implementation
mock_results = {
"query_database": lambda args: "📊 3 đơn hàng được tìm thấy",
"read_file": lambda args: "📄 Nội dung file đã được đọc",
"search_documents": lambda args: "🔍 Tìm thấy 2 tài liệu phù hợp",
"get_exchange_rate": lambda args: f"💱 1 {args['from_currency']} = {args['to_currency']} rate"
}
if tool_name in mock_results:
return mock_results[tool_name](arguments)
return f"Kết quả từ {tool_name}"
# === CHAT VỚI AI ===
async def chat(self, user_message):
"""Gửi message đến AI và xử lý tool calls"""
messages = [{"role": "user", "content": user_message}]
# Định nghĩa tools cho API
tools = [
{
"type": "function",
"function": {
"name": "query_database",
"description": "Truy vấn database",
"parameters": {
"type": "object",
"properties": {
"sql": {"type": "string"}
}
}
}
},
{
"type": "function",
"function": {
"name": "get_exchange_rate",
"description": "Lấy tỷ giá hối đoái",
"parameters": {
"type": "object",
"properties": {
"from_currency": {"type": "string"},
"to_currency": {"type": "string"}
}
}
}
}
]
# === BƯỚC 1: Gọi AI lần đầu ===
response = self.client.chat.completions.create(
model="claude-sonnet-4-20250514",
messages=messages,
tools=tools,
tool_choice="auto"
)
assistant_message = response.choices[0].message
messages.append(assistant_message)
# === BƯỚC 2: Xử lý tool calls ===
while assistant_message.tool_calls:
print("🔧 AI muốn gọi tools...")
tool_results = []
for tool_call in assistant_message.tool_calls:
tool_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f" → Gọi {tool_name} với args: {arguments}")
# Thực thi tool qua MCP
result = await self.execute_tool(tool_name, arguments)
tool_results.append({
"tool_call_id": tool_call.id,
"role": "tool",
"content": result
})
# Thêm kết quả vào messages
messages.extend(tool_results)
# === BƯỚC 3: Gọi AI lần tiếp với kết quả ===
response = self.client.chat.completions.create(
model="claude-sonnet-4-20250514",
messages=messages,
tools=tools
)
assistant_message = response.choices[0].message
messages.append(assistant_message)
return assistant_message.content
# === DỌN DẸP ===
async def disconnect(self):
"""Ngắt kết nối MCP server"""
if self.mcp_process:
self.mcp_process.terminate()
print("🔴 MCP Server disconnected")
=== DEMO ===
async def main():
client = MCPClient()
try:
# Kết nối MCP server
await client.connect_to_mcp("mcp_server_basic.js")
# Các câu hỏi test
test_questions = [
"Liệt kê 5 đơn hàng gần nhất trong database",
"Tỷ giá USD sang VND hôm nay là bao nhiêu?",
"Tìm tất cả hóa đơn trong tháng 1/2024"
]
for question in test_questions:
print(f"\n{'='*50}")
print(f"👤 User: {question}")
answer = await client.chat(question)
print(f"🤖 AI: {answer}")
finally:
await client.disconnect()
if __name__ == "__main__":
asyncio.run(main())
Gợi ý ảnh chụp màn hình: Client kết nối thành công và nhận response từ AI
Giá và ROI: So Sánh Chi Phí Thực Tế
| Yếu tố | Function Calling | MCP |
|---|---|---|
| API Calls | 1-2 call/message (tùy workflow) | 2-4 call/message (thêm cho MCP) |
| Chi phí HolySheep GPT-4o |