Model Context Protocol (MCP) untuk Web Developer 2026: Bangun Server AI Tooling dengan TypeScript dari Nol
Panduan lengkap berbahasa Indonesia untuk memahami dan menerapkan Model Context Protocol (MCP) di proyek web modern. Mulai dari konsep, arsitektur, hingga implementasi server TypeScript yang runnable dengan validasi, error handling, dan best practices production.
Model Context Protocol (MCP) untuk Web Developer 2026: Bangun Server AI Tooling dengan TypeScript dari Nol
7+ menit baca • Level: Menengah • Fokus: Web Development + AI Integration
1) Introduction — Apa itu MCP dan Kenapa Penting?
Kalau beberapa tahun lalu API REST jadi “bahasa umum” antar aplikasi web, di 2026 kita melihat pola yang mirip untuk integrasi AI: Model Context Protocol (MCP).
Sederhananya, MCP adalah standar terbuka agar aplikasi AI (misalnya Claude, ChatGPT, atau AI coding assistant lain) bisa bicara ke tools, data source, dan workflow kamu dengan cara yang konsisten.
Bayangin begini:
- Sebelum MCP: tiap tool bikin “colokan” sendiri-sendiri, format request/response beda-beda.
- Dengan MCP: kita punya “USB-C untuk AI”. Sekali paham pola MCP, kamu bisa plug ke banyak client.
Kenapa ini penting buat web developer?
- Reuse skill backend yang sudah kamu punya: kamu tetap desain tool seperti API contract, schema validation, auth, logging.
- Faster integration: AI client tidak perlu custom adapter per tool.
- Lebih maintainable: arsitektur jelas antara client AI, MCP server, dan service internal.
- Ekosistem cepat tumbuh: GitHub trending + diskusi X + artikel dev.to menunjukkan lonjakan topik “agentic workflows”, “MCP server”, dan “AI tooling infrastructure”.
Real-world context: startup SaaS sekarang banyak yang menambahkan “AI operator” untuk tugas support, data lookup, atau automasi internal. MCP memungkinkan tim web menghubungkan AI ke sistem yang sudah ada tanpa rewrite total.
2) Prerequisites — Apa yang Harus Disiapkan?
Sebelum mulai, pastikan kamu sudah nyaman dengan:
- Node.js LTS (disarankan Node 20+)
- TypeScript dasar-menengah
- Konsep async/await dan error handling
- JSON schema validation (kita pakai
zod) - Dasar HTTP API (untuk memahami flow tool invocation)
Tools yang dipakai di tutorial ini:
@modelcontextprotocol/serverzodtsxuntuk menjalankan TypeScript tanpa compile manual
Install environment:
node -v npm -v
Kalau belum ada, install Node LTS dulu. Setelah itu kita siap coding.
3) Core Concepts — Fondasi MCP dengan Analogi Sederhana
Biar gampang kebayang, anggap MCP seperti restoran pintar:
- Client AI = Pelayan yang menerima permintaan pengguna.
- MCP Server = Dapur yang tahu daftar menu (tools), aturan, dan cara memasak.
- Tool = Menu spesifik (misalnya “buat todo”, “cari data customer”).
- Schema (Zod) = Standar kualitas pesanan (format input harus valid).
Alur umumnya:
- User minta sesuatu ke AI.
- AI memutuskan perlu memanggil tool.
- AI kirim request ke MCP server.
- MCP server validasi input + eksekusi logic.
- Hasil dikembalikan ke AI untuk dijawab ke user.
Konsep kunci yang wajib kamu pegang:
- Tool-first design: desain kemampuan kecil, jelas, bisa diuji.
- Strong validation: jangan pernah percaya input mentah dari LLM.
- Deterministic output: hasil tool harus konsisten agar AI tidak “bingung”.
- Observability: log request, error, latency.
4) Architecture / Diagram — Gambaran Arsitektur
Berikut arsitektur sederhana untuk use case “AI Todo Assistant”:
+---------------------+ MCP Protocol +---------------------------+ | AI Client | <------------------------> | MCP Server (TypeScript) | | (Claude/ChatGPT/IDE)| | - register tools | +---------------------+ | - validate input (zod) | | - auth/rate limit/log | +-------------+-------------+ | | service call v +---------------------------+ | Todo Service / DB Layer | | - create/list/update task | +---------------------------+
Dalam production, kamu bisa menambahkan:
- Redis untuk rate limit
- PostgreSQL untuk persistence
- OpenTelemetry untuk tracing
- API gateway + auth proxy
5) Step-by-Step Implementation (Complete Runnable Code)
Di bagian ini kita bikin MCP server minimal tapi production-minded:
- Tool
create_todo - Tool
list_todos - Validation pakai
zod - Error handling rapi
- Logging sederhana
5.1 Inisialisasi project
mkdir mcp-todo-server cd mcp-todo-server npm init -y npm install @modelcontextprotocol/server zod npm install -D typescript tsx @types/node npx tsc --init
Update package.json scripts:
{ "scripts": { "dev": "tsx src/server.ts", "start": "node dist/server.js" } }
5.2 Buat file src/server.ts
Kode di bawah ini lengkap dan bisa langsung dijalankan untuk mode local testing.
import { Server } from "@modelcontextprotocol/server"; import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"; import { z } from "zod"; /** * Domain model sederhana untuk demo. * Untuk production: pindah ke database + repository layer. */ type Todo = { id: string; title: string; done: boolean; createdAt: string; }; const todos: Todo[] = []; /** * Utility logging sederhana. */ function logInfo(message: string, meta?: unknown) { console.log(JSON.stringify({ level: "info", message, meta, ts: new Date().toISOString() })); } function logError(message: string, error: unknown) { console.error( JSON.stringify({ level: "error", message, error: error instanceof Error ? { name: error.name, message: error.message, stack: error.stack } : error, ts: new Date().toISOString(), }) ); } /** * Input schema untuk tool create_todo. */ const CreateTodoInput = z.object({ title: z.string().min(3, "Title minimal 3 karakter").max(120, "Title maksimal 120 karakter"), }); /** * Input schema untuk list_todos. */ const ListTodosInput = z.object({ includeDone: z.boolean().default(true), }); async function main() { // Inisialisasi MCP server const server = new Server( { name: "todo-mcp-server", version: "1.0.0", }, { capabilities: { tools: {}, }, } ); // Register tool: create_todo server.tool( "create_todo", { title: "Create Todo", description: "Membuat todo baru untuk task management.", inputSchema: { type: "object", properties: { title: { type: "string", minLength: 3, maxLength: 120 }, }, required: ["title"], }, }, async (rawInput: unknown) => { try { const input = CreateTodoInput.parse(rawInput); const todo: Todo = { id: crypto.randomUUID(), title: input.title.trim(), done: false, createdAt: new Date().toISOString(), }; todos.push(todo); logInfo("Todo created", { todoId: todo.id, title: todo.title }); return { content: [ { type: "text", text: `✅ Todo berhasil dibuat ID: ${todo.id} Title: ${todo.title}`, }, ], }; } catch (error) { logError("Failed to create todo", error); // Jangan bocorkan detail internal ke user const message = error instanceof z.ZodError ? `Input tidak valid: ${error.issues.map((i) => i.message).join(", ")}` : "Gagal membuat todo karena kesalahan internal."; return { isError: true, content: [{ type: "text", text: `❌ ${message}` }], }; } } ); // Register tool: list_todos server.tool( "list_todos", { title: "List Todos", description: "Menampilkan daftar todo saat ini.", inputSchema: { type: "object", properties: { includeDone: { type: "boolean", default: true }, }, }, }, async (rawInput: unknown) => { try { const input = ListTodosInput.parse(rawInput ?? {}); const result = input.includeDone ? todos : todos.filter((t) => !t.done); if (result.length === 0) { return { content: [{ type: "text", text: "Belum ada todo." }], }; } const lines = result.map((t, index) => `${index + 1}. [${t.done ? "x" : " "}] ${t.title} (id=${t.id})`); return { content: [{ type: "text", text: `📋 Daftar Todo: ${lines.join(" ")}` }], }; } catch (error) { logError("Failed to list todos", error); return { isError: true, content: [{ type: "text", text: "❌ Gagal mengambil daftar todo." }], }; } } ); // Transport stdio cocok untuk local integration/testing const transport = new StdioServerTransport(); await server.connect(transport); logInfo("MCP server started", { transport: "stdio" }); } main().catch((error) => { logError("Fatal error on startup", error); process.exit(1); });
5.3 Jalankan server
npm run dev
Server sekarang siap menerima tool call dari MCP-compatible client.
5.4 Kenapa implementasi ini “runnable + sehat”?
- Ada validasi input dengan
zod - Error handling jelas (validation error vs internal error)
- Logging terstruktur JSON
- Tidak membocorkan stack trace ke end-user
- Domain model terpisah dari transport logic
6) Best Practices — Tips dari Praktik Industri
Berikut hal-hal yang sangat direkomendasikan saat MCP masuk ke production:
-
Version tools dengan jelas
- Contoh:
create_todo_v1, lalu deprecate secara bertahap.
- Contoh:
-
Schema strict, bukan longgar
- Selalu set min/max length, enum, pattern.
- Ini mengurangi halusinasi input dari model.
-
Idempotency untuk operasi kritikal
- Misal create order/payment: gunakan
idempotencyKey.
- Misal create order/payment: gunakan
-
Timeout dan retry policy
- Jangan biarkan tool call menggantung terlalu lama.
-
Observability end-to-end
- Tambahkan tracing (OpenTelemetry) + correlation ID.
-
Principle of least privilege
- MCP server hanya boleh akses resource yang dibutuhkan.
-
Pisahkan demo server vs production server
- Repo referensi MCP sendiri menekankan banyak server contoh bersifat edukasi, bukan drop-in production.
7) Common Mistakes — Kesalahan Umum yang Harus Dihindari
Mistake #1: “LLM pasti kirim input benar”
Ini jebakan paling umum. Tanpa schema ketat, bug aneh muncul di runtime.
Solusi: validasi semua input, kasih pesan error terarah.
Mistake #2: Tool terlalu gemuk
Satu tool melakukan 7 hal sekaligus bikin sulit debug.
Solusi: pecah jadi tools kecil dan composable.
Mistake #3: Tidak ada auth boundary
Langsung expose tool sensitif ke AI tanpa lapisan izin.
Solusi: tambahkan auth, scope, dan audit log.
Mistake #4: Output tidak deterministik
Kadang return object A, kadang B, field random.
Solusi: tetapkan response shape konsisten.
Mistake #5: Langsung production tanpa load test
Begitu dipakai tim besar, latency meledak.
Solusi: benchmark dari awal, pasang rate limit + queue bila perlu.
8) Advanced Tips — Untuk yang Mau Naik Level
Kalau basic MCP server sudah jalan, kamu bisa lanjut ke level berikut:
-
Transport strategy
- Local dev: stdio cepat dan simpel.
- Team/server deployment: Streamable HTTP + auth.
-
MCP + existing backend architecture
- Anggap MCP sebagai adapter layer di atas service domain kamu.
- Jangan taruh business logic utama di handler tool.
-
Tool governance
- Buat katalog internal: tool name, owner, SLA, data sensitivity.
-
Prompt-aware API design
- Beri deskripsi tool yang jelas, contoh input/output, batasan perilaku.
-
Secure-by-default pattern
- Input sanitization, outbound allowlist, secret manager, audit trail.
-
Progressive rollout
- Mulai dari read-only tools (aman), baru ke write action.
-
Testing pyramid untuk MCP
- Unit test: validasi schema + pure functions
- Integration test: tool handler + service layer
- Contract test: response shape tetap stabil antar versi
9) Summary & Next Steps
Kita sudah bahas dari nol sampai implementasi runnable:
- Memahami MCP sebagai standar integrasi AI-tooling
- Menyusun arsitektur yang clean
- Membangun MCP server TypeScript dengan error handling yang benar
- Mengetahui best practices + anti-pattern yang sering terjadi
Next steps yang saya sarankan untuk kamu:
- Tambahkan persistence (PostgreSQL + Prisma/Drizzle)
- Tambahkan auth token & role check per tool
- Migrasi ke HTTP transport untuk multi-client usage
- Tambahkan observability (logs + tracing + metrics)
- Buat CI contract test agar perubahan schema aman
Kalau kamu sudah sampai tahap ini, kamu bukan cuma “bisa coba-coba MCP”, tapi sudah punya fondasi untuk membangun AI-enabled web systems yang serius.
10) References
Dokumentasi resmi dan repositori yang dipakai sebagai rujukan:
-
Model Context Protocol — Introduction
https://modelcontextprotocol.io/docs/getting-started/intro -
MCP Architecture
https://modelcontextprotocol.io/docs/learn/architecture -
MCP Specification
https://spec.modelcontextprotocol.io -
MCP TypeScript SDK (official)
https://github.com/modelcontextprotocol/typescript-sdk -
MCP Servers (reference implementations)
https://github.com/modelcontextprotocol/servers -
MCP Registry
https://registry.modelcontextprotocol.io -
VS Code + MCP docs (ecosystem support)
https://code.visualstudio.com/docs/copilot/chat/mcp-servers -
OpenAI docs — MCP integration references
https://developers.openai.com/api/docs/mcp/
Semoga tutorial ini bikin kamu lebih pede membangun integrasi AI yang rapi, aman, dan scalable. 🚀