dailytutorfor.you
Data Science & AI

MCP untuk Developer 2026: Bangun Server Tool AI Production-Ready dengan Python (Lengkap dari Nol)

MCP (Model Context Protocol) jadi standar baru integrasi AI app dengan tools dan data eksternal. Di tutorial ini kamu akan belajar konsep inti MCP, arsitektur host-client-server, implementasi server Python yang benar-benar runnable, plus best practices keamanan, observability, dan scaling untuk use case nyata.

9 menit baca

MCP untuk Developer 2026: Bangun Server Tool AI Production-Ready dengan Python (Lengkap dari Nol)

Level: Menengah
Durasi baca: ~15 menit
Stack: Python 3.11+, MCP Python SDK, uv/pip

1) Introduction — What and Why

Kalau kamu aktif ngikutin tren developer di 2026, pasti sering lihat istilah AI agents, tool calling, dan terutama MCP (Model Context Protocol).

Kenapa MCP ramai?

  • Di GitHub Trending, repository terkait AI tooling, agent infrastructure, dan MCP ekosistem naik cepat.
  • Banyak diskusi developer (X/komunitas) beralih dari “prompt engineering doang” ke “bagaimana AI bisa akses tools dan data secara aman”.
  • Dokumentasi resmi MCP dan SDK multi-bahasa makin matang, jadi adopsinya nggak lagi eksperimen semata.

Bayangin kamu punya AI assistant buat tim engineering. Assistant ini harus bisa:

  • baca status deployment,
  • cek tiket incident,
  • query knowledge base internal,
  • dan jalanin workflow tertentu.

Tanpa standar, tiap integrasi jadi custom glue code yang rapuh. Nah, MCP adalah “USB-C untuk aplikasi AI”: satu protokol standar untuk menghubungkan AI host ke tools/resources eksternal.

Hasilnya:

  • integrasi lebih konsisten,
  • onboarding tool baru lebih cepat,
  • kontrol keamanan lebih jelas (permission, auth, boundary).

Di tutorial ini kita fokus bikin MCP server Python yang bisa dipakai untuk use case nyata, bukan sekadar demo satu fungsi tambah angka.


2) Prerequisites

Sebelum mulai, pastikan kamu punya:

  1. Python 3.11+
  2. Basic paham:
    • REST API/HTTP,
    • JSON,
    • async/await Python (minimal konsep)
  3. Environment setup:
    • uv (recommended) atau pip
  4. Editor: VS Code / Cursor / IDE favorit

Install dependency:

# opsi A (recommended) uv init mcp-sales-assistant cd mcp-sales-assistant uv add "mcp[cli]" # opsi B (pip) python -m venv .venv source .venv/bin/activate pip install "mcp[cli]"

Cek instalasi:

python -c "import mcp; print('MCP SDK installed')"

3) Core Concepts — Fondasi MCP (pakai analogi)

Biar gampang, anggap MCP seperti sistem restoran:

  • Host = restoran (aplikasi AI utama, misalnya IDE/chat app)
  • Client = waiter (komponen penghubung host ke server MCP)
  • Server = dapur spesialis (penyedia tools/resources)

Tiga primitive inti di server

  1. Tools → aksi (mirip endpoint POST)
    • contoh: create_ticket, check_order_status
  2. Resources → data kontekstual (mirip endpoint GET)
    • contoh: kb://oncall-runbook
  3. Prompts → template instruksi reusable
    • contoh: prompt standar untuk incident summary

Layer arsitektur MCP

  • Data Layer: JSON-RPC 2.0 message (capability negotiation, tools/resources/prompts, notifications)
  • Transport Layer:
    • stdio (lokal, cepat, tanpa network overhead)
    • streamable-http (remote server, cocok multi-client)

Kenapa ini penting?

Karena ketika host berganti (misal dari IDE A ke IDE B), server MCP kamu tetap bisa dipakai selama patuh standar. Ini bikin investasi engineering lebih tahan lama.


4) Architecture / Diagram

Kita buat contoh: Sales Ops Assistant untuk tim produk.

Use case:

  • Tool untuk hitung nilai order + pajak + diskon.
  • Tool untuk validasi prioritas lead.
  • Resource berisi policy diskon.
  • Prompt template untuk follow-up email.

Diagram sederhana:

+------------------------------+ | MCP Host (IDE/Chat AI App) | | - UI Chat | | - Orchestrator | +--------------+---------------+ | | (MCP Client connection) v +------------------------------+ | MCP Server (Python FastMCP) | | Tools: | | - calculate_quote | | - score_lead | | Resources: | | - policy://discount | | Prompts: | | - followup_email | +--------------+---------------+ | v +------------------------------+ | External Systems | | - CRM API (optional) | | - Internal KB (optional) | +------------------------------+

5) Step-by-Step Implementation (Runnable)

Di bagian ini kita bikin server yang bisa langsung jalan.

Step 1 — Buat file server.py

from __future__ import annotations from dataclasses import dataclass from typing import Literal from mcp.server.fastmcp import FastMCP # Inisialisasi server MCP mcp = FastMCP("SalesOpsMCP", json_response=True) @dataclass class QuoteResult: subtotal: float discount_amount: float tax_amount: float total: float currency: str def _round2(x: float) -> float: return float(f"{x:.2f}") @mcp.tool() def calculate_quote( base_price: float, qty: int, discount_pct: float = 0.0, tax_pct: float = 11.0, currency: str = "IDR", ) -> dict: """Hitung total quotation dengan validasi input.""" # Error handling: validasi semua input penting if base_price <= 0: raise ValueError("base_price harus > 0") if qty <= 0: raise ValueError("qty harus > 0") if not (0 <= discount_pct <= 100): raise ValueError("discount_pct harus di range 0..100") if not (0 <= tax_pct <= 100): raise ValueError("tax_pct harus di range 0..100") subtotal = base_price * qty discount_amount = subtotal * (discount_pct / 100) taxable = subtotal - discount_amount tax_amount = taxable * (tax_pct / 100) total = taxable + tax_amount result = QuoteResult( subtotal=_round2(subtotal), discount_amount=_round2(discount_amount), tax_amount=_round2(tax_amount), total=_round2(total), currency=currency, ) return { "subtotal": result.subtotal, "discount_amount": result.discount_amount, "tax_amount": result.tax_amount, "total": result.total, "currency": result.currency, } @mcp.tool() def score_lead( company_size: int, budget_usd: float, urgency: Literal["low", "medium", "high"], ) -> dict: """Scoring lead sederhana untuk prioritas sales.""" if company_size < 1: raise ValueError("company_size minimal 1") if budget_usd < 0: raise ValueError("budget_usd tidak boleh negatif") size_score = min(company_size / 500, 1.0) * 40 budget_score = min(budget_usd / 100000, 1.0) * 40 urgency_score_map = {"low": 8, "medium": 14, "high": 20} urgency_score = urgency_score_map[urgency] score = _round2(size_score + budget_score + urgency_score) if score >= 75: priority = "P1" elif score >= 55: priority = "P2" else: priority = "P3" return {"lead_score": score, "priority": priority} @mcp.resource("policy://discount") def discount_policy() -> str: """Resource berisi policy diskon agar model punya konteks bisnis.""" return ( "Discount Policy v2026: " "- Max standard discount: 20% " "- >20% requires manager approval " "- Tax default Indonesia: 11% " "- Enterprise annual prepay can get additional 5%" ) @mcp.prompt() def followup_email(customer_name: str, pain_point: str) -> str: """Prompt template follow-up email.""" return ( f"Tulis email follow-up profesional ke {customer_name}. " f"Fokus pada pain point: {pain_point}. " "Gunakan gaya ringkas, sopan, dan sertakan CTA untuk jadwal demo 30 menit." ) if __name__ == "__main__": # streamable-http cocok untuk skenario multi-client/remote # Endpoint default MCP biasanya di /mcp mcp.run(transport="streamable-http")

Step 2 — Jalankan server

python server.py

Kalau sukses, server listen di port default (umumnya 8000) dan siap diakses client MCP.

Step 3 — Smoke test cepat dengan Inspector (opsional tapi disarankan)

npx -y @modelcontextprotocol/inspector

Lalu koneksikan ke endpoint server (contoh):

  • http://localhost:8000/mcp

Tes:

  • tools/list
  • tools/callcalculate_quote
  • resources/list + resources/get

Step 4 — Contoh testing call dengan MCP Inspector

Contoh payload untuk calculate_quote:

{ "base_price": 1500000, "qty": 3, "discount_pct": 10, "tax_pct": 11, "currency": "IDR" }

Expected result (kurang lebih):

{ "subtotal": 4500000.0, "discount_amount": 450000.0, "tax_amount": 445500.0, "total": 4495500.0, "currency": "IDR" }

6) Best Practices (Tips dari lapangan)

1. Pisahkan tool “read” vs “write”

  • Tool read-only (aman) dan side-effect (berisiko) sebaiknya dipisah jelas.
  • Ini memudahkan policy approval dan audit.

2. Validasi input seketat mungkin

Jangan percaya input dari model mentah-mentah.

  • range check,
  • type check,
  • allowlist nilai tertentu,
  • fail fast dengan error message jelas.

3. Terapkan prinsip least privilege

Kalau tool akses database/API:

  • gunakan credential minimal,
  • batasi scope token,
  • rotate secret berkala.

4. Observability wajib

Log hal berikut:

  • nama tool,
  • latency,
  • status (success/fail),
  • error class.

Tanpa observability, kamu akan “buta” saat incident.

5. Versioning contract

Saat ubah parameter tool, gunakan strategi kompatibilitas:

  • tambah field baru sebagai optional,
  • hindari breaking change mendadak,
  • dokumentasikan changelog.

7) Common Mistakes (dan cara hindarinya)

Mistake #1: Tool terlalu “powerful” tanpa guardrail

Contoh buruk: satu tool bisa execute shell command arbitrer.

Solusi:

  • pecah jadi tool kecil dengan kemampuan spesifik,
  • gunakan allowlist command/aksi,
  • tambahkan konfirmasi eksplisit untuk aksi destruktif.

Mistake #2: Menganggap resource selalu fresh

Resource bisa stale kalau sumber data berubah cepat.

Solusi:

  • tambahkan metadata timestamp,
  • jelas-kan TTL/cache policy,
  • sediakan tool refresh bila perlu.

Mistake #3: Tidak handle timeout/retry

Di sistem nyata, dependency eksternal bisa lambat.

Solusi:

  • set timeout default,
  • retry dengan backoff untuk error transient,
  • circuit breaker kalau dependency sering gagal.

Mistake #4: Tidak membedakan error user vs system

Kalau semua error dikembalikan generik, debugging jadi lama.

Solusi:

  • error input: ValueError dengan pesan actionable,
  • error internal: log detail internal + pesan user-friendly.

8) Advanced Tips (kalau mau naik level)

A. Lifespan context untuk dependency management

Pakai lifespan/context di FastMCP untuk init resource sekali (DB pool, HTTP client), lalu reuse antar request supaya hemat latency.

B. Multi-transport strategy

  • stdio untuk local developer workflow
  • streamable-http untuk shared environment/team

Dengan begitu kamu dapat DX bagus + deployment fleksibel.

C. Security hardening checklist

  • Auth token untuk remote MCP
  • TLS termination di reverse proxy
  • Rate limiting per client
  • Audit log immutable
  • Input schema validation ketat

D. Structured output untuk downstream automation

Kalau output tool terstruktur (schema konsisten), host AI lebih gampang chaining ke workflow lain (ticketing, notification, reporting).

E. Contract test untuk tools

Bikin test otomatis yang memverifikasi:

  • schema input/output,
  • edge case,
  • error behavior.

Ini penting supaya perubahan tool tidak merusak agent behavior diam-diam.


9) Summary & Next Steps

Kita sudah bahas end-to-end:

  • Kenapa MCP jadi standar penting di era AI agent,
  • Konsep host-client-server dan primitive inti,
  • Implementasi MCP server Python yang runnable,
  • Best practices keamanan + reliability,
  • Kesalahan umum dan upgrade path ke production.

Next steps yang saya sarankan

  1. Tambahkan auth untuk endpoint MCP remote.
  2. Integrasikan 1 dependency nyata (misal CRM sandbox API).
  3. Implement structured logging + dashboard latency.
  4. Buat contract tests untuk semua tool utama.
  5. Rilis v1 internal lalu lakukan dogfooding dengan tim sendiri.

Kalau kamu konsisten di lima langkah ini, MCP server kamu bukan cuma “jalan”, tapi layak dipakai tim secara serius.


10) References


Catatan riset tren (ringkas)

  • GitHub Trending menonjolkan repositori AI tooling/agent infrastructure dan proyek terkait konteks lokal + integrasi model.
  • Diskusi komunitas developer banyak mengarah ke isu “integrasi AI ke sistem nyata” (bukan sekadar prompt).
  • Dokumentasi MCP + SDK lintas bahasa makin lengkap, menandakan adopsi menuju standardisasi lintas tool.