Tutorial MCP (Model Context Protocol): Panduan Lengkap untuk Developer - Nayaka Yoga Pradipta

Tutorial MCP (Model Context Protocol): Panduan Lengkap untuk Developer

Senin, 23 Des 2024

Kalau kamu seorang developer yang sudah mulai bermain dengan AI dan LLM (Large Language Model), pasti pernah merasakan frustrasi ini: “Gimana caranya AI ini bisa akses data atau tools yang aku punya?”

Nah, di sinilah Model Context Protocol (MCP) hadir sebagai solusi yang game-changing. MCP adalah standar terbuka yang dikembangkan oleh Anthropic untuk menghubungkan AI dengan berbagai data source dan tools secara seamless.

Dalam tutorial ini, aku akan membagikan panduan lengkap tentang MCP—mulai dari konsep dasar, arsitektur, hingga cara membuat MCP server sendiri dengan contoh kode yang bisa langsung kamu praktikkan.

Apa Itu Model Context Protocol (MCP)?

Model Context Protocol (MCP) adalah protokol open-source yang menyediakan cara standar untuk menghubungkan aplikasi AI dengan sumber data eksternal dan tools. Bayangkan MCP seperti “USB port” untuk AI—satu interface universal yang memungkinkan berbagai AI model terhubung dengan berbagai aplikasi.

Analogi Sederhana

Sebelum MCP ada, setiap developer harus membuat custom integration untuk setiap kombinasi AI + data source. Ini seperti zaman dulu ketika setiap handphone punya charger berbeda—ribet banget!

MCP hadir layaknya USB-C yang jadi standar universal. Dengan MCP:

  • Satu protokol untuk semua koneksi
  • Reusable components yang bisa dipakai di berbagai AI client
  • Standarisasi yang memudahkan development dan maintenance

Kenapa MCP Penting untuk Developer?

  1. Eliminasi Boilerplate Code: Tidak perlu lagi menulis integration code yang repetitif untuk setiap AI platform
  2. Interoperability: MCP server yang kamu buat bisa dipakai di Claude, VS Code, dan client lainnya yang support MCP
  3. Security First: MCP dirancang dengan keamanan sebagai prioritas—data tetap di sisi server, AI hanya bisa akses melalui defined interface
  4. Scalability: Arsitektur yang modular memudahkan scaling dan maintenance
  5. Community Driven: Sebagai open standard, ada banyak MCP server yang sudah dibuat komunitas dan bisa langsung kamu gunakan

Arsitektur MCP: Host, Client, dan Server

Untuk memahami MCP dengan baik, kamu perlu mengerti tiga komponen utamanya:

1. MCP Host

Host adalah aplikasi utama yang digunakan user untuk berinteraksi dengan AI. Contohnya:

  • Claude Desktop
  • Cursor IDE
  • VS Code dengan extension yang support MCP
  • Aplikasi custom yang kamu buat

Host bertanggung jawab untuk:

  • Mengelola lifecycle MCP client
  • Mengatur permission dan security
  • Menyediakan UI untuk user

2. MCP Client

Client adalah komponen yang ada di dalam host dan bertugas:

  • Memaintain koneksi ke MCP server (1 client : 1 server)
  • Mengirim request ke server
  • Menerima dan memproses response dari server

Setiap MCP client hanya bisa terhubung ke satu server, tapi satu host bisa punya banyak client yang terhubung ke server berbeda.

3. MCP Server

Server adalah tempat di mana magic terjadi! Server expose:

  • Tools: Fungsi yang bisa dipanggil AI untuk melakukan aksi
  • Resources: Data atau konten yang bisa dibaca AI
  • Prompts: Template prompt yang bisa digunakan

Server bisa berjalan sebagai:

  • Local process: Dijalankan di mesin yang sama dengan host
  • Remote service: Berjalan di cloud atau server terpisah

Diagram Arsitektur

┌─────────────────────────────────────────────────────┐
│                    MCP HOST                          │
│  (Claude Desktop / Cursor / VS Code)                │
│                                                      │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐          │
│  │  Client  │  │  Client  │  │  Client  │          │
│  └────┬─────┘  └────┬─────┘  └────┬─────┘          │
└───────┼─────────────┼─────────────┼─────────────────┘
        │             │             │
        ▼             ▼             ▼
   ┌─────────┐   ┌─────────┐   ┌─────────┐
   │ Server  │   │ Server  │   │ Server  │
   │(GitHub) │   │  (DB)   │   │(Custom) │
   └─────────┘   └─────────┘   └─────────┘

Cara Kerja MCP: JSON-RPC, Tools, Resources, dan Prompts

MCP menggunakan JSON-RPC 2.0 sebagai format komunikasinya. Ini adalah protokol yang lightweight dan sudah well-established di industri.

Transport Layer

MCP mendukung dua jenis transport:

1. stdio (Standard Input/Output)

  • Server dijalankan sebagai subprocess
  • Komunikasi via stdin/stdout
  • Cocok untuk local development dan tools seperti Claude Desktop
{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["path/to/server.js"]
    }
  }
}

2. HTTP dengan SSE (Server-Sent Events)

  • Server berjalan sebagai HTTP service
  • Menggunakan SSE untuk streaming response
  • Cocok untuk remote deployment

Tiga Primitif Utama MCP

1. Tools

Tools adalah fungsi yang bisa dipanggil AI untuk melakukan aksi spesifik. Contoh:

  • search_database: Mencari data di database
  • send_email: Mengirim email
  • create_file: Membuat file baru
// Contoh definisi tool
{
  name: "get_weather",
  description: "Get current weather for a city",
  inputSchema: {
    type: "object",
    properties: {
      city: {
        type: "string",
        description: "City name"
      }
    },
    required: ["city"]
  }
}

2. Resources

Resources menyediakan data atau konten yang bisa dibaca AI. Berbeda dengan tools, resources lebih bersifat read-only dan contextual.

// Contoh resource
{
  uri: "file:///docs/readme.md",
  name: "Project README",
  mimeType: "text/markdown"
}

Resources sangat berguna untuk:

  • Memberikan context dokumen ke AI
  • Menyediakan data referensi
  • Expose file system atau database content

3. Prompts

Prompts adalah template yang bisa digunakan untuk memandu interaksi dengan AI. Ini membantu standardisasi cara user berinteraksi dengan capability tertentu.

// Contoh prompt
{
  name: "code_review",
  description: "Review code for best practices",
  arguments: [
    {
      name: "language",
      description: "Programming language",
      required: true
    }
  ]
}

Lifecycle Komunikasi MCP

  1. Initialization: Client dan server bertukar capability dan versioning info
  2. Discovery: Client request daftar tools, resources, dan prompts yang tersedia
  3. Execution: Client memanggil tools atau request resources sesuai kebutuhan
  4. Shutdown: Graceful termination ketika tidak diperlukan lagi

Setup Environment untuk MCP Development

Sekarang mari kita setup environment untuk mulai develop MCP server sendiri.

Prerequisites

Pastikan kamu sudah punya:

  • Node.js 18+ atau Python 3.10+
  • Claude Desktop atau MCP client lainnya untuk testing
  • Code editor (VS Code recommended)

Install MCP SDK

Untuk TypeScript/JavaScript:

# Buat project baru
mkdir my-mcp-server
cd my-mcp-server
npm init -y

# Install dependencies
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node tsx

Setup TypeScript config:

// tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

Update package.json:

{
  "name": "my-mcp-server",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js",
    "dev": "tsx src/index.ts"
  }
}

Contoh MCP Server Sederhana

Mari kita buat MCP server yang sederhana tapi fungsional—server yang bisa memberikan informasi cuaca.

Struktur Project

my-mcp-server/
├── src/
│   └── index.ts
├── package.json
└── tsconfig.json

Kode MCP Server

// src/index.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

// Inisialisasi server
const server = new McpServer({
  name: "weather-server",
  version: "1.0.0",
});

// Definisi schema untuk input
const GetWeatherSchema = z.object({
  city: z.string().describe("Nama kota untuk cek cuaca"),
});

// Daftar tool yang tersedia
server.tool(
  "get_weather",
  "Mendapatkan informasi cuaca untuk kota tertentu",
  GetWeatherSchema.shape,
  async ({ city }) => {
    // Simulasi data cuaca (di production, kamu akan call API cuaca)
    const weatherData = {
      Jakarta: { temp: 32, condition: "Cerah berawan", humidity: 75 },
      Bandung: { temp: 24, condition: "Berawan", humidity: 80 },
      Surabaya: { temp: 34, condition: "Cerah", humidity: 65 },
      Bali: { temp: 30, condition: "Cerah", humidity: 70 },
    };

    const weather = weatherData[city as keyof typeof weatherData];

    if (!weather) {
      return {
        content: [
          {
            type: "text" as const,
            text: `Maaf, data cuaca untuk ${city} tidak tersedia. Kota yang tersedia: Jakarta, Bandung, Surabaya, Bali`,
          },
        ],
      };
    }

    return {
      content: [
        {
          type: "text" as const,
          text: `Cuaca di ${city}:\n- Suhu: ${weather.temp}°C\n- Kondisi: ${weather.condition}\n- Kelembaban: ${weather.humidity}%`,
        },
      ],
    };
  }
);

// Tambah resource untuk dokumentasi
server.resource(
  "weather://docs",
  "Dokumentasi penggunaan weather server",
  async () => ({
    contents: [
      {
        uri: "weather://docs",
        mimeType: "text/plain",
        text: `
Weather MCP Server
==================
Server ini menyediakan informasi cuaca untuk kota-kota di Indonesia.

Tools yang tersedia:
- get_weather: Mendapatkan informasi cuaca untuk kota tertentu

Kota yang didukung:
- Jakarta
- Bandung  
- Surabaya
- Bali
        `.trim(),
      },
    ],
  })
);

// Tambah prompt template
server.prompt(
  "weather_check",
  "Template untuk mengecek cuaca",
  [
    {
      name: "city",
      description: "Nama kota",
      required: true,
    },
  ],
  async ({ city }) => ({
    messages: [
      {
        role: "user",
        content: {
          type: "text",
          text: `Tolong cek cuaca di ${city} dan berikan rekomendasi aktivitas outdoor yang cocok.`,
        },
      },
    ],
  })
);

// Jalankan server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("Weather MCP Server running on stdio");
}

main().catch(console.error);

Build dan Test

# Build project
npm run build

# Test dengan running langsung
npm run dev

Konfigurasi di Claude Desktop

Untuk menggunakan MCP server di Claude Desktop, tambahkan konfigurasi berikut:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "weather": {
      "command": "node",
      "args": ["/path/to/my-mcp-server/dist/index.js"]
    }
  }
}

Restart Claude Desktop, dan sekarang kamu bisa bertanya tentang cuaca!

MCP Server dan Tools Populer

Salah satu kekuatan MCP adalah ekosistem yang terus berkembang. Berikut beberapa MCP server populer yang bisa langsung kamu gunakan:

1. Filesystem Server

Server untuk akses file system lokal. Sangat berguna untuk:

  • Membaca dan menulis file
  • Browsing direktori
  • Manipulasi file
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/directory"
      ]
    }
  }
}

2. GitHub Server

Integrasi dengan GitHub untuk:

  • Membaca repository
  • Membuat dan manage issues
  • Review pull requests

3. Database Servers

Ada berbagai MCP server untuk database:

  • PostgreSQL: Query dan manipulasi data PostgreSQL
  • SQLite: Akses database SQLite lokal
  • MongoDB: Integrasi dengan MongoDB

4. DataForSEO Server

Untuk kebutuhan SEO dan marketing:

  • Keyword research
  • SERP analysis
  • Backlink analysis

5. Web Browser Server

Memungkinkan AI untuk:

  • Membaca konten web page
  • Screenshot halaman
  • Interaksi dengan web elements

Cara Menemukan MCP Server

Kamu bisa menemukan MCP server di:

  1. Official MCP Servers: github.com/modelcontextprotocol/servers
  2. Community Collections: Berbagai list di GitHub
  3. npm/PyPI: Cari dengan keyword “mcp-server”

Best Practices MCP Development

Dari pengalaman develop berbagai MCP server, berikut best practices yang wajib kamu ikuti:

1. Security First

// ❌ Jangan expose semua file
server.tool("read_file", async ({ path }) => {
  return fs.readFileSync(path);
});

// ✅ Validasi dan batasi akses
const ALLOWED_DIRS = ["/app/data", "/app/public"];

server.tool("read_file", async ({ path }) => {
  const resolvedPath = path.resolve(path);
  const isAllowed = ALLOWED_DIRS.some((dir) =>
    resolvedPath.startsWith(dir)
  );
  
  if (!isAllowed) {
    throw new Error("Access denied");
  }
  
  return fs.readFileSync(resolvedPath);
});

2. Descriptive Tool Definitions

// ❌ Kurang deskriptif
server.tool("search", async ({ q }) => {
  // ...
});

// ✅ Jelas dan informatif
server.tool(
  "search_products",
  "Search products in the catalog. Returns up to 10 results sorted by relevance. Supports filtering by category and price range.",
  {
    query: z.string().describe("Search keywords"),
    category: z.string().optional().describe("Product category filter"),
    minPrice: z.number().optional().describe("Minimum price in IDR"),
    maxPrice: z.number().optional().describe("Maximum price in IDR"),
  },
  async (params) => {
    // implementation
  }
);

3. Error Handling yang Baik

server.tool("api_call", async ({ endpoint }) => {
  try {
    const response = await fetch(endpoint);
    
    if (!response.ok) {
      return {
        content: [{
          type: "text",
          text: `API error: ${response.status} - ${response.statusText}`,
        }],
        isError: true,
      };
    }
    
    const data = await response.json();
    return {
      content: [{
        type: "text",
        text: JSON.stringify(data, null, 2),
      }],
    };
  } catch (error) {
    return {
      content: [{
        type: "text",
        text: `Failed to call API: ${error.message}`,
      }],
      isError: true,
    };
  }
});

4. Logging dan Debugging

// Gunakan stderr untuk logging (stdout reserved untuk MCP protocol)
console.error("[INFO] Server started");
console.error("[DEBUG] Processing request:", requestId);
console.error("[ERROR] Failed to connect:", error.message);

5. Rate Limiting dan Caching

import { LRUCache } from "lru-cache";

const cache = new LRUCache<string, any>({
  max: 100,
  ttl: 1000 * 60 * 5, // 5 minutes
});

server.tool("expensive_operation", async ({ query }) => {
  const cacheKey = `query:${query}`;
  
  // Check cache first
  const cached = cache.get(cacheKey);
  if (cached) {
    console.error("[CACHE] Hit for:", query);
    return cached;
  }
  
  // Perform expensive operation
  const result = await performExpensiveOperation(query);
  
  // Store in cache
  cache.set(cacheKey, result);
  
  return result;
});

6. Graceful Shutdown

process.on("SIGINT", async () => {
  console.error("[INFO] Shutting down gracefully...");
  // Cleanup connections, save state, etc.
  await cleanup();
  process.exit(0);
});

process.on("SIGTERM", async () => {
  console.error("[INFO] Received SIGTERM, shutting down...");
  await cleanup();
  process.exit(0);
});

Testing MCP Server

Testing adalah bagian penting dari development. Berikut cara test MCP server:

1. Manual Testing dengan MCP Inspector

# Install MCP Inspector
npx @modelcontextprotocol/inspector node dist/index.js

MCP Inspector menyediakan UI untuk:

  • Melihat daftar tools, resources, dan prompts
  • Menjalankan tools dengan input custom
  • Debug response

2. Automated Testing

// test/server.test.ts
import { describe, it, expect } from "vitest";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";

describe("Weather Server", () => {
  it("should return weather for valid city", async () => {
    const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
    
    // Setup client and server...
    
    const result = await client.callTool({
      name: "get_weather",
      arguments: { city: "Jakarta" },
    });
    
    expect(result.content[0].text).toContain("Jakarta");
    expect(result.content[0].text).toContain("°C");
  });
});

MCP dengan Python

Kalau kamu lebih nyaman dengan Python, MCP juga support Python SDK:

# Install: pip install mcp

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

server = Server("weather-server")

@server.tool()
async def get_weather(city: str) -> list[TextContent]:
    """Get weather information for a city."""
    weather_data = {
        "Jakarta": {"temp": 32, "condition": "Sunny"},
        "Bandung": {"temp": 24, "condition": "Cloudy"},
    }
    
    weather = weather_data.get(city)
    if not weather:
        return [TextContent(
            type="text",
            text=f"Weather data for {city} not available"
        )]
    
    return [TextContent(
        type="text", 
        text=f"Weather in {city}: {weather['temp']}°C, {weather['condition']}"
    )]

async def main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream)

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

Debugging Tips

1. Check Logs

MCP logs bisa dilihat di:

  • Claude Desktop: ~/Library/Logs/Claude/ (macOS)
  • Custom apps: Tergantung implementasi logging

2. Common Issues

Server tidak muncul di Claude:

  • Pastikan path ke server benar
  • Check syntax JSON config
  • Restart Claude Desktop

Tool tidak dipanggil:

  • Pastikan description tool cukup jelas
  • Check apakah AI memahami kapan harus menggunakan tool

Error “Connection refused”:

  • Server mungkin crash saat startup
  • Check stderr output untuk error messages

3. Development Mode

Gunakan tsx untuk development dengan hot reload:

# Install tsx globally
npm install -g tsx

# Run dengan watch mode
tsx watch src/index.ts

Real-World Use Cases

1. Personal Knowledge Base

Buat MCP server yang connect ke Notion atau Obsidian untuk:

  • Mencari notes
  • Membuat notes baru
  • Update existing notes

2. Development Workflow

MCP server untuk:

  • Run tests
  • Deploy aplikasi
  • Manage Git operations

3. Business Intelligence

Connect AI dengan:

  • Database perusahaan
  • Analytics platforms
  • Reporting tools

4. Content Creation

Seperti yang aku gunakan di blog ini:

  • Keyword research dengan DataForSEO
  • Image generation
  • Content publishing

Masa Depan MCP

MCP masih sangat baru (launched November 2024), tapi adopsinya sangat cepat:

  • IDE Integration: Cursor, VS Code, dan IDE lain mulai support MCP
  • Enterprise Adoption: Perusahaan besar mulai develop internal MCP servers
  • Community Growth: Ribuan MCP server sudah dibuat komunitas
  • Standardization: MCP sedang dalam proses join Linux Foundation

Sebagai developer, sekarang adalah waktu yang tepat untuk:

  1. Belajar dan eksperimen dengan MCP
  2. Kontribusi ke ekosistem dengan membuat MCP server
  3. Integrate MCP ke workflow development kamu

Kesimpulan dan Next Steps

MCP (Model Context Protocol) adalah breakthrough dalam cara kita mengintegrasikan AI dengan tools dan data. Dengan memahami konsep Host-Client-Server, serta primitif Tools-Resources-Prompts, kamu sudah punya fondasi kuat untuk mulai develop MCP server sendiri.

Langkah Selanjutnya

  1. Install Claude Desktop dan coba beberapa MCP server yang sudah ada
  2. Buat MCP server sederhana mengikuti contoh di tutorial ini
  3. Eksplorasi MCP servers dari komunitas di GitHub
  4. Join komunitas MCP untuk diskusi dan berbagi pengalaman

Resources Tambahan

Selamat bereksperimen dengan MCP! Kalau ada pertanyaan atau mau diskusi, feel free untuk reach out. Happy coding! 🚀