Model Context Protocol (MCP) la giao thuc mo cho phep cac tro ly AI nhu Claude goi cong cu ben ngoai, truy van co so du lieu va tuong tac voi API. Thay vi copy-paste ngu canh vao cua so chat, ban cap cho model quyen truy cap truc tiep vao he thong cua minh thong qua mot server nhe.
Trong bai huong dan nay, ban se xay dung mot MCP server hoan chinh bang TypeScript, cung cap mot cong cu tuy chinh cho Claude. Ket thuc bai, ban se co mot server hoat dong duoc ma co the mo rong voi bat ky tinh nang nao ban can.
Ban Se Xay Dung Gi
Mot MCP server chay local cung cap cong cu get-weather. Khi Claude hoi ve thoi tiet, no se goi server cua ban, server lay du lieu thuc va tra ve. Pattern nay ap dung duoc cho database, API noi bo, he thong file, hoac bat ky dich vu nao ban muon expose.
Yeu Cau Truoc Khi Bat Dau
- Node.js 18 tro len
- Package manager (npm hoac pnpm)
- Claude Desktop hoac Claude Code da cai dat
- Quen thuoc co ban voi TypeScript
Buoc 1: Khoi Tao Du An
Tao thu muc moi va khoi tao du an TypeScript:
mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
npx tsc --initPackage @modelcontextprotocol/sdk cung cap framework cho server. zod xu ly validate input cho cac tool.
Buoc 2: Cau Hinh TypeScript
Cap nhat tsconfig.json de dung module resolution hien dai:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}Cap nhat them package.json:
{
"type": "module",
"scripts": {
"build": "tsc",
"start": "node dist/index.js"
}
}Buoc 3: Viet Server
Tao file src/index.ts voi noi dung sau:
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
const server = new McpServer({
name: "weather-server",
version: "1.0.0",
});
server.tool(
"get-weather",
"Get current weather for a city",
{
city: z.string().describe("City name, e.g. 'London' or 'Ho Chi Minh City'"),
},
async ({ city }) => {
const response = await fetch(
`https://wttr.in/${encodeURIComponent(city)}?format=j1`
);
if (!response.ok) {
return {
content: [
{ type: "text", text: `Failed to fetch weather for ${city}` },
],
};
}
const data = await response.json();
const current = data.current_condition[0];
const summary = [
`Weather in ${city}:`,
`Temperature: ${current.temp_C}C / ${current.temp_F}F`,
`Condition: ${current.weatherDesc[0].value}`,
`Humidity: ${current.humidity}%`,
`Wind: ${current.windspeedKmph} km/h ${current.winddir16Point}`,
].join("\n");
return {
content: [{ type: "text", text: summary }],
};
}
);
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error("Weather MCP server running on stdio");
}
main().catch(console.error);Server nay lam ba viec:
- Tao instance MCP server voi ten va version
- Dang ky tool
get-weathervoi schema (ten thanh pho) va ham xu ly - Ket noi qua stdio transport - cach Claude giao tiep voi server local
Buoc 4: Build va Test
Compile TypeScript:
npm run buildTest xem server khoi dong khong loi:
echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1.0.0"}}}' | node dist/index.jsBan se thay response JSON voi server capabilities. Nhan Ctrl+C de dung.
Buoc 5: Ket Noi Voi Claude
Tao hoac chinh sua file cau hinh MCP. Voi Claude Desktop, sua file ~/Library/Application Support/Claude/claude_desktop_config.json (macOS) hoac %APPDATA%\Claude\claude_desktop_config.json (Windows):
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["/duong-dan-tuyet-doi/den/my-mcp-server/dist/index.js"]
}
}
}Voi Claude Code, them server vao file .mcp.json cua du an:
{
"mcpServers": {
"weather": {
"command": "node",
"args": ["./my-mcp-server/dist/index.js"]
}
}
}Khoi dong lai Claude sau khi luu cau hinh. Tool weather se xuat hien trong danh sach cong cu.
Buoc 6: Xac Nhan Hoat Dong
Mo Claude va hoi: "Thoi tiet o Ha Noi bay gio the nao?" Claude se goi tool get-weather cua ban va tra ve du lieu thoi tiet thuc te.
Them Nhieu Tool Hon
Suc manh cua MCP nam o kha nang to hop. Them bao nhieu tool tuy ban can:
server.tool(
"search-docs",
"Search internal documentation",
{
query: z.string().describe("Search query"),
limit: z.number().optional().default(5).describe("Max results"),
},
async ({ query, limit }) => {
// Logic tim kiem cua ban o day
const results = await searchDatabase(query, limit);
return {
content: [{ type: "text", text: JSON.stringify(results, null, 2) }],
};
}
);Moi tool co schema validation rieng, mo ta cho AI model, va ham xu ly async.
Meo Thuc Te
-
Dat ten tool va mo ta ro rang. Claude dua vao day de quyet dinh khi nao goi tool. Hay cu the ve chuc nang va truong hop su dung.
-
Validate input bang zod. Schema khong chi la tai lieu; no ngan chan request sai dinh dang truoc khi den handler.
-
Log ra stderr, khong phai stdout. Stdio transport dung stdout cho protocol messages. Dung
console.error()de debug. -
Xu ly loi mot cach duyen dang. Tra ve thong bao loi trong content array thay vi throw exception. Claude se giai thich van de cho nguoi dung.
-
Giu tool tap trung. Mot tool nen lam tot mot viec. Uu tien nhieu tool nho hon mot tool phuc tap.
-
Test truoc khi ket noi Claude. Dung MCP Inspector (
npx @modelcontextprotocol/inspector) de debug server truoc khi gan vao Claude.
Loi Thuong Gap
Server khong hien trong Claude: Kiem tra lai duong dan tuyet doi trong config. Dam bao file JS da compile ton tai o duong dan do.
Tool goi that bai im lang: Kiem tra output stderr. Chay server thu cong va gui test request de co lap van de.
Loi compile TypeScript: Dam bao "type": "module" duoc set trong package.json va cac import dung duoi .js.
Buoc Tiep Theo
Tu day, ban co the mo rong server de ket noi database, wrap REST API, tuong tac voi file system, hoac dieu phoi cac dich vu khac. He sinh thai MCP dang phat trien nhanh chong, va xay server tuy chinh la cach nhanh nhat de Claude lam viec voi cong cu va du lieu cu the cua ban.
Try claude-code
Claude Code la cach nhanh nhat de phat trien va test MCP server. No ket noi voi server local tu dong va cung cap phan hoi thoi gian thuc khi ban xay dung.