Build an MCP server in TypeScript: three tools, API key, logging
Build a small MCP server in TypeScript that lets an AI assistant call three read-only tools, with an API key check and logs that never hold the key. SDK 2.4.0.

Maulik Joshi
Full-Stack Developer
MCP (Model Context Protocol) is a standard way for an AI assistant to call tools you define, and this post shows developers how to build a small server for those tools in TypeScript. It answers two practical questions: how to keep unauthorized callers out with an API key, and how to log what happens without ever writing the key down. After reading, you will be able to build and run a server of your own and test that the right key, a wrong key and no key are treated differently.
MCP, the Model Context Protocol, is a standard way for an AI assistant to call tools that you define, such as looking up a clinic in a directory. A small MCP server in TypeScript has three parts: a factory that registers the tools, with Zod schemas describing the inputs each tool accepts; a transport, which is the channel the server talks over, either HTTP or stdio (the standard input and output of the program that launched it); and a gate in front of the transport whenever something other than the launching process can reach it. This post builds one with @modelcontextprotocol/server 2.4.0. It has three read-only tools over a synthetic (invented) clinic directory, an API key (a secret string the caller sends to prove it may use the server) checked on a request header over HTTP, structured logs, one JSON line per event written to stderr (the error output stream), that never contain the key, and a test client that shows the right key, a wrong key and no key behaving differently.
Everything below was built and run on November 22, 2026, on macOS 26.5 (Apple silicon) with Node 20.17.0 and npm 10.8.2. The MCP specification revision current that day was 2026-07-28. Output is copied from that run, and any trimmed listing is marked. The data is invented, six clinics with placeholder names and no people, so no patient information is involved.
#Which SDK and which versions
There are two generations of the TypeScript SDK, and tutorials mix them. The older one is the single package @modelcontextprotocol/sdk, whose latest release on npm was 1.32.2 when I checked. The current one, version 2, is split into @modelcontextprotocol/server and @modelcontextprotocol/client, with small adapter packages for Node and Express. The SDK repository's README calls v2 the stable release line, says it implements the 2026-07-28 specification, and says v1 keeps getting bug fixes and security updates for at least six months after v2 shipped on July 27, 2026. A snippet that imports from @modelcontextprotocol/sdk and calls server.tool is v1. In v2 the call is registerTool, imported from @modelcontextprotocol/server. This post is v2 only, and none of it was run on v1.
| Package | Version | Used for |
|---|---|---|
| @modelcontextprotocol/server | 2.4.0 | McpServer, createMcpHandler, serveStdio, OAuthError |
| @modelcontextprotocol/express | 2.0.2 | createMcpExpressApp and the requireBearerAuth middleware |
| @modelcontextprotocol/node | 2.1.2 | toNodeHandler, which adapts the SDK handler to Express |
| @modelcontextprotocol/client | 2.4.0 | Client and transports, for the test |
| express | 5.3.0 | The HTTP server |
| zod | 4.6.7 | Input schemas, imported from zod/v4 |
| tsx and typescript | 4.23.15 and 7.0.2 | Running and type-checking the TypeScript |
The v2 packages declare Node 20 or later in their engines field. The SDK ships ES modules only, so the project needs type set to module.
#The three tools
The dataset is a typed array in src/data.ts. Three of the six rows I used are shown here, and the other three have the same shape.
The tools are small on purpose. list_clinics filters by city, get_clinic fetches one record by id, and search_services finds clinics that offer a service. All three are read-only.
createServer is a factory because both transports want one. With createMcpHandler the SDK calls it on every HTTP request, and serveStdio calls it for the connection, so tools are registered inside it and not on a shared instance. That is what the SDK's HTTP page tells you to do.
inputSchema is the only schema you write. From it the SDK derives the JSON Schema a model sees, validates arguments before your handler runs, and types the handler's arguments. The default on limit means the handler always receives a number, and the describe text is the only documentation a model gets for an argument. A call that fails the schema comes back as an ordinary result with isError set, so a model can read the message and try again.
The unknown-id case is handled inside the tool and also returns isError. The SDK would turn a thrown error into the same shape, but a throw would skip the log line in the logged wrapper, so I return the error as a value. The annotations mark each tool read-only. They are hints for the client, which may use them to decide what to approve without asking, and the SDK documentation says annotations never change how it runs a tool. They label the tool and enforce nothing.
#Where should an MCP server write its logs?
The stdio transport page of the specification says a server must not write anything to stdout that is not a valid MCP message, and that it may write to stderr for logging. The HTTP transport has no such constraint, but one logger that writes JSON lines to stderr works under both, so that is what this server has.
Three choices matter here. Each event is one JSON object per line, which is easy to filter and easy to ship later. A replacer blanks any field whose name looks like a credential, as a backstop: the real protection is that no code passes the key to the logger in the first place. And the tool wrapper in server.ts, shown earlier, logs the names of the arguments and the number of rows returned, not the argument values. In a real clinic directory those values would be patient or staff identifiers, and a log is usually kept longer and read by more people than the data it describes.
The SDK also has MCP-level logging, where a handler sends notifications to the client. Its documentation marks that deprecated as of the 2026-07-28 protocol version and recommends stderr for stdio servers or OpenTelemetry instead, so this server does not use it.
To see what a stray stdout line does, I added a console.log to a copy of the stdio entry point and connected the SDK's own client. A plain text line was silently skipped. A JSON log line was reported to the client's error handler as a Zod validation error, and the connection still worked. That is more forgiving than the SDK documentation's warning that a stray console.log corrupts the stream, and I only tested this one client. The specification says must not, so treat any stdout write as a bug. I also piped three raw JSON-RPC messages into the real stdio entry point and captured stdout separately: it held two lines, both JSON-RPC responses, and the log lines were on stderr.
#How the server checks who is calling
Authorization is optional in MCP. The specification's authorization page says implementations using an HTTP-based transport should conform to its flow, and implementations using stdio should not follow it and should retrieve credentials from the environment instead. That one sentence decides the design.
The HTTP flow it describes is built on OAuth 2.1. The MCP server acts as a resource server, the client sends Authorization: Bearer followed by the token on every HTTP request, tokens must not go in the URI query string, and an invalid or expired token gets a 401. An API key is not part of that flow, because nothing issues it, scopes it or expires it unless you build that. It does fit the transport rules: a bearer header, a 401 on failure, nothing in the URL. So the gate below checks a key where an OAuth server would validate a token. The SDK's requireBearerAuth middleware reads the header and produces the 401, and I supply the one function that decides whether a presented token is acceptable.
A key is the wrong tool on stdio. A stdio server is a child process of the host that launched it, and the MCP local server security guide says the client and a stdio server share one trust domain, so there is no network hop for a key to guard. What a stdio server does need is the credentials it uses itself, such as a key for an API it calls. The spec says to take those from the environment, and the same guide advises passing secrets per server through the per-server environment settings in the client's configuration, not by exporting them globally. This directory has no upstream API, so my stdio entry point reads none.
Four decisions in auth.ts are worth stating. Keys come from the MCP_API_KEYS environment variable as label and key pairs, and the process refuses to start if the variable is empty, a pair has no label, or a key is shorter than 32 characters. I ran the empty, short and unlabeled cases, and each exited with that error. The comparison uses SHA-256 digests and timingSafeEqual against every configured key, so neither the comparison nor the loop stops early on a match. The returned AuthInfo carries the label as clientId, which later shows up in the logs, and carries the word redacted as its token, so a tool handler never receives the key. Last, expiresAt is set 60 seconds ahead because the SDK's gate answers 401 for any token without an expiry. I removed that line to confirm it, and a correct key came back with the error description Token has no expiration time.
createMcpExpressApp returns an Express app with JSON body parsing and, on a localhost bind, Host and Origin validation, which is the defense against DNS rebinding. I sent a correct key with a Host header of evil.example and got a 403 with the message Invalid Host. The streamable HTTP page of the specification says servers must validate the Origin header and should bind only to localhost when running locally, which is why listen has an explicit 127.0.0.1. Binding to another interface needs the allowedHosts option on createMcpExpressApp.
The logging middleware sits before the auth middleware so rejected requests are recorded too. It logs the method, the path without the query string, the status, the caller label and the duration. It never reads a header.
#Running the same tools as a local command
That is the whole stdio entry point. It calls the same createServer, so the tools, the schemas and the logging are identical, and the logged caller is stdio because there is no authenticated caller to name. A host launches it as a command. I did not register it in a host such as Claude Desktop or an IDE for this post. The SDK documentation has a page for that.
#Run it and call it
Put two keys in a file named .env that is git-ignored, and load it in each terminal. I kept mine outside the project folder.
The server prints one JSON line to stderr saying where it is listening. In a second terminal, three curl calls show the gate: no key, a wrong key, and the front-desk key. The listing below trims the response headers to the status and the challenge, and cuts the last line.
I also sent the correct key as access_token in the URL query string, and that returned 401, because the gate reads only the header.
Curl exercises the gate, and a real client exercises the tools. This file uses the SDK's own client with the key supplied through an authProvider, which the SDK's client documentation describes as the way to bring a bearer token that something outside the SDK owns, such as an API key. It makes six tool calls, including two that fail the schema and one for an id that does not exist.
Run it from the project folder with the same environment loaded. The output below is the HTTP part of that run, and the stdio session that follows it returned the same six results.
The validation messages are the SDK's own, generated from the Zod schemas, and they name the field and the rule. The wrong key and the missing key fail at connect time, before any tool is listed, with different error classes: UnauthorizedError for the wrong key, and a plain HTTP error carrying the server's JSON body for the missing one.
I also ran the MCP Inspector in CLI mode against the same server, with the correct key in a header. The version matters here, as the next section explains.
#What the logs showed
These are lines from the server's stderr during that run, one of each kind: startup, an HTTP request that succeeded, a tool call, a tool call that returned an error, and a rejected request. The key is not in any of them.
After the run I searched the server's log and the client's stderr for both configured keys and for the wrong key the client sent, and found no matches in either file. That check is worth keeping as an automated test in a real project, because the failure it catches is a future edit that adds a header or a token to a log line.
One gap showed up. The two calls that failed schema validation appear in the log as HTTP requests with status 200, but there is no tool_call line for them. The SDK rejects them before the handler runs, so a wrapper inside the handler never sees them. If you want rejected calls counted, they need a different hook, and I did not build one.
#What did not go to plan
The server type-checked and ran on the first attempt. Four things still cost time or are worth knowing.
- The Inspector command from the documentation resolved to an old cached copy. Running npx @modelcontextprotocol/inspector with no version gave version 0.15.0 and the error Arguments cannot be passed to a URL-based MCP server, with exit code 1. Pinning @2.16.0 fixed it. That version declares Node ^22.23.4, ^24.22.1 or >=26.12.1 in its engines field, and npm printed engine warnings on Node 20.17.0, but the call above worked.
- A correct key with no expiry is rejected by requireBearerAuth. The SDK documentation warns about this, and I confirmed it by removing the expiresAt line and getting 401 with Token has no expiration time.
- The Inspector CLI treats a 401 as the start of an OAuth flow. With a wrong key or no key, it printed an auth_required error about interactive OAuth needing a TTY and exited with code 3. It does not say the key was wrong. The 401 from this server carries no resource metadata, and the Inspector still treats it as an OAuth prompt, so whoever is debugging a key-based server has to know to read the server's log or use curl.
- On re-reading my first version of auth.ts, a bare key with no label would have been parsed with almost all of itself as the label, and the label goes into the logs. I did not run that version with a bare key. I changed the parser to reject any pair without a label and ran the three bad-configuration cases above against the fixed version.
#What this demo does not do
The specification's security section for tools says servers must validate all tool inputs, implement proper access controls, rate limit tool invocations and sanitize tool outputs. This server validates inputs with Zod and has a single access check. It does not rate limit. It does not give different keys different scopes: every key receives the same clinic:read scope, although the SDK supports required scopes on the whole endpoint and per tool. Keys cannot expire or be revoked without a restart. And it speaks plain HTTP on the loopback interface, so a key sent to it over a network could be read by anything on the path. Put TLS in front of any deployment that is not loopback.
#What not to do
- Do not return secrets from tools. A tool result is handed to a model and the application that runs it, so keys, tokens and connection strings stay out of results and out of error text. That is why the AuthInfo token above is the word redacted.
- Do not add a write tool without a confirmation path. The specification says there should always be a human in the loop with the ability to deny tool invocations, but that is a SHOULD aimed at client applications, so a server cannot assume it is enforced. Annotations such as destructiveHint are hints the SDK does not enforce. I would split a write into two tools, a first that returns what would change plus a short-lived confirmation code, and a second that applies the change only when given that code. That pattern is my suggestion and is not built here.
- Do not expose an unauthenticated HTTP server. The specification says servers should implement proper authentication for all connections, and a tool server with no check hands anyone who finds the URL your data.
- Do not put the key in the URL. The specification forbids access tokens in the query string, and URLs end up in access logs and browser history.
- Do not log argument values, request headers or the Authorization header. Log names, counts, status and the caller label.
- Do not bind to 0.0.0.0 without naming the hosts you serve. Binding to all interfaces drops the default Host check that stops DNS rebinding.
- Do not let a tool fetch a URL the caller supplies. The SDK documentation warns that this lets any connected client send requests from your server's network position. Resolve an identifier against a fixed list instead.
#When an API key is not enough
I would use a static key for a server with a handful of callers you know, on a private network, behind TLS, where a restart to rotate a key is acceptable. I would move to OAuth when many clients you do not control connect, when you need to know which person made a call, or when you need expiry and revocation without redeploying. The SDK's authorization page covers that path: requireBearerAuth with a verifier that checks a JWT or calls token introspection, scope checks, and a published protected resource metadata document that tells clients where to sign in. It also says the SDK never issues tokens and points new servers at a dedicated identity provider. I did not build that here.
The tools here return synthetic rows. If the same pattern fronts a real clinic system, a key check and read-only tools do not make it HIPAA-aware on their own. Tool results travel to whichever model the caller's application uses, and whether that is acceptable for patient information, and under which agreement, is a decision for the clinic's compliance adviser. My HIPAA-aware software development page covers the requirements and common mistakes on the build side. This is not legal advice.
#Questions about building an MCP server in TypeScript
#Next step
If you want an MCP server or other AI tooling built over your own system, send what the system is, what data the tools would touch and who would call them through an estimate request or the contact page, and I will tell you what is feasible. My healthcare workflow automation page covers six clinic tasks worth automating first. The AI Lab lists this guide next to related guides and runnable demos.
Last checked on November 22, 2026 against the MCP specification revision 2026-07-28, the TypeScript SDK v2 documentation at ts.sdk.modelcontextprotocol.io/v2 and the package versions listed above. The SDK and the specification both change, so check the current documentation before you build. This is not legal advice.
#Sources
- Model Context Protocol specification 2026-07-28 (modelcontextprotocol.io/specification/2026-07-28): Authorization (basic/authorization), Transports, stdio and Streamable HTTP (basic/transports), Tools (server/tools)
- MCP documentation 2026-07-28: Local Server Security, MCP Inspector CLI client (modelcontextprotocol.io/docs/2026-07-28/tools/inspector/cli)
- MCP TypeScript SDK README, main branch (github.com/modelcontextprotocol/typescript-sdk), and v2 documentation (ts.sdk.modelcontextprotocol.io/v2): Build your first server, Build your first client, Tools, Serve over HTTP, Serve with Express, Require authorization, Authenticate without a user, Logging, progress and cancellation, stdio
- npm registry pages for @modelcontextprotocol/server, client, express, node and sdk, and for the Inspector, checked November 22, 2026
Stay updated with new posts
Get notified when I publish new articles about web development, system design, and AI. No spam, unsubscribe anytime.