TypeScript MCP Server Generator

TypeScript MCP Server Generator

Guides an AI agent to create a TypeScript MCP server project with the official SDK, tools, Vitest tests and client configuration, step by step.

Skill files2 files

references/

SKILL.md224 lines
1
---
2
name: typescript-mcp-server-generator
3
description: 'Use this skill when the user wants to create a new Model Context Protocol (MCP) server in TypeScript or Node.js. Also use it to expose TypeScript code, an API, or a database to AI clients as MCP tools. The skill makes an npm project with the MCP TypeScript SDK 2.x, Vitest tests, and client configuration. Do not use it for an MCP client or for a server in another language.'
4
compatibility: 'Node.js 22.12 or later on an LTS line (22, 24, or 26), npm, and network access to download packages. The minimum Node.js versions for the MCP Inspector are 22.23.4, 24.22.1, and 26.12.1, one for each LTS line.'
5
---
6
7
# TypeScript MCP Server Generator
8
9
Create a Model Context Protocol (MCP) server in TypeScript with the official [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) 2.x. SDK 2.4.x implements the MCP specification revision [2026-07-28](https://modelcontextprotocol.io/specification/2026-07-28). A client enables it with `versionNegotiation`. By default, a client still uses the 2025 `initialize` handshake.
10
11
## Workflow
12
13
Copy this checklist. Use it to track your progress:
14
15
- [ ] Step 1: Create the project.
16
- [ ] Step 2: Write the server.
17
- [ ] Step 3: Write the tests.
18
- [ ] Step 4: Build until the tests pass.
19
- [ ] Step 5: Configure the client.
20
21
### Step 1: Create the project
22
23
Make this layout:
24
25
```text
26
project-name/
27
├── package.json
28
├── tsconfig.json
29
├── src/index.ts
30
└── test/server.test.ts
31
```
32
33
Write `package.json`:
34
35
```json
36
{
37
"name": "my-mcp-server",
38
"version": "0.1.0",
39
"type": "module",
40
"bin": { "my-mcp-server": "dist/index.js" },
41
"scripts": {
42
"build": "tsc",
43
"dev": "tsx src/index.ts",
44
"start": "node dist/index.js",
45
"test": "vitest run"
46
}
47
}
48
```
49
50
Write `tsconfig.json`:
51
52
```json
53
{
54
"compilerOptions": {
55
"target": "es2022",
56
"module": "nodenext",
57
"moduleResolution": "nodenext",
58
"strict": true,
59
"types": ["node"],
60
"rootDir": "src",
61
"outDir": "dist"
62
},
63
"include": ["src"]
64
}
65
```
66
67
Install the dependencies:
68
69
```bash
70
npm install @modelcontextprotocol/server zod@^4.2
71
npm install -D typescript@^7.0.2 @types/node@^22 tsx vitest@^5.1.2 @modelcontextprotocol/client
72
```
73
74
- `@modelcontextprotocol/server` contains `McpServer` and the stdio entry `@modelcontextprotocol/server/stdio`.
75
- `@modelcontextprotocol/client` is only for the tests.
76
- `tsx` runs the server during development. Do not use Node.js native TypeScript execution.
77
78
### Step 2: Write the server
79
80
Start from this template in `src/index.ts`:
81
82
```typescript
83
#!/usr/bin/env node
84
import { McpServer } from '@modelcontextprotocol/server';
85
import { serveStdio } from '@modelcontextprotocol/server/stdio';
86
import * as z from 'zod/v4';
87
88
function createServer(): McpServer {
89
const server = new McpServer({ name: 'demo', version: '0.1.0' });
90
91
server.registerTool(
92
'divide',
93
{
94
title: 'Divide',
95
description: 'Divide a by b.',
96
inputSchema: z.object({
97
a: z.number().describe('Dividend'),
98
b: z.number().describe('Divisor')
99
}),
100
outputSchema: z.object({ result: z.number() })
101
},
102
async ({ a, b }) => {
103
if (b === 0) {
104
return { content: [{ type: 'text', text: 'b must not be zero.' }], isError: true };
105
}
106
const result = a / b;
107
return {
108
content: [{ type: 'text', text: JSON.stringify({ result }) }],
109
structuredContent: { result }
110
};
111
}
112
);
113
114
return server;
115
}
116
117
void serveStdio(createServer);
118
console.error('demo MCP server running on stdio');
119
```
120
121
Then change the template to match the request of the user:
122
123
1. Replace the `divide` tool with the tools that the user asks for.
124
2. Give each tool a zod `inputSchema` (`z.object({ ... })`), a `title`, and a `description`. The description tells the model when to use the tool.
125
3. When the client must get machine-readable data, add an `outputSchema`. Return the data in `structuredContent`. Also return the same data as serialized JSON in a text block for older clients.
126
4. Mark a read-only tool with `annotations: { readOnlyHint: true }`.
127
5. Add resources (`registerResource`) and prompts (`registerPrompt`) only when the user asks for them.
128
129
Use stdio by default. Read [references/streamable-http.md](references/streamable-http.md) only when the user asks for a remote server or HTTP.
130
131
### Step 3: Write the tests
132
133
The test starts the built server as a subprocess. It connects to the server with the SDK client. Write a test for each tool and for each error result in `test/server.test.ts`:
134
135
```typescript
136
import { Client } from '@modelcontextprotocol/client';
137
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
138
import { afterAll, beforeAll, expect, test } from 'vitest';
139
140
let client: Client;
141
142
beforeAll(async () => {
143
client = new Client({ name: 'test-client', version: '1.0.0' }, { versionNegotiation: { mode: { pin: '2026-07-28' } } });
144
await client.connect(new StdioClientTransport({ command: process.execPath, args: ['dist/index.js'] }));
145
});
146
147
afterAll(async () => {
148
await client.close();
149
});
150
151
test('negotiates the 2026-07-28 revision', () => {
152
expect(client.getNegotiatedProtocolVersion()).toBe('2026-07-28');
153
});
154
155
test('divide', async () => {
156
const result = await client.callTool({ name: 'divide', arguments: { a: 6, b: 3 } });
157
expect(result.structuredContent).toEqual({ result: 2 });
158
});
159
160
test('divide by zero', async () => {
161
const result = await client.callTool({ name: 'divide', arguments: { a: 1, b: 0 } });
162
expect(result.isError).toBe(true);
163
expect(JSON.stringify(result.content)).toContain('must not be zero');
164
});
165
```
166
167
- For an HTTP server, use the test setup in [references/streamable-http.md](references/streamable-http.md).
168
- The test runs `dist/index.js`. Run `npm run build` before `npm test`.
169
- `process.execPath` is the `node` command that runs the tests. Do not use the `node` command from `PATH`.
170
- The test uses the real stdio transport and the real JSON-RPC messages.
171
- The `pin` option makes the client use the revision 2026-07-28. Without it, the client uses the 2025 handshake.
172
173
### Step 4: Build until the tests pass
174
175
1. Run `npm run build && npm test`. This command compiles the code to `dist/` and runs the tests.
176
2. If a test or the compiler fails, read the error. Fix the server or the test.
177
3. Run `npm run build && npm test` again.
178
4. Continue only when the build and all tests pass.
179
180
### Step 5: Configure the client
181
182
For VS Code, write `.vscode/mcp.json`:
183
184
```json
185
{
186
"servers": {
187
"demo": {
188
"type": "stdio",
189
"command": "node",
190
"args": ["/absolute/path/to/project/dist/index.js"]
191
}
192
}
193
}
194
```
195
196
For Claude Desktop, put the same `command` and `args` in `claude_desktop_config.json`, below the `mcpServers` key.
197
198
For an HTTP server, use the client configuration in [references/streamable-http.md](references/streamable-http.md).
199
200
Tell the user these facts:
201
202
- `node dist/index.js` starts the stdio server. The server waits for a host on stdin. The logs go to stderr.
203
- To test the server manually, run `npx @modelcontextprotocol/inspector node dist/index.js`. The minimum Node.js versions for the MCP Inspector are 22.23.4, 24.22.1, and 26.12.1, one for each LTS line.
204
205
## Gotchas
206
207
SDK 2.x changed many patterns of the v1 package `@modelcontextprotocol/sdk`. Do not copy examples from v1. To update an existing server, run `npx @modelcontextprotocol/codemod@latest v1-to-v2 .`. Then search for `@mcp-codemod-error` markers. Read the [upgrade guide](https://ts.sdk.modelcontextprotocol.io/v2/migration/upgrade-to-v2.html) for the full list.
208
209
- Use the focused v2 packages. Do not install `@modelcontextprotocol/sdk`. The SDK removed the SSE server transport and the WebSocket client transport. The frozen copy of the old SSE code is only in `@modelcontextprotocol/server-legacy`.
210
- The SDK does not support Zod 3. Use `zod@^4.2` and give schemas as `z.object({ ... })`. The raw shape form `{ name: z.string() }` is deprecated.
211
- Use `registerTool()`, `registerResource()`, and `registerPrompt()`. The variadic `tool()` methods do not exist.
212
- If a tool has an `outputSchema`, return `structuredContent` in each successful result.
213
- Write `completable(z.string(), callback).optional()`. Put `.optional()` on the outside.
214
- Return a result with `isError: true` for an error that the model must read. The v2 error classes are `ProtocolError`, `SdkError`, and `SdkHttpError` (with `.status`). `McpError` and `StreamableHTTPError` do not exist.
215
- In a stdio server, stdout is the protocol channel. Do not call `console.log()`. Use `console.error()`.
216
- There are no sessions and no `initialize` handshake on 2026-07-28. Per-call state lives in handles that the server makes and the model passes as tool arguments.
217
- The SDK answers `server/discover`, fills `resultType`, and routes `subscriptions/listen`. Do not write them manually.
218
- Do not use `ctx.mcpReq.elicitInput()`. It throws on a 2026-07-28 request. Return `inputRequired({ inputRequests: { ... } })`. Read the answer with `acceptedContent(ctx.mcpReq.inputResponses, 'id', schema)`. Use the same zod schema that you gave to `inputRequired.elicit`. The content comes from the client and is untrusted. To keep state between the retries, return `requestState` in `inputRequired(...)`. `requestState` comes back from the client. Treat it as untrusted input. Create one codec at module scope, outside the factory, with `createRequestStateCodec({ key })` from `@modelcontextprotocol/server`. Load a key of at least 32 bytes from the configuration. Each server process must use the same key. Pass a `bind` function that returns the user and `ctx.mcpReq.method`. Every tool call has the method `tools/call`. Thus, also put the tool name and the important arguments in the state. On the retry, reject the state if they do not match the call. Return `requestState: await codec.mint(state, ctx)` in `inputRequired(...)`. Set `requestState: { verify: codec.verify }` in the `McpServer` options. Read the state with `ctx.mcpReq.requestState<T>()`. The codec signs the state but does not encrypt it. Do not put secrets in the state.
219
- The revision 2026-07-28 deprecates sampling, MCP logging, and roots ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)). They continue to work for at least twelve months. HTTP+SSE is deprecated since 2025-03-26 (SEP-2596). It can be removed three months after SEP-2596 becomes final. Do not add these features to a new server:
220
- **Sampling** (`server.server.createMessage()`): Call the LLM provider API directly. If existing code must keep sampling, use `inputRequired.createMessage`.
221
- **MCP logging** (`ctx.mcpReq.log`): Log to stderr or use OpenTelemetry.
222
- **Roots**: Get paths from tool arguments, resource URIs, or the server configuration.
223
- **HTTP+SSE**: Use Streamable HTTP for a remote server.
224

© GitHub, Inc. · MIT · source · posted by @OpenSourceBuffGuy on promptparty.com

@OpenSourceBuffGuy

I find openly licensed prompts and post them here.

0 followers · 6,373 prompts

More by @OpenSourceBuffGuy

See all
Website Clone Architect prompt image

Website Clone Architect

Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.

agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait prompt image

Italian Terrace Cafe Candid Portrait

Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.

image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat prompt image

Night Street Photo With Leashed Cat

Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.

image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators

1 view

Reviews

Loading reviews…

Discussion

Loading comments…