TypeScript MCP Server Generator
لما تبغى تنشئ سيرفر MCP جديد بـTypeScript أو Node.js.
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.
Install
npx skills add github/awesome-copilot --skill typescript-mcp-server-generatorWorks with
claude-code (native), claude (native), codex (native), chatgpt (native), gemini-cli (native), cursor (native), copilot (native), opencode (native), amp (native), roo (native), kiro (native), goose (native), junie (native), trae (native), cline (compatible), continue (compatible), antigravity (compatible), windsurf (compatible), augment (compatible), qwen-code (compatible)
Content
TypeScript MCP Server Generator
Create a Model Context Protocol (MCP) server in TypeScript with the official MCP TypeScript SDK 2.x. SDK 2.4.x implements the MCP specification revision 2026-07-28. A client enables it with versionNegotiation. By default, a client still uses the 2025 initialize handshake.
Workflow
Copy this checklist. Use it to track your progress:
- [ ] Step 1: Create the project.
- [ ] Step 2: Write the server.
- [ ] Step 3: Write the tests.
- [ ] Step 4: Build until the tests pass.
- [ ] Step 5: Configure the client.
Step 1: Create the project
Make this layout:
project-name/
├── package.json
├── tsconfig.json
├── src/index.ts
└── test/server.test.ts
Write package.json:
{
"name": "my-mcp-server",
"version": "0.1.0",
"type": "module",
"bin": { "my-mcp-server": "dist/index.js" },
"scripts": {
"build": "tsc",
"dev": "tsx src/index.ts",
"start": "node dist/index.js",
"test": "vitest run"
}
}
Write tsconfig.json:
{
"compilerOptions": {
"target": "es2022",
"module": "nodenext",
"moduleResolution": "nodenext",
"strict": true,
"types": ["node"],
"rootDir": "src",
"outDir": "dist"
},
"include": ["src"]
}
Install the dependencies:
npm install @modelcontextprotocol/server zod@^4.2
npm install -D typescript@^7.0.2 @types/node@^22 tsx vitest@^5.1.2 @modelcontextprotocol/client
@modelcontextprotocol/servercontainsMcpServerand the stdio entry@modelcontextprotocol/server/stdio.@modelcontextprotocol/clientis only for the tests.tsxruns the server during development. Do not use Node.js native TypeScript execution.
Step 2: Write the server
Start from this template in src/index.ts:
#!/usr/bin/env node
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
function createServer(): McpServer {
const server = new McpServer({ name: 'demo', version: '0.1.0' });
server.registerTool(
'divide',
{
title: 'Divide',
description: 'Divide a by b.',
inputSchema: z.object({
a: z.number().describe('Dividend'),
b: z.number().describe('Divisor')
}),
outputSchema: z.object({ result: z.number() })
},
async ({ a, b }) => {
if (b === 0) {
return { content: [{ type: 'text', text: 'b must not be zero.' }], isError: true };
}
const result = a / b;
return {
content: [{ type: 'text', text: JSON.stringify({ result }) }],
structuredContent: { result }
};
}
);
return server;
}
void serveStdio(createServer);
console.error('demo MCP server running on stdio');
Then change the template to match the request of the user:
- Replace the
dividetool with the tools that the user asks for. - Give each tool a zod
inputSchema(z.object({ ... })), atitle, and adescription. The description tells the model when to use the tool. - When the client must get machine-readable data, add an
outputSchema. Return the data instructuredContent. Also return the same data as serialized JSON in a text block for older clients. - Mark a read-only tool with
annotations: { readOnlyHint: true }. - Add resources (
registerResource) and prompts (registerPrompt) only when the user asks for them.
Use stdio by default. Read [references/streamable-http.md](references/streamable-http.md) only when the user asks for a remote server or HTTP.
Step 3: Write the tests
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:
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
import { afterAll, beforeAll, expect, test } from 'vitest';
let client: Client;
beforeAll(async () => {
client = new Client({ name: 'test-client', version: '1.0.0' }, { versionNegotiation: { mode: { pin: '2026-07-28' } } });
await client.connect(new StdioClientTransport({ command: process.execPath, args: ['dist/index.js'] }));
});
afterAll(async () => {
await client.close();
});
test('negotiates the 2026-07-28 revision', () => {
expect(client.getNegotiatedProtocolVersion()).toBe('2026-07-28');
});
test('divide', async () => {
const result = await client.callTool({ name: 'divide', arguments: { a: 6, b: 3 } });
expect(result.structuredContent).toEqual({ result: 2 });
});
test('divide by zero', async () => {
const result = await client.callTool({ name: 'divide', arguments: { a: 1, b: 0 } });
expect(result.isError).toBe(true);
expect(JSON.stringify(result.content)).toContain('must not be zero');
});
- For an HTTP server, use the test setup in [references/streamable-http.md](references/streamable-http.md).
- The test runs
dist/index.js. Runnpm run buildbeforenpm test. process.execPathis thenodecommand that runs the tests. Do not use thenodecommand fromPATH.- The test uses the real stdio transport and the real JSON-RPC messages.
- The
pinoption makes the client use the revision 2026-07-28. Without it, the client uses the 2025 handshake.
Step 4: Build until the tests pass
- Run
npm run build && npm test. This command compiles the code todist/and runs the tests. - If a test or the compiler fails, read the error. Fix the server or the test.
- Run
npm run build && npm testagain. - Continue only when the build and all tests pass.
Step 5: Configure the client
For VS Code, write .vscode/mcp.json:
{
"servers": {
"demo": {
"type": "stdio",
"command": "node",
"args": ["/absolute/path/to/project/dist/index.js"]
}
}
}
For Claude Desktop, put the same command and args in claude_desktop_config.json, below the mcpServers key.
For an HTTP server, use the client configuration in [references/streamable-http.md](references/streamable-http.md).
Tell the user these facts:
node dist/index.jsstarts the stdio server. The server waits for a host on stdin. The logs go to stderr.- 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.
Gotchas
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 for the full list.
- 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. - The SDK does not support Zod 3. Use
zod@^4.2and give schemas asz.object({ ... }). The raw shape form{ name: z.string() }is deprecated. - Use
registerTool(),registerResource(), andregisterPrompt(). The variadictool()methods do not exist. - If a tool has an
outputSchema, returnstructuredContentin each successful result. - Write
completable(z.string(), callback).optional(). Put.optional()on the outside. - Return a result with
isError: truefor an error that the model must read. The v2 error classes areProtocolError,SdkError, andSdkHttpError(with.status).McpErrorandStreamableHTTPErrordo not exist. - In a stdio server, stdout is the protocol channel. Do not call
console.log(). Useconsole.error(). - There are no sessions and no
initializehandshake on 2026-07-28. Per-call state lives in handles that the server makes and the model passes as tool arguments. - The SDK answers
server/discover, fillsresultType, and routessubscriptions/listen. Do not write them manually. - Do not use
ctx.mcpReq.elicitInput(). It throws on a 2026-07-28 request. ReturninputRequired({ inputRequests: { ... } }). Read the answer withacceptedContent(ctx.mcpReq.inputResponses, 'id', schema). Use the same zod schema that you gave toinputRequired.elicit. The content comes from the client and is untrusted. To keep state between the retries, returnrequestStateininputRequired(...).requestStatecomes back from the client. Treat it as untrusted input. Create one codec at module scope, outside the factory, withcreateRequestStateCodec({ key })from@modelcontextprotocol/server. Load a key of at least 32 bytes from the configuration. Each server process must use the same key. Pass abindfunction that returns the user andctx.mcpReq.method. Every tool call has the methodtools/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. ReturnrequestState: await codec.mint(state, ctx)ininputRequired(...). SetrequestState: { verify: codec.verify }in theMcpServeroptions. Read the state withctx.mcpReq.requestState<T>(). The codec signs the state but does not encrypt it. Do not put secrets in the state. - The revision 2026-07-28 deprecates sampling, MCP logging, and roots (SEP-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:
- Sampling (
server.server.createMessage()): Call the LLM provider API directly. If existing code must keep sampling, useinputRequired.createMessage. - MCP logging (
ctx.mcpReq.log): Log to stderr or use OpenTelemetry. - Roots: Get paths from tool arguments, resource URIs, or the server configuration.
- HTTP+SSE: Use Streamable HTTP for a remote server.
Source and license
- Source
- GitHub Awesome Copilot
- Original
- github/awesome-copilot/skills/typescript-mcp-server-generator/SKILL.md
- License
- MIT