Build an MCP Server in TypeScript (Node.js)

Create a Model Context Protocol server with the official TypeScript SDK: register tools with zod schemas, add resources, run over stdio and test.

Published December 1, 2026

If your team lives in Node.js, the official TypeScript SDK is the natural way to expose internal APIs to AI assistants over MCP. This tutorial builds a server that looks up npm package information, with input validation via zod, and shows how to test and connect it.

The concept

The SDK's McpServer class registers tools with a name, a description, an input schema and an async handler. Schemas are written with zod, so inputs are validated before your handler runs and the JSON Schema the model sees is generated automatically.

Handlers return a result containing an array of content items, typically text. Errors can be returned as results with isError set, which lets the model see what went wrong and try again, instead of crashing the session.

Project setup

A minimal ES module project.

mkdir npm-info-mcp && cd npm-info-mcp
npm init -y && npm pkg set type=module
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node && npx tsc --init

The server

Save as src/index.ts. It calls the public npm registry.

import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
import { z } from 'zod'

const server = new McpServer({ name: 'npm-info', version: '1.0.0' })

server.tool(
  'package_info',
  'Get the latest version, description and weekly downloads of an npm package.',
  { name: z.string().describe('Exact npm package name, e.g. "react"') },
  async ({ name }) => {
    const meta = await fetch(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`)
    if (!meta.ok) return { isError: true, content: [{ type: 'text', text: `Package ${name} not found` }] }
    const pkg = await meta.json()
    const dl = await fetch(`https://api.npmjs.org/downloads/point/last-week/${encodeURIComponent(name)}`).then(r => r.json())
    return { content: [{ type: 'text', text: `${pkg.name}@${pkg.version}: ${pkg.description}\nWeekly downloads: ${dl.downloads}` }] }
  },
)

await server.connect(new StdioServerTransport())
console.error('npm-info MCP server running on stdio')

Request path

JSON-RPCokreturnHosttools/callMcpServerzod validatesHandlerfetch registryResultcontent[]
Every call is validated before your code runs.

Practical examples

Build and inspect

Compile, then open the Inspector against the built file.

npx tsc
npx @modelcontextprotocol/inspector node dist/index.js

Add a resource

Expose read-only context such as a package README.

import { ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js'
server.resource('readme', new ResourceTemplate('npm://{name}/readme', { list: undefined }),
  async (uri, { name }) => {
    const pkg = await fetch(`https://registry.npmjs.org/${name}`).then(r => r.json())
    return { contents: [{ uri: uri.href, text: pkg.readme ?? 'No README' }] }
  })

Host config

Point the host at the compiled entry file.

{ "mcpServers": { "npm-info": { "command": "node", "args": ["/abs/path/npm-info-mcp/dist/index.js"] } } }

Common mistakes

  • console.log in a stdio server; use console.error for logs.
  • Throwing on expected failures instead of returning isError results the model can react to.
  • Missing .describe() on schema fields, leaving the model to guess inputs.
  • Forgetting "type": "module" when importing the SDK's ESM paths.

Key takeaways

  • McpServer + zod gives validated, self-describing tools.
  • Return content arrays; use isError for recoverable failures.
  • Log to stderr when using stdio.
  • Test with the Inspector before wiring into a host.

FAQ

Can I deploy it as a remote server?

Yes. The SDK includes a Streamable HTTP server transport you can mount in Express or another HTTP framework, with authentication in front.

Is the API stable?

The SDK evolves with the spec. Pin versions and check the changelog when upgrading.

How many tools should one server have?

As few as cover the use case well. Many hosts show all tools to the model, so fewer, clearer tools work better.

More AI articles