# Boilerplate MCP Server Python Gratis yang Sudah Dites

> Boilerplate MCP server Python gratis dengan SDK 2.x: dua tool, resource, prompt, dan smoke test lewat stdio. Jalankan dengan uv, sambungkan ke Claude Code.

URL: https://www.matthewswong.com/id/toolkit/mcp-server-python-starter/

- Author: Matthews Wong (https://www.matthewswong.com/id/about/)
- Diperbarui: 13 November 2026
- Diperiksa terhadap: mcp 2.3.0 (Python SDK)

> **Poin utama:** MCP server kecil dalam satu file Python yang jalan dengan dua perintah dan mudah diubah menjadi milik Anda. Ia mendaftarkan dua tool, satu resource, dan satu prompt di SDK 2.x, melayaninya lewat stdio, dan menyertakan smoke test yang terhubung sebagai client sungguhan, jadi Anda tahu server ini berfungsi sebelum menyambungkannya ke Claude Code.

- Jenis: Starter MCP
- Bisa dipakai di: Claude Code, Claude Desktop, Any MCP client, Python 3.10+
- Unduh: [mcp-server-python-starter.zip](https://www.matthewswong.com/downloads/toolkit/mcp-server-python-starter.zip) (8.2 KB)
- Lisensi: Bebas dipakai, diubah, dan dibagikan, termasuk untuk pekerjaan.

## File-filenya

Persis isi unduhannya. Baca dulu, lalu salin atau unduh.

### server.py

```python
"""A minimal MCP server over stdio.

A client such as Claude Code starts this file as a child process and talks
to it over stdin and stdout. stdout carries the protocol, so never print()
here: one stray line corrupts the stream. Log to stderr instead.
"""

import json
import logging
import re
import sys

from mcp.server.mcpserver import MCPServer
from mcp.server.mcpserver.exceptions import ToolError

logging.basicConfig(stream=sys.stderr, level=logging.INFO)
log = logging.getLogger("starter")

mcp = MCPServer("starter", version="0.1.0")

# Replace this with your real data source: a database, an API, a file.
NOTES: dict[str, str] = {
    "welcome": "This note ships with the starter. Replace NOTES with real data.",
}

NOTE_ID = re.compile(r"^[a-z0-9-]{1,40}$")
MAX_NOTE_CHARS = 2000


@mcp.tool()
def search_notes(query: str) -> str:
    """Find notes whose id or text contains the query (case-insensitive).

    Returns matching ids with their text. Use before add_note to avoid
    duplicates.
    """
    needle = query.lower()
    matches = [
        {"id": note_id, "text": text}
        for note_id, text in NOTES.items()
        if needle in f"{note_id} {text}".lower()
    ]
    return json.dumps(matches, indent=2)


@mcp.tool()
def add_note(id: str, text: str) -> str:
    """Store a new note under a short id. Fails if the id is already taken.

    The id is lowercase letters, digits and hyphens, at most 40 characters.
    """
    # ToolError is for a failure you saw coming: the model receives the
    # message and can recover. Any other exception counts as a crash, and
    # the model is told only that the tool failed.
    if not NOTE_ID.match(id):
        raise ToolError("id must match ^[a-z0-9-]{1,40}$")
    if not text or len(text) > MAX_NOTE_CHARS:
        raise ToolError(f"text must be 1 to {MAX_NOTE_CHARS} characters")
    if id in NOTES:
        raise ToolError(f'A note with id "{id}" already exists.')
    NOTES[id] = text
    return f'Saved note "{id}".'


@mcp.resource("notes://index", mime_type="text/plain")
def notes_index() -> str:
    """The id of every stored note, one per line."""
    return "\n".join(NOTES)


@mcp.prompt()
def summarize_notes(topic: str) -> str:
    """Ask for a short summary of every note on one topic."""
    return (
        f'Search the notes for "{topic}" and summarize what they say in five '
        "bullet points. Name the note id behind each point."
    )


if __name__ == "__main__":
    log.info("MCP server ready on stdio")
    mcp.run()
```

### .gitignore

```
.venv/
__pycache__/
.env
```

### .mcp.json.example

```
{
  "mcpServers": {
    "starter": {
      "command": "uv",
      "args": [
        "run",
        "--directory",
        "/absolute/path/to/this/folder",
        "python",
        "server.py"
      ]
    }
  }
}
```

### LICENSE

```
MIT License

Copyright (c) 2026 Matthews Wong

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

### README.md

````markdown
# MCP server starter (Python)

A minimal Model Context Protocol server over stdio: two tools, one resource,
one prompt, and a smoke test that talks to it the way a real client does.

Built on the official `mcp` package, 2.x, where the high-level server class
is `MCPServer` (it was `FastMCP` in 1.x). Needs Python 3.10 or newer and
[uv](https://docs.astral.sh/uv/).

## Run it

```bash
uv sync
uv run python smoke.py    # starts the server, lists its tools, calls one
```

`ok: 2 tools, search and duplicate check passed` means the server works.

## Connect it to Claude Code

Register the server with the absolute path to this folder, because the client
starts the server from its own working directory.

```bash
claude mcp add starter -- uv run --directory /absolute/path/to/this/folder python server.py
claude mcp list
```

To share the server with everyone who clones a repository, copy
`.mcp.json.example` to `.mcp.json` at that repository's root and fix the path.

Then ask Claude: "search my notes for welcome".

## What is where

| File        | What it does                                                 |
| ----------- | ------------------------------------------------------------ |
| `server.py` | The tools, the resource and the prompt, served over stdio    |
| `smoke.py`  | Starts the server as a client would and checks what it finds |

## Make it yours

1. Replace the `NOTES` dict in `server.py` with your real data source.
2. Rename the tools and rewrite their docstrings. The docstring becomes the
   tool description, which is what the model reads to decide whether to call
   it, so say what it returns and when to use it.
3. Type every parameter. The type hints become the input schema.
4. Update `smoke.py` to the new tool names and run it again.

## Rules that save an afternoon

- **Never print to stdout.** stdout carries the protocol. Log to stderr.
- **Raise `ToolError` for failures you expect.** The model receives your
  message and can recover. Any other exception is treated as a crash, and the
  model is told only that the tool failed.
- **Validate every input.** The schema is the only thing between the model's
  guess and your data.
- **Keep secrets in the environment**, never in the code or in `.mcp.json`.

## License

MIT. See `LICENSE`.
````

### pyproject.toml

```toml
[project]
name = "mcp-server-starter"
version = "0.1.0"
description = "A minimal MCP server over stdio: two tools, one resource, one prompt, and a smoke test."
requires-python = ">=3.10"
dependencies = ["mcp>=2.3,<3"]
```

### smoke.py

```python
"""Smoke test: start the server the way a real client does, list what it
offers and call one tool. Exits non-zero when anything is off.

    uv run python smoke.py
"""

import asyncio
import sys

from mcp import Client, StdioServerParameters


async def main() -> None:
    server = StdioServerParameters(command=sys.executable, args=["server.py"])
    async with Client(server) as client:
        tools = await client.list_tools()
        names = sorted(tool.name for tool in tools.tools)
        assert names == ["add_note", "search_notes"], names

        found = await client.call_tool("search_notes", {"query": "welcome"})
        assert not found.is_error
        assert "welcome" in found.content[0].text

        duplicate = await client.call_tool(
            "add_note", {"id": "welcome", "text": "again"}
        )
        assert duplicate.is_error
        assert "already exists" in duplicate.content[0].text

        print(f"ok: {len(names)} tools, search and duplicate check passed")


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

## Pakai saat

- Anda ingin Claude menjangkau data atau API Anda sendiri dari Python dan butuh server yang sudah jalan.
- Anda mengenal FastMCP dari SDK 1.x dan ingin contoh yang berfungsi untuk import 2.x.
- Anda mengajarkan MCP dan butuh server yang cukup pendek untuk dibaca sekali duduk.

## Dari unduh sampai jalan

1. **Instal dan jalankan smoke test.** Ekstrak, lalu jalankan uv sync dan uv run python smoke.py. Skrip ini menjalankan server sebagai child process, mendaftar tool-nya, memanggil salah satunya, dan memeriksa bahwa id duplikat ditolak. Baris yang diawali ok berarti server berfungsi di mesin Anda.
2. **Daftarkan ke Claude Code.** Jalankan claude mcp add starter -- uv run --directory diikuti path absolut ke foldernya, lalu python server.py. Gunakan path absolut karena client menjalankan server dari working directory-nya sendiri. claude mcp list menunjukkan apakah server tersambung.
3. **Panggil tool dari percakapan.** Minta Claude mencari kata welcome di catatan Anda. Claude memanggil search_notes lalu membaca JSON yang dikembalikan tool.
4. **Ganti data contohnya.** Ganti dict NOTES di server.py dengan database atau API Anda, ubah nama tool, tulis ulang docstring-nya, lalu sesuaikan smoke.py. Jalankan smoke test setiap kali ada perubahan.
5. **Bagikan lewat repositori.** Salin .mcp.json.example menjadi .mcp.json di root repositori lalu perbaiki path-nya. Setiap orang yang meng-clone repositori itu akan diminta menyetujui server yang sama.

## Kenapa ditulis seperti ini

- **Satu file, dengan import 2.x.** server.py mengimpor MCPServer dari mcp.server.mcpserver, nama 2.x untuk class yang di 1.x bernama FastMCP. Tool, resource, dan prompt adalah fungsi biasa di bawah decorator, dan mcp.run() melayaninya lewat stdio secara default.
- **Docstring dan type hint adalah kontraknya.** Docstring menjadi deskripsi tool, yaitu yang dibaca model untuk memutuskan apakah akan memanggilnya. Type hint menjadi input schema. Karena itu setiap docstring menyebut apa yang dikembalikan tool dan kapan memakainya.
- **Kegagalan yang terduga melempar ToolError.** add_note melempar ToolError untuk id yang salah, teks kosong, atau duplikat. Client menerima hasil error berisi pesan itu, sehingga model melihat alasan kegagalannya dan bisa memilih id lain. Exception lain dianggap crash, dan model hanya diberi tahu bahwa tool gagal.
- **Log ditulis ke stderr.** stdout membawa protokolnya, jadi starter ini mengatur logging agar menulis ke stderr dan tidak pernah memanggil print. Satu baris nyasar di stdout merusak alirannya.
- **Smoke test yang bertindak seperti client.** smoke.py memakai Client dan StdioServerParameters dari paket mcp yang sama untuk menjalankan server.py lewat stdio, jadi ia menguji jalur yang ditempuh client sungguhan. Ini cara tercepat membedakan server yang rusak dari konfigurasi client yang salah.

## Yang sering salah

- Apa pun yang dicetak ke stdout merusak koneksi, karena stdout membawa protokolnya. Tulis log ke stderr, termasuk di dalam tool.
- Starter ini menargetkan mcp 2.x. Contoh yang mengimpor FastMCP dari mcp.server.fastmcp ditulis untuk 1.x, dan import itu memunculkan ModuleNotFoundError di 2.x.
- Catatan disimpan di memori dan hilang saat proses berhenti. Itu disengaja untuk sebuah starter; sambungkan penyimpanan sungguhan sebelum mengandalkannya.
- Starter ini tanpa autentikasi, dan itu wajar untuk proses stdio lokal. Jangan mengeksposnya ke jaringan dalam kondisi seperti ini.

## FAQ

### Apa beda FastMCP dan MCPServer di SDK Python?

Keduanya adalah class server tingkat tinggi yang sama dengan dua nama. Di mcp 1.x namanya FastMCP, diimpor dari mcp.server.fastmcp. Di 2.x namanya MCPServer, diimpor dari mcp.server.mcpserver, dan path import lama memunculkan ModuleNotFoundError yang menunjuk ke panduan migrasi.

### Apakah perlu API key atau akun untuk menjalankannya?

Tidak. Server dan smoke test-nya berjalan lokal dengan Python 3.10 atau lebih baru dan uv, tanpa model di tengahnya. Anda baru butuh Claude Code atau client MCP lain saat ingin model memanggil tool-nya.

### Kenapa melempar ToolError, bukan exception Python biasa?

ToolError berubah menjadi hasil error yang pesannya bisa dibaca model, sehingga model dapat memperbaiki argumennya lalu mencoba lagi. Exception lain dianggap crash, dan model hanya diberi tahu bahwa tool gagal. Spesifikasi MCP menarik garis yang sama: tool execution error membawa umpan balik yang bisa ditindaklanjuti model.

### Bisakah ini jadi dasar untuk server production?

Sebagai dasar, bisa: struktur, input bertipe, dan penanganan error-nya tetap terpakai. Sebelum production Anda tetap butuh penyimpanan sungguhan, autentikasi bila server keluar dari mesin Anda, dan tool yang dibatasi pada akses sekecil mungkin.

## Pelajari apa yang dikemas file ini

- Pelajaran gratis: [Apa Itu MCP Server? Begini Perjalanan Satu Tool Call](https://www.matthewswong.com/id/learn/ai-agents-mcp/what-is-mcp-how-a-tool-call-travels/)
- Pelajaran gratis: [Cara Membatasi Akses MCP Server: Read-Only dan Toolset](https://www.matthewswong.com/id/learn/ai-agents-mcp/scope-an-mcp-server-read-only-toolsets/)
- Pelajaran gratis: [Menambah MCP Server di Claude Code: Scope dan Izin](https://www.matthewswong.com/id/learn/claude-code-tips/add-mcp-server-claude-code/)
- [Membangun MCP Server dari Nol: Panduan Praktis untuk Developer](https://www.matthewswong.com/id/blog/mcp-server-development-guide/)
- [Primitif MCP: Tools, Resources, dan Prompts](https://www.matthewswong.com/id/blog/mcp-tools-resources-prompts-primitives/)
- [Transport MCP: stdio vs Streamable HTTP](https://www.matthewswong.com/id/blog/mcp-transports-stdio-vs-http/)
- [Checklist Keamanan MCP Server untuk Developer](https://www.matthewswong.com/id/blog/mcp-server-security-checklist/)

## Sumber

- [MCP Python SDK: migration guide, v1 to v2](https://py.sdk.modelcontextprotocol.io/v2/migration/)
- [Model Context Protocol specification 2026-07-28: tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
- [Claude Code docs: connect Claude Code to tools via MCP](https://code.claude.com/docs/en/mcp)

[Semua item toolkit](https://www.matthewswong.com/id/toolkit/)

---

- HTML version: https://www.matthewswong.com/id/toolkit/mcp-server-python-starter/
- English: https://www.matthewswong.com/en/toolkit/mcp-server-python-starter/
- Site index for agents: https://www.matthewswong.com/llms.txt
- Sitemap: https://www.matthewswong.com/sitemap.xml
- API description (OpenAPI): https://www.matthewswong.com/openapi.json
