Skip to main content
MCP starter

MCP Server Starter in TypeScript

A stdio MCP server with two tools, a resource, a prompt and a smoke test, on the v2 SDK.

By Matthews WongUpdated Checked against @modelcontextprotocol/server 2.4.0

Key takeaway

A small MCP server you can run in two commands and reshape into your own. It registers two tools, one resource and one prompt on the v2 TypeScript SDK, serves them over stdio, and ships a smoke test that connects as a real client, so you know it works before you point Claude Code at it.

9 files

The files

Exactly what the download contains. Read it first, then copy or download.

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"]
}
How to use it

From download to working

Use it when

  • You want Claude to reach your own data or API and need a server that already runs.
  • You know the v1 SDK and want a working example of the v2 package layout.
  • You are teaching MCP and need something small enough to read in ten minutes.
  1. Install and run the smoke test

    Unzip, then run npm install and npm run smoke. The script builds the server, starts it as a child process, lists its tools and calls one. A line starting with ok means the server works on your machine.

  2. Register it with Claude Code

    Run npm run build, then claude mcp add starter -- node followed by the absolute path to dist/index.js. Use the absolute path because the client starts the server from its own working directory. claude mcp list shows whether it connected.

  3. Call a tool from a conversation

    Ask Claude to search your notes for welcome. Claude calls search_notes, asking for approval first if your permission mode requires it, and reads the JSON the tool returns.

  4. Replace the sample data

    Swap the NOTES map in src/server.ts for your database or API, rename the tools, rewrite their descriptions, and update scripts/smoke.mjs to match. Run the smoke test after every change.

What is inside

Why it is written this way

The server is a factory, apart from the transport

src/server.ts builds and returns the server; src/index.ts only serves it over stdio with serveStdio. When you later need HTTP, you add a second entry point and leave every tool untouched.

One read-only tool and one that writes

search_notes carries readOnlyHint, add_note does not. Keeping the two kinds apart lets a client approve reads freely and stop to ask before a write.

Inputs are validated by a schema

Each tool declares a Zod object as its inputSchema. A call with a bad id never reaches your code: the SDK answers with an error result that names the field, which the model can read and correct.

Expected failures are results, not exceptions

A duplicate id returns isError with a plain message. The model sees why the call failed and can choose another id, where a thrown error would tell it nothing useful.

A smoke test that acts like a client

scripts/smoke.mjs uses the official client package to start the built server over stdio, so it exercises the same path Claude Code does. It is the fastest way to tell a broken server from a broken client config.

Watch for

What goes wrong

  • Anything written to stdout breaks the connection, because stdout carries the protocol. Log with console.error, in tools too.
  • This starter targets the v2 packages. Code written for the older single @modelcontextprotocol/sdk package uses different imports, so do not mix examples from both.
  • The notes live in memory and vanish when the process exits. That is deliberate for a starter; connect real storage before you rely on it.
  • It has no authentication, which is fine for a local stdio process. Do not expose it over a network as it is.
Questions

Frequently asked

Short answers before you download it.

What is the difference between @modelcontextprotocol/sdk and @modelcontextprotocol/server?

The single @modelcontextprotocol/sdk package is version 1 of the TypeScript SDK. Version 2 splits it into @modelcontextprotocol/server and @modelcontextprotocol/client and implements the 2026-07-28 revision of the specification. This starter uses the v2 packages.

Do I need an API key or an account to run it?

No. The server and its smoke test run locally with Node.js 20 or newer and no model in the loop. You only need a Claude Code or other MCP client when you want a model to call the tools.

Why does TypeScript complain about Buffer or process?

TypeScript 6 no longer includes @types packages automatically. The starter's tsconfig.json sets types to node for that reason; keep the line if you copy the config into another project.

Can I use it as the base for a production server?

As a base, yes: the structure, validation and error handling carry over. Before production you still need real storage, authentication if it leaves your machine, and tools scoped to the least access the job needs.

Go deeper

Learn what this file packages

Free lessons and articles on this site that explain the ideas behind it.

Sources

Primary sources checked on the research date. Follow them for the current version.

More from the toolkit

Take these too

MCP starterFree

MCP Server Starter in Python

A stdio MCP server in one file with two tools, a resource, a prompt and a smoke test, on the 2.x SDK.

  • Claude Code
  • Claude Desktop
  • Any MCP client

7 files8.2 KB.zip

TemplateFree

CLAUDE.md Template for Any Repository

A 70-line starter CLAUDE.md: project, stack, commands, hard rules, how to verify work and what not to do.

  • Claude Code

1 file2.1 KB.md

PromptFree

Plan Before Code Prompt

A planning prompt that covers business, domain, tech design and steps, then lists the decisions it needs from you.

  • Claude Code
  • Cursor
  • Claude.ai

1 file2.3 KB.md

All toolkit items