{"slug": "build-an-mcp-server-in-typescript-step-by-step-guide", "title": "Build an MCP Server in TypeScript: Step-by-Step Guide", "summary": "A developer walkthrough shows how to build a minimal MCP server in TypeScript using the v2 `@modelcontextprotocol/server` SDK, which implements MCP spec revision 2026-07-28. The example registers two tools — an offline word counter and an npm version lookup that calls a public API — then serves them over stdio and connects to clients like Claude Desktop, Claude Code, Cursor and VS Code. It also demonstrates declaring network access in a manifest so users and scanners can verify which hosts a server contacts.", "body_md": "To build an MCP server, install the official SDK, create an `McpServer`, register one or more tools with a name, description, input schema and handler, then serve it over stdio. With the TypeScript SDK that is about 30 lines of code. You can test it with the MCP Inspector and connect it to Claude Desktop, Claude Code, Cursor or VS Code with a few lines of config.\n\nThis tutorial builds a small server with two tools: one that works offline and one that calls a public API. Then it shows how to declare that network access in a manifest so users (and scanners) can check your server only talks to the hosts you say it does. It uses the v2 TypeScript SDK (`@modelcontextprotocol/server`), which implements the current MCP spec, revision 2026-07-28. If MCP is new to you, read [what an MCP server is](https://agxmart.com/what-is-an-mcp-server) first. If you already have an API, read [MCP vs API](https://agxmart.com/blog/mcp-vs-api) to decide whether you need a server at all.\n\n```\nmkdir word-tools\ncd word-tools\nnpm init -y\nnpm install @modelcontextprotocol/server zod\nnpm install -D @types/node typescript\nmkdir src\n```\n\nThese are the packages the [official build-a-server tutorial](https://modelcontextprotocol.io/docs/develop/build-server) uses. In v2 the SDK is split into separate server and client packages. The older all-in-one `@modelcontextprotocol/sdk` package is the v1 line.\n\nAdd `\"type\": \"module\"` and a build script to `package.json`:\n\n```\n{\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"tsc\"\n  }\n}\n```\n\nCreate `tsconfig.json`:\n\n```\n{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"Node16\",\n    \"moduleResolution\": \"Node16\",\n    \"types\": [\"node\"],\n    \"outDir\": \"./build\",\n    \"rootDir\": \"./src\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\"]\n}\n```\n\nCreate `src/index.ts`:\n\n``` js\nimport { McpServer } from \"@modelcontextprotocol/server\";\nimport { serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport { z } from \"zod\";\n\nconst NPM_REGISTRY = \"https://registry.npmjs.org\";\n\n// serveStdio calls this whenever it needs a server instance,\n// so it must return a fresh McpServer every time.\nfunction createServer() {\n  const server = new McpServer({\n    name: \"word-tools\",\n    version: \"1.0.0\",\n  });\n\n  // Tool 1: pure computation, no network.\n  server.registerTool(\n    \"count_words\",\n    {\n      description: \"Count the words and characters in a piece of text.\",\n      inputSchema: z.object({\n        text: z.string().max(100_000).describe(\"The text to count\"),\n      }),\n    },\n    async ({ text }) => {\n      const words = text.trim() === \"\" ? 0 : text.trim().split(/\\s+/).length;\n      return {\n        content: [\n          { type: \"text\", text: `Words: ${words}\\nCharacters: ${text.length}` },\n        ],\n      };\n    },\n  );\n\n  // Tool 2: calls one public API.\n  server.registerTool(\n    \"npm_latest_version\",\n    {\n      description: \"Get the latest published version of an npm package.\",\n      inputSchema: z.object({\n        name: z\n          .string()\n          .regex(/^(@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/)\n          .describe(\"npm package name, for example zod or @scope/pkg\"),\n      }),\n    },\n    async ({ name }) => {\n      const res = await fetch(`${NPM_REGISTRY}/${name}/latest`);\n      if (!res.ok) {\n        return {\n          content: [{ type: \"text\", text: `Package not found: ${name}` }],\n          isError: true,\n        };\n      }\n      const data = (await res.json()) as { version?: string };\n      return {\n        content: [{ type: \"text\", text: `${name}@${data.version ?? \"unknown\"}` }],\n      };\n    },\n  );\n\n  return server;\n}\n\nserveStdio(createServer, {\n  onerror: (error) => console.error(\"word-tools error:\", error),\n});\nconsole.error(\"word-tools MCP server running on stdio\");\n```\n\nA few details matter here:\n\n`registerTool(name, config, handler)`` description` and an `inputSchema`. The handler receives the validated arguments and returns `content`.` serveStdio``server.connect(new StdioServerTransport())` still compiles but only serves older, 2025-era clients.`console.log` corrupts the stream, so use `console.error`.` fetch`. Tool arguments come from a model that may have read untrusted text, so treat them like user input.`isError: true`.\nThe current MCP revision is 2026-07-28. It removed the `initialize` handshake and protocol sessions and added a `server/discover` method that servers must implement ([changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog)). Not every SDK's stable release speaks it yet. From the [official build-a-server tutorial](https://modelcontextprotocol.io/docs/develop/build-server):\n\n| SDK | What the tutorial says about protocol revisions | \n|---|---|\n| TypeScript v2 ( `@modelcontextprotocol/server` ) | `serveStdio` negotiates per client, answering both 2026-07-28 clients and older clients that send`initialize` | \n| Java | Latest stable release uses 2025-11-25; clients that support only 2026-07-28 cannot connect | \n| Kotlin | Latest stable release uses 2025-11-25; same limitation as Java | \n| Python, C#, Go, Ruby, Rust | Tutorial does not state a revision; check each SDK's release notes | \n\nIf you need to reach clients on both revisions today, TypeScript v2 with `serveStdio` is the documented option.\n\nThe model only sees each tool's name, description and input schema, so those are your interface:\n\n`npm_latest_version` is easier for a model to pick correctly than a generic `npm` tool with a mode argument.\nTools are one of three server primitives. **Resources** are read-only data the client can load, addressed by a URI. **Prompts** are reusable templates the user picks, usually as a slash command. The v2 SDK registers them the same way as tools, as shown in the SDK docs for [resources](https://ts.sdk.modelcontextprotocol.io/v2/servers/resources.html) and [prompts](https://ts.sdk.modelcontextprotocol.io/v2/servers/prompts.html). Add these inside `createServer()`:\n\n```\n// A static resource: a name, a fixed URI, metadata and a read callback.\nserver.registerResource(\n  \"usage\",\n  \"word-tools://usage\",\n  {\n    title: \"Usage notes\",\n    description: \"How the word-tools server counts words\",\n    mimeType: \"text/plain\",\n  },\n  async (uri) => ({\n    contents: [\n      { uri: uri.href, text: \"Words are split on whitespace. Characters include spaces.\" },\n    ],\n  }),\n);\n\n// A prompt with one required argument.\nserver.registerPrompt(\n  \"summarise-length\",\n  {\n    title: \"Summarise text length\",\n    description: \"Ask for a word count and a one-line summary\",\n    argsSchema: z.object({ text: z.string() }),\n  },\n  ({ text }) => ({\n    messages: [\n      {\n        role: \"user\",\n        content: { type: \"text\", text: `Count the words in this text, then summarise it in one line:\\n\\n${text}` },\n      },\n    ],\n  }),\n);\n```\n\nCheck the exact field names against the SDK pages linked above if your SDK version differs; the SDK is still on its v2 line and details can move.\n\n```\nnpm run build\nnpx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern --method tools/list\n```\n\nYou should see `count_words` and `npm_latest_version`. The Inspector CLI defaults to the older protocol era, so the official tutorial recommends running the same command again with `--protocol-era legacy` to check that older clients work too. Run `npx @modelcontextprotocol/inspector node build/index.js` without `--cli` to open the visual UI and call tools by hand.\n\nTwo kinds of test catch most problems.\n\n**Unit tests for the logic.** Move the word count into its own exported function in `src/count.ts` and test it with Node's built-in [test runner](https://nodejs.org/api/test.html), with no extra dependencies:\n\n```\n// src/count.ts\nexport function countWords(text: string): number {\n  return text.trim() === \"\" ? 0 : text.trim().split(/\\s+/).length;\n}\npython\n// src/count.test.ts\nimport { test } from \"node:test\";\nimport assert from \"node:assert/strict\";\nimport { countWords } from \"./count.js\";\n\ntest(\"counts words\", () => {\n  assert.equal(countWords(\"hello  world\"), 2);\n  assert.equal(countWords(\"   \"), 0);\n});\n```\n\nBuild, then run `node --test build/`.\n\n**An integration test that spawns the server and calls a tool.** The Inspector CLI is built for this: it starts the server, calls a method and exits, so it fits in CI ([Inspector docs](https://modelcontextprotocol.io/docs/tools/inspector)):\n\n```\nnpx @modelcontextprotocol/inspector --cli node build/index.js --protocol-era modern \\\n  --method tools/call --tool-name count_words --tool-arg text=\"one two three\" --format json\n```\n\nRun it in both the `modern` and `legacy` protocol eras so you know both kinds of client work.\n\nClients stop a stdio server by closing its input or sending a signal. If your server holds anything open, such as a database pool or a temp file, release it on `SIGINT` and `SIGTERM` ([Node.js signal events](https://nodejs.org/api/process.html#signal-events)):\n\n``` js\nfor (const signal of [\"SIGINT\", \"SIGTERM\"] as const) {\n  process.on(signal, () => {\n    console.error(`word-tools: received ${signal}, shutting down`);\n    // close database pools, flush logs, delete temp files here\n    process.exit(0);\n  });\n}\n```\n\nLog to stderr here too, never stdout.\n\nFor Claude Code:\n\n```\nclaude mcp add --transport stdio word-tools -- node /absolute/path/to/word-tools/build/index.js\n```\n\nFor Claude Desktop, add it to `claude_desktop_config.json` and restart the app:\n\n```\n{\n  \"mcpServers\": {\n    \"word-tools\": {\n      \"command\": \"node\",\n      \"args\": [\"/absolute/path/to/word-tools/build/index.js\"]\n    }\n  }\n}\n```\n\nOur [MCP server install guide](https://agxmart.com/blog/how-to-install-mcp-server) has the config file paths and formats for Claude Desktop, Claude Code, Cursor and VS Code.\n\nThe official Python SDK follows the same pattern. Its current quickstart uses the `MCPServer` class and needs Python 3.10 or higher ([official tutorial](https://modelcontextprotocol.io/docs/develop/build-server)):\n\n``` python\nfrom mcp.server import MCPServer\n\nmcp = MCPServer(\"word-tools\")\n\n@mcp.tool()\ndef count_words(text: str) -> str:\n    \"\"\"Count the words and characters in a piece of text.\"\"\"\n    words = len(text.split())\n    return f\"Words: {words}\\nCharacters: {len(text)}\"\n\nif __name__ == \"__main__\":\n    mcp.run(transport=\"stdio\")\n```\n\nInstall it with `uv add \"mcp[cli]\"` or `pip install \"mcp[cli]\"`. The SDK builds the tool schema from type hints and the docstring.\n\nPublishing to npm lets users run your server with `npx` instead of cloning the repo. Three `package.json` fields matter. The first two match the [official tutorial](https://modelcontextprotocol.io/docs/develop/build-server):\n\n```\n{\n  \"name\": \"@your-scope/word-tools\",\n  \"version\": \"1.0.0\",\n  \"type\": \"module\",\n  \"bin\": { \"word-tools\": \"./build/index.js\" },\n  \"files\": [\"build\"],\n  \"scripts\": {\n    \"build\": \"tsc && chmod 755 build/index.js\",\n    \"prepublishOnly\": \"npm run build\"\n  }\n}\n```\n\n`bin`` npx @your-scope/word-tools` start the server. npm requires the file to start with `#!/usr/bin/env node`, so add that as the first line of `src/index.ts` (`files`` prepublishOnly``npm publish`, so you never publish a stale build (\nThen run `npm publish --access public`. If you also want a listing in the official MCP Registry, see our guide to [getting your MCP server discovered](https://agxmart.com/blog/get-your-mcp-server-discovered).\n\nUsers who follow an [MCP server security checklist](https://agxmart.com/blog/mcp-server-security-guide) will want to know which hosts your server talks to. Say it up front in a manifest. AGXmart reads an `agent.json` file in the repo root, where you list the domains your code contacts and the environment variables it needs:\n\n```\n{\n  \"name\": \"word-tools\",\n  \"description\": \"Count words and look up npm package versions.\",\n  \"type\": \"mcp\",\n  \"entrypoint\": \"node build/index.js\",\n  \"network\": [\"registry.npmjs.org\"],\n  \"env\": []\n}\n```\n\nWhen the server is scanned, all outbound traffic is recorded and compared with this list. A domain you did not declare, or a hard-coded IP address, gets flagged in the public report. Without a declaration, any network traffic counts as undeclared. So keep the list accurate and short. If your server needs an API key, list the variable name in `env` and never commit the value.\n\nIf you also publish to the official MCP Registry, you will have a `server.json` too. AGXmart can read that file, but it does not hold a list of network domains, so `agent.json` is where you declare egress.\n\nPush the repo to GitHub, then [submit it for a free scan](https://agxmart.com/submit). The scan runs on a fresh virtual machine that is destroyed afterwards. It runs Semgrep with custom rules (eval, shell exec, hidden environment variable reads, obfuscation), Gitleaks for secrets and OSV-Scanner for vulnerable dependencies. It then installs and starts your server in a Docker container with all Linux capabilities dropped, running as a non-root user, and lists its tools over stdio with `tools/list`. It sends an `initialize` request first, which servers on pre-2026-07-28 revisions expect; it does not yet call `server/discover`. A server built with `serveStdio` answers both. The probe runs three times, and three matching clean runs earn the reproducibility badge.\n\nThe results become badges and a 0 to 100 score on a public listing page, and once listed the server appears in the [MCP server directory](https://agxmart.com/mcp-servers). You can read exactly what each check does on the [verification page](https://agxmart.com/how-we-scan), and how listings work on the [developers page](https://agxmart.com/developers). A scan is a malware and risk check, not a safety guarantee, and the report says so.\n\nBefore you submit, run through the same checks yourself:\n\nOnce your server is listed, our guide on how to [get your MCP server discovered](https://agxmart.com/blog/get-your-mcp-server-discovered) covers the MCP Registry, naming and getting your first users.\n\nUse the language your team already knows. There are official SDKs for TypeScript and Python, and also Java, Kotlin, C#, Go, Ruby and Rust, as listed in the official build-a-server tutorial. TypeScript and Python have the most examples.\n\n`@modelcontextprotocol/sdk` is the v1 TypeScript SDK, which bundles client and server code. The v2 SDK splits them into `@modelcontextprotocol/server` and `@modelcontextprotocol/client` and supports the 2026-07-28 spec. New projects should start on v2.\n\nOn the stdio transport, stdout carries the JSON-RPC protocol messages. Anything else printed there corrupts the stream and the client drops the connection. Log to stderr with `console.error`, or use a logger that writes to stderr or a file.\n\nUnder the 2026-07-28 revision, yes: servers MUST implement it ([changelog](https://modelcontextprotocol.io/specification/2026-07-28/changelog)). With the TypeScript v2 SDK, `serveStdio` handles both `server/discover` and the older `initialize` flow for you. Test with the Inspector in both `--protocol-era modern` and `--protocol-era legacy`.\n\nStart with tools, since they are what the model calls. Add a resource when the client should be able to read data without a tool call, and a prompt when users repeat the same request often.\n\nUnit-test the logic behind each tool with your normal test runner, then use the Inspector CLI (`--cli`) in CI to start the server and call `tools/list` and `tools/call`. It exits with the result, so a failing call fails the build.\n\nServe it over the Streamable HTTP transport instead of stdio, behind HTTPS, with authentication. The spec requires HTTP servers to validate the Origin header and recommends OAuth 2.1 for auth. Our comparison of [local and remote MCP servers](https://agxmart.com/blog/local-vs-remote-mcp-servers) explains the trade-offs.\n\n*Originally published on [AGXmart](https://agxmart.com/blog/build-your-first-mcp-server). I run AGXmart, a marketplace for open-source AI agents, MCP servers and agent skills with public security scans. Search and install from your terminal with `npx agxmart`, or list your own tool and start selling.*", "url": "https://wpnews.pro/news/build-an-mcp-server-in-typescript-step-by-step-guide", "canonical_source": "https://dev.to/agxmart/build-an-mcp-server-in-typescript-step-by-step-guide-d61", "published_at": "2026-12-01 04:10:07+00:00", "updated_at": "2026-12-01 04:14:25.943279+00:00", "lang": "en", "topics": ["ai-agents", "agent-protocols", "developer-tools", "ai-tools"], "entities": ["Model Context Protocol", "@modelcontextprotocol/server", "Claude Desktop", "Claude Code", "Cursor", "VS Code", "npm"], "also_reported_by": [], "takeaway": "With the v2 TypeScript SDK, an MCP server is roughly 30 lines: create an McpServer, register tools with Zod input schemas and handlers, and serve over stdio with serveStdio, which must return a fresh server instance per call.", "recommendation": {"advice": "Build MCP tools with the v2 @modelcontextprotocol/server SDK, validate inputs with Zod schemas, and declare network access in a manifest so scanners can verify allowed hosts.", "playbook": "agent-architecture", "playbook_url": "https://wpnews.pro/playbooks/agent-architecture"}, "alternates": {"html": "https://wpnews.pro/news/build-an-mcp-server-in-typescript-step-by-step-guide", "markdown": "https://wpnews.pro/news/build-an-mcp-server-in-typescript-step-by-step-guide.md", "text": "https://wpnews.pro/news/build-an-mcp-server-in-typescript-step-by-step-guide.txt", "jsonld": "https://wpnews.pro/news/build-an-mcp-server-in-typescript-step-by-step-guide.jsonld"}}