I wanted first-hand experience before writing more about MCP, so I built and shipped a real server: ai-api-cost-mcp, a small tool that lets an AI assistant estimate and compare OpenAI, Claude and Gemini API costs. This guide shows how to build an MCP server in Node.js the way I did it, from the first tool to npm and the official MCP Registry.
I cover the tool definitions, the one stdio rule you cannot break, live prices with a safe fallback, the timeout I had to fix, testing with a real MCP client, and what publishing really involved. It all happened between 22 and 24 November 2026, and the code is public on GitHub.
How to build an MCP server in Node.js
What an MCP server is, in plain words
The Model Context Protocol (MCP) is an open standard that lets AI apps such as Claude Desktop, Claude Code or Cursor use tools that someone else wrote. Your server describes its tools: a name, a description and the inputs each one accepts. The AI app, called the client, reads that list and calls a tool when a question needs it.
My server uses the stdio transport. The client starts the server as a child process, and the two exchange JSON messages through standard input and output. There is no port, no hosting and no login, which makes stdio the simplest place to start. If you are still deciding whether you need MCP at all, I compared it with plain HTTP APIs in MCP vs REST API for AI agents.
One calculator for the website and the server
The server has three read-only tools: list_models shows the models and rates it knows, estimate_cost prices one model for a workload, and compare_models ranks every model for the same workload. Those numbers already existed on my site in the free AI API Cost Calculator.
I did not want two copies of the pricing logic drifting apart, so the server runs the same calculator module as the web page. A small script, scripts/sync-calculator.mjs, copies the website file into the package, and npm runs it on prepack before every publish. The page and the server cannot disagree about a rate or a formula. If you are wrapping an existing product in MCP, start the same way: reuse code your product already trusts and keep the MCP layer thin.
Registering tools with zod
I used the official TypeScript SDK from plain JavaScript (@modelcontextprotocol/sdk 1.32.2 with zod 4.6.7). Each tool is one registerTool call with a name, a config object and a handler. This is the shortest one, simplified a little:
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: "ai-api-cost-mcp", version }); server.registerTool( "list_models", { description: "List the models this server knows, with rates per 1M tokens.", inputSchema: { provider: z.enum(["OpenAI", "Anthropic", "Google"]).optional() }, annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false }, }, async ({ provider }) => { const models = currentModels(await getRateTable()) .filter((m) => !provider || m.provider === provider); return { content: [{ type: "text", text: formatTable(models) }], structuredContent: { models }, }; } ); await server.connect(new StdioServerTransport()); The zod schema does two jobs: the SDK turns it into the JSON Schema the client sees, and it checks arguments before my handler runs. Descriptions matter more than I expected: the model reads them to pick a tool and fill each field, so write them like help text for a new colleague.
The annotations tell the client these tools only read and calculate. They are hints, not a security boundary.
Text for the model, structuredContent for code
Every tool returns a readable text answer, usually a Markdown table, plus the same numbers as structuredContent, a plain JSON object. The assistant shows and reasons about the text. My test reads the JSON, and so can any program, without parsing text.
When someone asks for a model the server does not know, the handler does not throw. It returns a normal result with isError: true and a message listing the known model ids, so the model can correct itself and try again.
On stdio, logs go to stderr
This rule breaks most first servers. On stdio, standard output is the protocol channel, so a stray console.log puts text there that the client cannot parse. The official MCP debugging guide says local servers should not log to stdout. My server logs with console.error, which goes to stderr, and the host app captures it.
Live rates without breaking offline use
AI API prices change, and I did not want a new npm release for every price update. So the site build also publishes a public file, /tools/ai-api-pricing.json, generated from the same calculator module. The server tries that file and falls back to the rates bundled in the package.
Validate everything you download
The server treats the live file as untrusted input:
- It checks every model entry: text fields must be present, and every rate, including promotional rates, must be a finite number of zero or more.
- It uses the live table only if its verified date is at least as new as the bundled one, so an old copy can never roll prices back.
- It caches the result for 12 hours.
- Setting
AI_API_COST_MCP_OFFLINE=1skips the request completely.
It is a plain GET of a static file. Nothing the user types is sent anywhere, and the README says so.
The timeout that was too tight
My first version gave that request 2.5 seconds. In my tests, a cold first request, which needs a DNS lookup and a TLS handshake, took roughly 0.9 to 1.8 seconds. That was too close. On a slower connection the request would be cut off, and a fresh install would quietly answer with bundled rates.
The fix had three parts: a 5-second timeout, a warm-up call right after server.connect, and one shared in-flight promise so the warm-up and an early tool call never send two requests:
let inflight = null; export async function getRateTable() { if (cache && Date.now() - cache.loadedAt < REFRESH_MS) return cache.table; if (!inflight) inflight = loadRateTable().finally(() => (inflight = null)); return inflight; } // index.js, right after server.connect(transport) getRateTable().catch(() => {}); A silent fallback is good for users and bad for debugging, so every answer says which rate table it used and when those rates were verified.
Testing an MCP server with a real client
I wanted a check I could rerun with one command, so I wrote test/smoke.mjs with the SDK's own Client and StdioClientTransport. It starts the real server and talks to it exactly as an AI app would.
The test checks that exactly three tools are listed and compares estimate_cost results with the calculator module directly, to six decimal places. It also tries custom rates, confirms that an unknown model returns isError: true, and checks that compare_models covers every model, sorted from cheapest. It runs offline by default; LIVE=1 lets the server fetch the live file.
After the scripted test passed, I checked the tools inside a real AI app.
Then I tested it the way a user would. After publishing, I ran npx -y ai-api-cost-mcp with a real client, and it read the live rates. I also added the server to Claude Desktop and asked it to compare models for a support bot priced at $49 per user. Claude called compare_models with the support preset and that price. A user only needs this config:
{ "mcpServers": { "ai-api-cost": { "command": "npx", "args": ["-y", "ai-api-cost-mcp"] } } } How to publish an MCP server: npm, the Registry and directories
npm first
Three package.json fields do most of the work: bin so npx can run the server, files so only the source, README and license ship, and engines for the Node.js version. The entry file starts with #!/usr/bin/env node.
My npm account uses a security key for two-factor authentication, so npm publish --access public waited until I approved it in the browser. Right after that, npm showed a 0.0.0-stage placeholder for a few minutes before 0.1.0 became latest.
With a security key, an npm publish waits for a human approval in the browser.
The official MCP Registry
The official MCP Registry stores metadata, not code, which is why npm comes first. My steps:
- Add
"mcpName": "io.github.m-mustufa/ai-api-cost-mcp"topackage.jsonand publish that version to npm. With GitHub login, the name must start withio.github.and your username. - Run
mcp-publisher initto generateserver.json. - Read every line it generated and fix what it guessed.
- Run
mcp-publisher validate. - Run
mcp-publisher login githuband approve the device code on GitHub. - Run
mcp-publisher publish.
Step 3 is my warning. The template added a required API-key variable that my server does not have, and it copied my Bitbucket git remote, while the public code lives on GitHub. I fixed both by hand and declared the one real, optional variable:
"environmentVariables": [{ "name": "AI_API_COST_MCP_OFFLINE", "isRequired": false, "isSecret": false }] Directories: what worked and what did not
Directories read a GitHub repository, but my source lives in my website's repo, so I mirror the package folder into a standalone public repo with git subtree.
- Glama: listed through its Add Server form after review and a Docker check. A small
glama.jsonnames me as the maintainer. - Smithery: closed self-listing on 31 October 2026, so there was nothing to submit.
- mcp.so: the web form was paid only, $39 for a dofollow link. I opened a free GitHub issue instead, because I do not pay for links.
What I would tell you before you start
- Reuse logic your product already trusts and keep the MCP layer thin.
- Write tool and field descriptions for the model, not for yourself.
- Return text and
structuredContent, and useisErrorfor bad input. - Never write to stdout on a stdio server.
- Validate anything you download, fall back safely and give cold network calls room.
- Test with a real client, then test the published package with
npx. - Read every line
mcp-publisher initwrites before you publish.
One honest note: I built this on the v1 SDK. There is now also a v2 line with separate packages such as @modelcontextprotocol/server. registerTool keeps its shape, but the upgrade guide wraps plain zod shapes like mine in z.object(), so check the current SDK docs before copying older examples, including mine.
Try it with npx -y ai-api-cost-mcp, or use the AI API Cost Calculator in the browser. My OpenAI vs Claude vs Gemini API pricing guide explains the numbers. If your server will touch customer data, read my MCP server security checklist first. Need an MCP server or AI feature in your SaaS product? See my AI SaaS development services or get in touch.
I first published this on my blog: How to Build an MCP Server: Node.js Build, Test and Publish.



