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
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.
Persis isi unduhannya. Baca dulu, lalu salin atau unduh.
// 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;
}
node_modules/
dist/
.env
{
"mcpServers": {
"starter": {
"command": "node",
"args": ["/absolute/path/to/dist/index.js"]
}
}
}
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.
# 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`.
{
"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"
}
}
// 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();
}
#!/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");
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "src",
"outDir": "dist",
"strict": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src"]
}
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.
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.
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.
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.
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.
search_notes membawa readOnlyHint, add_note tidak. Memisahkan keduanya memungkinkan client menyetujui pembacaan dengan leluasa dan berhenti untuk bertanya sebelum penulisan.
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.
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.
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.
Jawaban singkat sebelum Anda mengunduhnya.
Pelajaran dan artikel gratis di situs ini yang menjelaskan gagasan di baliknya.
Sumber primer yang diperiksa pada tanggal riset. Ikuti tautannya untuk versi terbaru.
MCP server stdio dalam satu file dengan dua tool, satu resource, satu prompt, dan smoke test, memakai SDK 2.x.
7 file8.2 KB.zip
CLAUDE.md awal 70 baris: proyek, stack, perintah, aturan keras, cara memverifikasi pekerjaan, dan yang tidak boleh dilakukan.
1 file2.1 KB.md
Prompt perencanaan yang mencakup bisnis, domain, tech design, dan langkah kerja, lalu mendaftar keputusan yang perlu Anda ambil.
1 file2.3 KB.md