# Boilerplate MCP Server TypeScript Gratis yang Sudah Dites

> Boilerplate MCP server TypeScript gratis dengan SDK v2: dua tool, resource, prompt, dan smoke test lewat stdio. Unduh lalu sambungkan ke Claude Code.

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

- Author: Matthews Wong (https://www.matthewswong.com/id/about/)
- Diperbarui: 13 November 2026
- Diperiksa terhadap: @modelcontextprotocol/server 2.4.0

> **Poin utama:** MCP server kecil yang jalan dengan dua perintah dan mudah diubah menjadi milik Anda. Ia mendaftarkan dua tool, satu resource, dan satu prompt di SDK TypeScript v2, 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, Node.js 20+
- Unduh: [mcp-server-typescript-starter.zip](https://www.matthewswong.com/downloads/toolkit/mcp-server-typescript-starter.zip) (11.1 KB)
- Lisensi: Bebas dipakai, diubah, dan dibagikan, termasuk untuk pekerjaan.

## File-filenya

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

### src/server.ts

```ts
// Everything the server offers is registered here, in one factory.
// Keeping it separate from the transport (src/index.ts) means the same
// server can later be served over HTTP without touching a tool.
import { McpServer } from "@modelcontextprotocol/server";
import { z } from "zod";

const SERVER_NAME = "starter";
const SERVER_VERSION = "0.1.0";

/** Replace this with your real data source: a database, an API, a file. */
const NOTES = new Map<string, string>([
  ["welcome", "This note ships with the starter. Replace NOTES with real data."],
]);

export function createServer(): McpServer {
  const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });

  // A read-only tool. The description is what the model reads to decide
  // whether to call it, so say what it returns and when to use it.
  server.registerTool(
    "search_notes",
    {
      title: "Search notes",
      description:
        "Find notes whose id or text contains the query. Returns matching ids with their text. Use before add_note to avoid duplicates.",
      inputSchema: z.object({
        query: z.string().min(1).describe("Text to look for, case-insensitive"),
      }),
      annotations: { readOnlyHint: true },
    },
    async ({ query }) => {
      const needle = query.toLowerCase();
      const matches = [...NOTES.entries()]
        .filter(([id, text]) => `${id} ${text}`.toLowerCase().includes(needle))
        .map(([id, text]) => ({ id, text }));
      return {
        content: [{ type: "text", text: JSON.stringify(matches, null, 2) }],
      };
    },
  );

  // A tool that changes state. Validate hard, and report a failure as a
  // result with isError so the model can read the message and recover.
  server.registerTool(
    "add_note",
    {
      title: "Add a note",
      description:
        "Store a new note under a short id. Fails if the id is already taken.",
      inputSchema: z.object({
        id: z
          .string()
          .regex(/^[a-z0-9-]{1,40}$/)
          .describe("Lowercase letters, digits and hyphens, at most 40 characters"),
        text: z.string().min(1).max(2000).describe("The note body"),
      }),
      annotations: { readOnlyHint: false, destructiveHint: false },
    },
    async ({ id, text }) => {
      if (NOTES.has(id)) {
        return {
          isError: true,
          content: [
            { type: "text", text: `A note with id "${id}" already exists.` },
          ],
        };
      }
      NOTES.set(id, text);
      return { content: [{ type: "text", text: `Saved note "${id}".` }] };
    },
  );

  // A resource: data the client can read by URI without calling a tool.
  server.registerResource(
    "notes-index",
    "notes://index",
    {
      title: "Notes index",
      description: "The id of every stored note, one per line.",
      mimeType: "text/plain",
    },
    async (uri) => ({
      contents: [{ uri: uri.href, text: [...NOTES.keys()].join("\n") }],
    }),
  );

  // A prompt: a reusable message template the user can pick in the client.
  server.registerPrompt(
    "summarize_notes",
    {
      title: "Summarize notes",
      description: "Ask for a short summary of every note on one topic.",
      argsSchema: z.object({ topic: z.string().describe("What to summarize") }),
    },
    ({ topic }) => ({
      messages: [
        {
          role: "user",
          content: {
            type: "text",
            text: `Search the notes for "${topic}" and summarize what they say in five bullet points. Name the note id behind each point.`,
          },
        },
      ],
    }),
  );

  return server;
}
```

### .gitignore

```
node_modules/
dist/
.env
```

### .mcp.json.example

```
{
  "mcpServers": {
    "starter": {
      "command": "node",
      "args": ["/absolute/path/to/dist/index.js"]
    }
  }
}
```

### 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 (TypeScript)

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 `@modelcontextprotocol/server` 2.x. Needs Node.js 20 or newer.

## Run it

```bash
npm install
npm run smoke    # builds, 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

Build once, then register the built file. Use the absolute path, because the
client starts the server from its own working directory.

```bash
npm run build
claude mcp add starter -- node /absolute/path/to/dist/index.js
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                                                    |
| ------------------- | --------------------------------------------------------------- |
| `src/server.ts`     | Registers the tools, the resource and the prompt in one factory |
| `src/index.ts`      | Serves that factory over stdio                                  |
| `scripts/smoke.mjs` | Starts the built server as a client would and checks it         |

## Make it yours

1. Replace the `NOTES` map in `src/server.ts` with your real data source.
2. Rename the tools and rewrite their descriptions. The description is what
   the model reads to decide whether to call a tool, so say what it returns
   and when to use it.
3. Keep read-only tools and tools that change something separate, and mark
   them with `readOnlyHint`. Clients use the hint when asking for approval.
4. Update `scripts/smoke.mjs` to the new tool names and run `npm run smoke`.

## Rules that save an afternoon

- **Never write to stdout.** stdout carries the protocol. Use `console.error`.
- **Report expected failures as results.** Return `isError: true` with a clear
  message so the model can read it and recover. Throw only for real crashes.
- **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`.
````

### package.json

```json
{
  "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.",
  "type": "module",
  "private": true,
  "engines": {
    "node": ">=20"
  },
  "scripts": {
    "dev": "tsx src/index.ts",
    "build": "tsc",
    "start": "node dist/index.js",
    "smoke": "npm run build && node scripts/smoke.mjs"
  },
  "dependencies": {
    "@modelcontextprotocol/server": "^2.4.0",
    "zod": "^4.6.0"
  },
  "devDependencies": {
    "@modelcontextprotocol/client": "^2.4.0",
    "@types/node": "^22.0.0",
    "tsx": "^4.20.0",
    "typescript": "^6.0.0"
  }
}
```

### scripts/smoke.mjs

```js
// Smoke test: start the built server the way a real client does, list what
// it offers and call one tool. Exits non-zero when anything is off.
//
//   npm run smoke
import assert from "node:assert/strict";

import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";

const transport = new StdioClientTransport({
  command: process.execPath,
  args: ["dist/index.js"],
});
const client = new Client({ name: "smoke-test", version: "0.1.0" });

await client.connect(transport);
try {
  const { tools } = await client.listTools();
  const names = tools.map((tool) => tool.name).sort();
  assert.deepEqual(names, ["add_note", "search_notes"]);

  const result = await client.callTool({
    name: "search_notes",
    arguments: { query: "welcome" },
  });
  assert.equal(result.isError ?? false, false);
  assert.match(result.content[0].text, /welcome/);

  const duplicate = await client.callTool({
    name: "add_note",
    arguments: { id: "welcome", text: "again" },
  });
  assert.equal(duplicate.isError, true);

  console.log(`ok: ${names.length} tools, search and duplicate check passed`);
} finally {
  await client.close();
}
```

### src/index.ts

```ts
#!/usr/bin/env node
// The stdio entry point. 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 console.log here or in a tool:
// one stray line corrupts the stream. Write logs to stderr instead.
import { serveStdio } from "@modelcontextprotocol/server/stdio";

import { createServer } from "./server.js";

serveStdio(createServer, {
  onerror: (error) => console.error("[starter] transport error:", error),
});

console.error("[starter] MCP server ready on stdio");
```

### tsconfig.json

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src"]
}
```

## Pakai saat

- Anda ingin Claude menjangkau data atau API Anda sendiri dan butuh server yang sudah jalan.
- Anda mengenal SDK v1 dan ingin contoh yang berfungsi untuk susunan paket v2.
- Anda mengajarkan MCP dan butuh contoh yang cukup kecil untuk dibaca dalam sepuluh menit.

## Dari unduh sampai jalan

1. **Instal dan jalankan smoke test.** Ekstrak, lalu jalankan npm install dan npm run smoke. Skrip ini mem-build server, menjalankannya sebagai child process, mendaftar tool-nya, dan memanggil salah satunya. Baris yang diawali ok berarti server berfungsi di mesin Anda.
2. **Daftarkan ke Claude Code.** Jalankan npm run build, lalu claude mcp add starter -- node diikuti path absolut ke dist/index.js. 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, dengan meminta persetujuan lebih dulu bila mode izin Anda mengharuskannya, lalu membaca JSON yang dikembalikan tool.
4. **Ganti data contohnya.** Ganti map NOTES di src/server.ts dengan database atau API Anda, ubah nama tool, tulis ulang deskripsinya, lalu sesuaikan scripts/smoke.mjs. Jalankan smoke test setiap kali ada perubahan.

## Kenapa ditulis seperti ini

- **Server berupa factory, terpisah dari transport.** src/server.ts membuat dan mengembalikan server; src/index.ts hanya melayaninya lewat stdio dengan serveStdio. Saat nanti butuh HTTP, Anda cukup menambah entry point kedua tanpa menyentuh satu tool pun.
- **Satu tool read-only dan satu yang menulis.** search_notes membawa readOnlyHint, add_note tidak. Memisahkan keduanya memungkinkan client menyetujui pembacaan dengan leluasa dan berhenti untuk bertanya sebelum penulisan.
- **Input divalidasi oleh schema.** Setiap tool mendeklarasikan objek Zod sebagai inputSchema. Pemanggilan dengan id yang salah tidak pernah sampai ke kode Anda: SDK menjawab dengan hasil error yang menyebut field-nya, sehingga model bisa membaca dan memperbaikinya.
- **Kegagalan yang terduga adalah hasil, bukan exception.** Id yang duplikat mengembalikan isError dengan pesan yang jelas. Model melihat alasan kegagalannya dan bisa memilih id lain, sedangkan error yang dilempar tidak memberi tahu apa pun yang berguna.
- **Smoke test yang bertindak seperti client.** scripts/smoke.mjs memakai paket client resmi untuk menjalankan server hasil build lewat stdio, jadi ia menguji jalur yang sama dengan Claude Code. Ini cara tercepat membedakan server yang rusak dari konfigurasi client yang salah.

## Yang sering salah

- Apa pun yang ditulis ke stdout merusak koneksi, karena stdout membawa protokolnya. Tulis log dengan console.error, termasuk di dalam tool.
- Starter ini menargetkan paket v2. Kode untuk paket tunggal @modelcontextprotocol/sdk yang lama memakai import berbeda, jadi jangan mencampur contoh dari keduanya.
- 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 @modelcontextprotocol/sdk dan @modelcontextprotocol/server?

Paket tunggal @modelcontextprotocol/sdk adalah versi 1 dari SDK TypeScript. Versi 2 memecahnya menjadi @modelcontextprotocol/server dan @modelcontextprotocol/client serta mengimplementasikan revisi spesifikasi 2026-07-28. Starter ini memakai paket v2.

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

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

### Kenapa TypeScript mengeluhkan Buffer atau process?

TypeScript 6 tidak lagi menyertakan paket @types secara otomatis. Karena itu tsconfig.json di starter ini mengatur types ke node; pertahankan baris itu bila Anda menyalin konfigurasinya ke proyek lain.

### Bisakah ini jadi dasar untuk server production?

Sebagai dasar, bisa: struktur, validasi, 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 di TypeScript: Panduan](https://www.matthewswong.com/id/blog/build-mcp-server-typescript-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 TypeScript SDK v2: documentation](https://ts.sdk.modelcontextprotocol.io/v2/)
- [MCP TypeScript SDK v2: upgrading from v1](https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2)
- [Model Context Protocol specification 2026-07-28: tools](https://modelcontextprotocol.io/specification/2026-07-28/server/tools)
- [Claude Code docs: connect 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-typescript-starter/
- English: https://www.matthewswong.com/en/toolkit/mcp-server-typescript-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
