Skip to main content
Starter MCP

Starter MCP Server dengan TypeScript

MCP server stdio dengan dua tool, satu resource, satu prompt, dan smoke test, memakai SDK v2.

Oleh Matthews WongDiperbarui Dicek dengan @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.

9 file

File-filenya

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

src/server.ts3.5 KB
src/server.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;
}
.gitignore25 B
.gitignore
node_modules/
dist/
.env
.mcp.json.example124 B
.mcp.json.example
{
  "mcpServers": {
    "starter": {
      "command": "node",
      "args": ["/absolute/path/to/dist/index.js"]
    }
  }
}
LICENSE1.0 KB
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.md2.3 KB
README.md
# 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.json648 B
package.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.mjs1.2 KB
scripts/smoke.mjs
// 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.ts568 B
src/index.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.json251 B
tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "rootDir": "src",
    "outDir": "dist",
    "strict": true,
    "skipLibCheck": true,
    "types": ["node"]
  },
  "include": ["src"]
}
Cara memakainya

Dari unduh sampai jalan

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.
  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.

Isinya

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.

Perhatikan

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.
Pertanyaan

Yang sering ditanyakan

Jawaban singkat sebelum Anda mengunduhnya.

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 lebih dalam

Pelajari apa yang dikemas file ini

Pelajaran dan artikel gratis di situs ini yang menjelaskan gagasan di baliknya.

Sumber

Sumber primer yang diperiksa pada tanggal riset. Ikuti tautannya untuk versi terbaru.

Lainnya dari toolkit

Ambil ini juga

Starter MCPGratis

Starter MCP Server dengan Python

MCP server stdio dalam satu file dengan dua tool, satu resource, satu prompt, dan smoke test, memakai SDK 2.x.

  • Claude Code
  • Claude Desktop
  • Any MCP client

7 file8.2 KB.zip

TemplateGratis

Template CLAUDE.md untuk Repository Apa Pun

CLAUDE.md awal 70 baris: proyek, stack, perintah, aturan keras, cara memverifikasi pekerjaan, dan yang tidak boleh dilakukan.

  • Claude Code

1 file2.1 KB.md

PromptGratis

Prompt Rencana Sebelum Coding

Prompt perencanaan yang mencakup bisnis, domain, tech design, dan langkah kerja, lalu mendaftar keputusan yang perlu Anda ambil.

  • Claude Code
  • Cursor
  • Claude.ai

1 file2.3 KB.md

Semua item toolkit