The short answer: An MCP server is a small program that exposes tools, resources and prompts to AI applications through the Model Context Protocol. In TypeScript, install
@modelcontextprotocol/sdkandzod, create anMcpServer, register tools withregisterTool(a name, a description, an input schema and a handler), connect aStdioServerTransport, and add the compiled script to your AI client's configuration. Never write logs to stdout in a stdio server, test it with the MCP Inspector, and keep each tool narrow and well described.
The Model Context Protocol (MCP) gives AI applications a standard way to connect to outside capabilities. Instead of every assistant inventing its own plugin format, an MCP server exposes tools, data and prompt templates once, and any MCP-compatible client (desktop assistants, coding agents, IDE integrations) can use them. If you've wanted your AI assistant to query your issue tracker, read internal documentation or run a project-specific script, an MCP server is how you give it that ability.
This tutorial builds a small but realistic server in TypeScript, step by step. By the end you'll have a server with two tools (one of which calls an external API), a resource, proper error handling and configuration through environment variables, and you'll know how to test it and connect it to a client. The code uses version 1.x of the official TypeScript SDK; if you're on a newer major version, check the SDK's documentation for any changed import paths.
MCP in five minutes
Three roles make up an MCP setup. The host is the AI application the user interacts with, such as a desktop assistant or a coding agent. Inside the host, an MCP client maintains a connection to each server. Your server is the part you write.
Servers can offer three kinds of things:
- Tools: functions the model can decide to call, such as "search issues" or "create a draft invoice." Each has a name, a description and an input schema.
- Resources: read-only data identified by a URI, such as a configuration file or a document, which the host can pull into context.
- Prompts: reusable prompt templates the user can pick, often with arguments.
Messages use JSON-RPC 2.0. For local servers, the usual transport is stdio: the host starts your server as a child process and exchanges messages over its standard input and output. For remote servers, the protocol defines a Streamable HTTP transport. This tutorial uses stdio because it's the simplest to get running. For a deeper look at the architecture and security model, see the companion guide to the Model Context Protocol.
Prerequisites
- Node.js 18 or later (a current LTS release is best).
- Basic TypeScript knowledge.
- An MCP-compatible client to test with, such as a desktop AI assistant or a coding agent that supports MCP servers.
Setting up the project
mkdir issue-helper-mcp && cd issue-helper-mcp
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node
npx tsc --init
Edit package.json to use ES modules and add a build script:
{
"name": "issue-helper-mcp",
"version": "1.0.0",
"type": "module",
"bin": { "issue-helper-mcp": "build/index.js" },
"scripts": {
"build": "tsc",
"inspect": "npx @modelcontextprotocol/inspector node build/index.js"
}
}
And set the important compiler options in tsconfig.json:
{
"compilerOptions": {
"target": "ES2022",
"module": "Node16",
"moduleResolution": "Node16",
"outDir": "./build",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true
},
"include": ["src/**/*"]
}
The Node16 module settings matter, because the SDK's import paths end in .js and rely on Node's ES module resolution.
Creating the server
Create src/index.ts with the smallest working server:
#!/usr/bin/env node
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: "issue-helper", version: "1.0.0" });
// Tools and resources are registered here.
const transport = new StdioServerTransport();
await server.connect(transport);
That's a complete MCP server, although it doesn't offer anything yet. The name and version are reported to clients during the initial handshake.
Rule one: never log to stdout
With the stdio transport, standard output is the protocol channel. Anything else written there, such as a stray console.log, corrupts the JSON-RPC stream and the client will fail with confusing parse errors. Use console.error for debugging output, which goes to standard error, or the SDK's logging support, which sends structured log messages to the client.
Registering your first tool
A tool has three parts: metadata that tells the model what it does, an input schema that defines its arguments, and a handler that does the work. Start with something self-contained: a tool that turns a free-text bug report into a structured issue draft.
server.registerTool(
"draft_issue",
{
title: "Draft an issue",
description:
"Turn a bug report into a structured issue draft with a title, steps to reproduce and a severity. " +
"Use when the user describes a bug and wants to file it. Does not create anything; it only returns a draft.",
inputSchema: {
report: z.string().min(10).describe("The user's description of the bug, in their words"),
severity: z.enum(["low", "medium", "high"]).default("medium").describe("How serious the bug is"),
},
},
async ({ report, severity }) => {
const title = report.split(/[.!?\n]/)[0].slice(0, 80);
const draft = [
`Title: ${title}`,
`Severity: ${severity}`,
"",
"Description:",
report,
"",
"Steps to reproduce:",
"1. (fill in)",
].join("\n");
return { content: [{ type: "text", text: draft }] };
},
);
Look at the description closely, because it matters more than the code. The model chooses tools based on their descriptions, so a good one says what the tool does, when to use it, and what it doesn't do ("does not create anything"). The .describe() calls on each argument end up in the schema the model sees. The guide to designing tools for AI agents covers these principles in depth.
The handler returns an object with a content array. Text content is the most common, but tools can also return images and embedded resources.
A tool that calls an external API
Most useful servers wrap an existing API. Here's a tool that searches issues in a GitHub repository using GitHub's public search API, with proper error handling and a structured result:
const GITHUB_TOKEN = process.env.GITHUB_TOKEN; // optional; raises rate limits
server.registerTool(
"search_issues",
{
title: "Search GitHub issues",
description:
"Search open and closed issues in a GitHub repository by keywords. " +
"Returns up to 10 matches with number, title, state and URL. Use before drafting a new issue to avoid duplicates.",
inputSchema: {
repo: z.string().regex(/^[\w.-]+\/[\w.-]+$/).describe("Repository as owner/name, e.g. vercel/next.js"),
query: z.string().min(2).describe("Keywords to search for"),
},
outputSchema: {
results: z.array(z.object({ number: z.number(), title: z.string(), state: z.string(), url: z.string() })),
},
},
async ({ repo, query }) => {
const q = encodeURIComponent(`${query} repo:${repo} is:issue`);
const res = await fetch(`https://api.github.com/search/issues?q=${q}&per_page=10`, {
headers: {
Accept: "application/vnd.github+json",
"User-Agent": "issue-helper-mcp",
...(GITHUB_TOKEN ? { Authorization: `Bearer ${GITHUB_TOKEN}` } : {}),
},
});
if (!res.ok) {
return {
content: [{ type: "text", text: `GitHub search failed with status ${res.status}. Check the repository name, or try again later.` }],
isError: true,
};
}
const data = (await res.json()) as { items: { number: number; title: string; state: string; html_url: string }[] };
const results = data.items.map((i) => ({ number: i.number, title: i.title, state: i.state, url: i.html_url }));
return {
content: [{ type: "text", text: JSON.stringify({ results }, null, 2) }],
structuredContent: { results },
};
},
);
Three details here are worth copying into every tool you write:
- Errors are returned, not thrown. Returning
isError: truewith a helpful message lets the model see what went wrong and adjust, for example by correcting the repository name. An exception just produces a generic failure. - Validation happens in the schema. The regex on
reporejects malformed input before your code runs, and the error explains why. - Structured output is offered alongside text. The
outputSchemaandstructuredContentlet clients that support structured results use the data directly, while the text version keeps older clients working.
Adding a resource
Resources expose read-only data. Here's one that serves your team's issue-writing guidelines, so the host can include them in context when drafting issues:
import { readFile } from "node:fs/promises";
server.registerResource(
"issue-guidelines",
"guidelines://issues",
{
title: "Issue writing guidelines",
description: "The team's conventions for titles, labels and reproduction steps",
mimeType: "text/markdown",
},
async (uri) => ({
contents: [{ uri: uri.href, text: await readFile(new URL("../GUIDELINES.md", import.meta.url), "utf8") }],
}),
);
Whether and how a resource is shown to the model is up to the host: some let users attach resources explicitly, others let the application decide. That's the key difference from tools, which the model invokes itself.
Configuration through environment variables
Servers often need secrets, such as API tokens. For stdio servers, the host passes environment variables when it starts the process, and the MCP specification says stdio implementations should take credentials from the environment rather than using the HTTP authorization flow. Read them once at startup and fail clearly if a required one is missing:
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
console.error(`Missing required environment variable ${name}`);
process.exit(1);
}
return value;
}
Never hard-code tokens in the server source, and give each token the narrowest permissions that work. A read-only token for a search tool limits the damage if the model is ever tricked into misusing it.
Building and testing with the MCP Inspector
Build the server, then open it in the MCP Inspector, an official browser-based tool for testing servers:
npm run build
npm run inspect
The Inspector starts your server, connects to it, and lets you list tools and resources, call tools with arguments, and see the raw messages. Use it to check that descriptions read well, that schemas reject bad input, and that errors come back as helpful messages. It's much faster than debugging through an AI client, where you can't easily see what was sent.
Connecting to a client
Each MCP client has its own configuration format, but most follow the same shape: a server name, the command to run, its arguments and environment variables. A typical entry looks like this:
{
"mcpServers": {
"issue-helper": {
"command": "node",
"args": ["/absolute/path/to/issue-helper-mcp/build/index.js"],
"env": { "GITHUB_TOKEN": "your-read-only-token" }
}
}
}
Use absolute paths, since the client may start the process from a different working directory. After restarting or reloading the client, ask it something that should trigger your tool, such as "search vercel/next.js for issues about image caching," and check that it calls search_issues. If the tool doesn't appear, check the client's MCP logs; the usual causes are a wrong path, a build that didn't run, or something printing to stdout.
Structuring a larger server
Once a server has more than a few tools, split it up so it stays maintainable:
src/
index.ts // creates the server, registers modules, connects transport
config.ts // reads and validates environment variables
tools/
issues.ts // export function registerIssueTools(server: McpServer) { ... }
releases.ts
resources/
guidelines.ts
lib/
github.ts // shared API client with auth, retries and error mapping
Each module exports a function that takes the server and registers its tools. Shared concerns, such as the API client, error formatting and retries, live in one place. Keep the number of tools modest: every tool's description competes for the model's attention, and a server with dozens of overlapping tools makes the model's choices worse. Ten clear tools beat forty vague ones.
Under the hood
It helps to know what the SDK is doing for you. When the client starts your process, it sends an initialize request with its protocol version and capabilities; your server replies with its own, including the fact that it offers tools and resources. The client then calls tools/list to get your tool names, descriptions and JSON Schemas (the SDK converts your Zod schemas). When the model decides to use a tool, the client sends tools/call with the arguments, the SDK validates them against your schema, runs your handler, and sends back the result. Resources follow the same pattern with resources/list and resources/read.
Seeing these messages in the Inspector makes debugging much easier, and it's a reminder that the model only ever sees what's in those messages. If a tool is misused, the fix is almost always in its name, description or schema.
Security basics for your first server
Even a small local server deserves some care, because it gives a language model the ability to act:
- Prefer read-only tools until you need writes, and make write tools explicit in their names and descriptions.
- Validate everything, including values that look safe. File paths, shell arguments and URLs from the model are untrusted input.
- Never pass model input to a shell. If a tool must run a command, use a fixed command with validated arguments, not string concatenation.
- Remember prompt injection. Content your tools return, such as issue text written by strangers, can contain instructions aimed at the model. The guide to prompt injection explains why that matters and how to limit the damage.
- Install third-party servers carefully. A server runs with your user's permissions. Review the code or the publisher before adding one.
Ideas for what to build next
- A documentation server that searches your internal docs and returns relevant sections.
- A database server with read-only, parameterised query tools for common questions.
- A deployment helper that reports build status and recent errors from your hosting platform.
- A project-specific server that runs your test suite or linter and returns a summary.
Each follows the same pattern as this tutorial: a few narrow tools with clear descriptions, validated inputs, helpful errors, and credentials from the environment.
Adding a prompt template
The third MCP primitive, prompts, lets your server offer ready-made instructions that users can choose in their client, often as a command or menu item. For the issue helper, a natural prompt is "triage this bug report," which combines your guidelines with the user's text. With the 1.x SDK, prompts are registered in the same style as tools:
server.registerPrompt(
"triage_bug",
{
title: "Triage a bug report",
description: "Check a bug report for duplicates and draft a well-structured issue",
argsSchema: { repo: z.string(), report: z.string() },
},
({ repo, report }) => ({
messages: [
{
role: "user",
content: {
type: "text",
text:
`Here is a bug report for ${repo}:\n\n${report}\n\n` +
"First use search_issues to look for duplicates. If none match, use draft_issue " +
"to produce a draft that follows our issue guidelines. Show me the draft before anything else.",
},
},
],
}),
);
Prompts are a good way to package know-how about using your own tools well. The model still decides how to act, but a well-written prompt steers it toward the sequence that works, such as searching before drafting. How prompts appear depends on the client; some show them as slash commands, others in a menu. Check the SDK documentation for your version, as argument handling has been refined across releases.
Testing your tools automatically
The Inspector is great for exploring, but you'll want automated tests too, so changes don't break existing tools. Keep each tool's logic in a plain function and register a thin wrapper, so you can test the logic without the protocol:
// src/tools/draft.ts
export function buildIssueDraft(report: string, severity: "low" | "medium" | "high"): string {
const title = report.split(/[.!?\n]/)[0].slice(0, 80);
return [`Title: ${title}`, `Severity: ${severity}`, "", "Description:", report].join("\n");
}
// src/tools/draft.test.ts
import { describe, it, expect } from "vitest";
import { buildIssueDraft } from "./draft";
describe("buildIssueDraft", () => {
it("uses the first sentence as the title", () => {
const draft = buildIssueDraft("Export fails on Safari. Steps below.", "high");
expect(draft).toContain("Title: Export fails on Safari");
expect(draft).toContain("Severity: high");
});
});
For tools that call external APIs, inject the HTTP client or mock fetch, and test the error paths: a 404, a rate limit, a timeout and malformed responses. These are the cases where a helpful error message matters most, and they're the hardest to trigger by hand.
For a full end-to-end check, the SDK also includes a client. A small script can start your server over stdio, list its tools and call one, which makes a useful smoke test in CI to confirm the server starts and registers everything correctly.
Publishing and sharing your server
Once the server is useful, you'll want others to run it. The simplest route for a TypeScript server is publishing it as an npm package with a bin entry, as set up in the package.json earlier. Users can then run it with npx in their client configuration instead of cloning and building it.
Before publishing, add the things users need to trust and use it:
- A README listing every tool and resource, what each one does, required environment variables and the permissions each token needs.
- A configuration example for at least one popular client.
- Semantic versioning and a changelog, especially for changes to tool names, arguments or behaviour, since users' workflows depend on them.
- A clear statement of what the server can access, so users can make an informed decision before installing it.
For servers meant to be shared across a team or offered as a service, consider a remote server using the Streamable HTTP transport instead, so you deploy updates once and handle authentication centrally. The MCP deep dive covers remote deployment and authorization.
Troubleshooting common problems
- The client says the server failed to start. Run the exact command from the client configuration in a terminal. Missing builds, wrong paths and missing environment variables show up immediately.
- Parse errors or garbled messages. Something is writing to stdout. Search for
console.login your code and dependencies' startup output, and switch toconsole.error. - Tools appear but are never used. The model doesn't see why it should use them. Rewrite the descriptions to say what each tool does and when to use it, and check that names are clear.
- The wrong tool gets called. Two tools probably overlap. Make their descriptions distinct, or merge them.
- Validation errors on every call. The schema may be stricter than the model expects. Add
.describe()text with examples of valid values, and check the error messages the model receives. - Changes don't take effect. Rebuild, then restart or reload the client. Most clients start the server once and keep it running.
- Import errors at startup. Check that
package.jsonhas"type": "module"and thattsconfig.jsonuses theNode16module settings, since the SDK relies on ES module resolution.
When in doubt, go back to the Inspector. If a tool works there but not in your client, the problem is in the client configuration; if it fails in the Inspector too, it's in the server.
Designing tools around tasks
When you wrap an existing API, it's tempting to create one tool per endpoint. That usually makes the model's job harder. A user asking "is there already an issue about slow exports, and if not, draft one" needs a search and a draft, not a dozen low-level calls that the model has to chain correctly.
Start from the tasks users actually want to accomplish, then design the smallest set of tools that covers them, each completing a meaningful step. Return just the fields the model needs to continue, not entire API responses: large, noisy results waste context and make mistakes more likely. Use consistent naming, such as a verb and a noun in the same style across all tools, so the model can predict what each one does. And when a tool fails, say what to do next, for example "repository not found; check the owner/name format," because that message is the only guidance the model gets.
These choices matter more than any SDK detail. A server with three well-designed tools will be used more successfully than one with thirty thin wrappers.
The finished project at a glance
By this point your server has two tools (a self-contained draft tool and an API-backed search tool with structured output), a resource serving your guidelines, a prompt that combines them, configuration through environment variables, unit tests for tool logic and a manual testing workflow with the Inspector. That's the same shape as most production MCP servers: a few narrow, well-described capabilities wrapped around an existing system, validated at the edges and safe to run with limited credentials. Everything else you build will be a variation on this pattern, with more tools, a different API, or a remote transport.
Keep the project in version control from the start, with the README, tests and a sample client configuration alongside the code. When you come back to it in a few months, or hand it to a colleague, everything needed to understand, run and extend the server will be in one place, and the next tool you add will take minutes rather than an afternoon.
Frequently asked questions
What is an MCP server?
An MCP server is a program that exposes tools, resources and prompt templates to AI applications using the Model Context Protocol. Any MCP-compatible client, such as a desktop assistant or a coding agent, can connect to it and let the model call its tools or read its data.
How do I create an MCP server in TypeScript?
Install the official SDK package @modelcontextprotocol/sdk and zod, create an McpServer with a name and version, register tools with registerTool using a description, a Zod input schema and a handler, then connect a StdioServerTransport. Build it with tsc and add the compiled script to your client's MCP configuration.
Why is my MCP server not showing up in my client?
Common causes are a wrong or relative path in the client configuration, forgetting to rebuild after changes, missing environment variables, or code that writes to stdout, which corrupts the stdio protocol stream. Check the client's MCP logs and test the server on its own with the MCP Inspector.
What is the difference between MCP tools and resources?
Tools are functions the model decides to call, with arguments, to take an action or fetch information. Resources are read-only data identified by a URI, which the host application or user chooses to bring into context. Use tools for actions and queries, and resources for reference material.
How should an MCP server handle API keys?
For local servers using the stdio transport, read credentials from environment variables that the client passes when it starts the server, and never hard-code them. Give each token the narrowest permissions it needs. Remote servers using HTTP follow the protocol's OAuth-based authorization flow instead.
The takeaway
An MCP server is a small program with a big effect: it turns your APIs, data and scripts into capabilities any MCP-compatible assistant can use. Start with one or two narrow tools, write descriptions as carefully as code, return helpful errors, keep stdout clean and secrets in the environment, and test with the Inspector before connecting a client. Once the first server works, the second one takes an afternoon.
Author at LuminaryEra
The LuminaryEra editorial desk publishes long-form, hands-on guides on AI-assisted development, large language models, developer tools and web engineering. Articles are researched and drafted with the help of AI tools, link to their sources, and are corrected when readers report errors.
View all articles




