AI Development

How to Build an MCP Server: Step-by-Step Tutorial

November 18, 2026 · 13 min read

How to Build an MCP Server: Step-by-Step Tutorial

Connecting an AI agent to your own systems used to mean writing a custom integration for every AI tool. The Model Context Protocol (MCP) changed that: you build one server that describes your tools, and any MCP-compatible AI application can use them. If you want to build MCP server integrations for your product or internal systems, this tutorial gives you a working starting point.

You will build a small "ticket desk" server with two tools and one resource, test it with the MCP Inspector, connect it to Claude Code, see the same server in Python, and learn the security and design rules that separate a demo from a production server. The code uses the official TypeScript SDK v2, released in July 2026 for the 2026-07-28 MCP specification, and it has been run end to end with a real MCP client.

What You Will Build and What You Need

The ticket desk server lets an AI agent work with support tickets:

  • list_tickets: a read-only tool that lists tickets, optionally filtered by status.
  • create_ticket: a write tool that creates a ticket with a validated title and priority.
  • triage-guide: a resource containing the team's rules for setting priority.

To follow along you need Node.js 20 or later, basic TypeScript knowledge and a terminal. You do not need an AI model API key to build and test the server, because the MCP Inspector lets you call tools directly. If MCP is new to you, read our developer's guide to the Model Context Protocol first for the concepts behind hosts, clients and servers.

Step 1: Plan Your Tools Before You Write Code

The quality of an MCP server depends more on tool design than on code. The model decides which tool to call by reading names, descriptions and input schemas, so treat those as prompts. Follow these rules:

  • Keep the tool list short. A few well-defined tools beat dozens of overlapping ones. Too many choices confuse the model and fill its context window.
  • Name tools as verbs. Names such as list_tickets and create_ticket say exactly what happens.
  • Write descriptions for a new colleague. Explain what the tool does, when to use it and what it returns.
  • Type every input. Use enums for fixed choices, length limits for text and sensible defaults.
  • Separate reads from writes. Read-only tools are safe to call freely. Write tools should be narrow and easy to audit.
  • Return compact results. Send what the model needs, not entire database rows or megabytes of logs.

Step 2: Set Up the Project

Create a folder and install the v2 server package, Zod for input schemas and tsx to run TypeScript without a build step:

mkdir ticket-desk && cd ticket-desk
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server zod tsx
mkdir src

The type=module setting matters because the SDK ships as ES modules only. If you have used MCP before, note that v2 replaces the single @modelcontextprotocol/sdk package from v1 with separate server and client packages. Old imports such as @modelcontextprotocol/sdk/server/mcp.js belong to v1.

Step 3: Write the Server

Create src/index.ts with the following code:

import { McpServer } from "@modelcontextprotocol/server";
import { serveStdio } from "@modelcontextprotocol/server/stdio";
import * as z from "zod/v4";

type Ticket = {
  id: string;
  title: string;
  status: "open" | "closed";
  priority: "low" | "medium" | "high";
};

// In a real server this would be your database or helpdesk API.
const tickets: Ticket[] = [
  { id: "T-101", title: "Checkout page times out on mobile", status: "open", priority: "high" },
  { id: "T-102", title: "Update the privacy policy link", status: "open", priority: "low" },
  { id: "T-103", title: "Add Apple Pay to checkout", status: "closed", priority: "medium" },
];

function createServer(): McpServer {
  const server = new McpServer({ name: "ticket-desk", version: "1.0.0" });

  server.registerTool(
    "list_tickets",
    {
      title: "List tickets",
      description: "List support tickets. Optionally filter by status (open or closed).",
      inputSchema: z.object({
        status: z.enum(["open", "closed"]).optional().describe("Only return tickets with this status"),
      }),
      annotations: { readOnlyHint: true },
    },
    async ({ status }) => {
      const rows = tickets.filter((t) => !status || t.status === status);
      return { content: [{ type: "text", text: JSON.stringify(rows, null, 2) }] };
    }
  );

  server.registerTool(
    "create_ticket",
    {
      title: "Create ticket",
      description: "Create a new support ticket and return its ID.",
      inputSchema: z.object({
        title: z.string().min(5).max(120).describe("Short summary of the problem"),
        priority: z.enum(["low", "medium", "high"]).default("medium"),
      }),
    },
    async ({ title, priority }) => {
      const id = `T-${101 + tickets.length}`;
      tickets.push({ id, title, status: "open", priority });
      return { content: [{ type: "text", text: `Created ${id} (${priority} priority)` }] };
    }
  );

  server.registerResource(
    "triage-guide",
    "docs://triage-guide",
    {
      title: "Triage guide",
      description: "How the support team sets ticket priority",
      mimeType: "text/markdown",
    },
    async (uri) => ({
      contents: [
        {
          uri: uri.href,
          text: "# Triage guide\n- high: customers cannot pay or log in\n- medium: a feature is broken but has a workaround\n- low: cosmetic issues and copy changes",
        },
      ],
    })
  );

  return server;
}

void serveStdio(createServer);
console.error("ticket-desk MCP server running on stdio");

Here is what each part does:

  • createServer: a factory function that builds a fresh McpServer with a name and version. The SDK's serveStdio helper calls it to create the server for each connection.
  • registerTool: takes a name, a config object and a handler. The inputSchema is a full Zod object. The SDK turns it into the JSON Schema the model sees and validates every call before your handler runs, so a title shorter than five characters is rejected automatically.
  • annotations: readOnlyHint tells clients that list_tickets does not change anything, which helps hosts decide when to ask the user for approval.
  • Handler results: each handler returns a content array of typed blocks. For a failure the model should read and recover from, return the message with isError set to true instead of throwing.
  • registerResource: exposes read-only context at a URI. The host application decides when to include it, so it suits reference material such as policies and schemas.
  • serveStdio: connects the server to standard input and output.

One rule catches almost everyone: with stdio, standard output carries the protocol messages. A single console.log corrupts the stream and breaks the connection. Always log to standard error with console.error, as the last line does.

Step 4: Test It With the MCP Inspector

The MCP Inspector is the official debugging client. It starts your server, connects to it and gives you a browser interface for calling tools:

# Start the server (it waits quietly for a client on stdin)
npx tsx src/index.ts

# Open the MCP Inspector in your browser and connect it to the server
npx @modelcontextprotocol/inspector npx tsx src/index.ts

In the Inspector, click Connect and work through this checklist:

  1. Open the Tools tab and confirm both tools appear with their descriptions and input fields.
  2. Call list_tickets with status set to open. You should see two tickets.
  3. Call create_ticket with a sensible title. The reply should be "Created T-104 (medium priority)", because priority defaults to medium.
  4. Call create_ticket with the title "Hi". The call should fail with an input validation error, proving your schema is enforced.
  5. Open the Resources tab and read docs://triage-guide.

We ran exactly these checks with an automated MCP client against the code above, and every one passed.

Step 5: Connect It to an AI Client

Once the server works in the Inspector, connect it to a real AI host. With Claude Code, one command registers a local stdio server. Everything after the double dash is the command Claude Code runs to start your server:

# Register the server with Claude Code (stdio is the default transport)
claude mcp add ticket-desk -- npx tsx /absolute/path/to/ticket-desk/src/index.ts

# Check that it connected
claude mcp list

To share the server with your team, add a .mcp.json file to the project root instead. Claude Code asks each developer to approve project-scoped servers the first time it sees them:

{
  "mcpServers": {
    "ticket-desk": {
      "command": "npx",
      "args": ["tsx", "/absolute/path/to/ticket-desk/src/index.ts"]
    }
  }
}

Other MCP clients, including VS Code with GitHub Copilot and Cursor, use similar JSON settings that point at the same command. Now ask your assistant "Which tickets are open?" and watch it call list_tickets. Many teams also describe their MCP tools in an AGENTS.md file so coding agents know when to use them.

Prefer Python? The Same Server in Python

The official Python SDK reached version 2 on 28 July 2026, the day the new specification shipped, and it renamed the popular FastMCP class to MCPServer. Type hints become the input schema, and Pydantic's Field adds validation rules such as minimum length:

from typing import Annotated, Literal

from pydantic import Field
from mcp.server.mcpserver import MCPServer

mcp = MCPServer("ticket-desk")

# In a real server this would be your database or helpdesk API.
tickets = [
    {"id": "T-101", "title": "Checkout page times out on mobile", "status": "open", "priority": "high"},
    {"id": "T-102", "title": "Update the privacy policy link", "status": "open", "priority": "low"},
    {"id": "T-103", "title": "Add Apple Pay to checkout", "status": "closed", "priority": "medium"},
]


@mcp.tool()
def list_tickets(status: Literal["open", "closed"] | None = None) -> list[dict]:
    """List support tickets. Optionally filter by status (open or closed)."""
    return [t for t in tickets if status is None or t["status"] == status]


@mcp.tool()
def create_ticket(
    title: Annotated[str, Field(min_length=5, max_length=120)],
    priority: Literal["low", "medium", "high"] = "medium",
) -> str:
    """Create a new support ticket and return its ID."""
    ticket_id = f"T-{101 + len(tickets)}"
    tickets.append({"id": ticket_id, "title": title, "status": "open", "priority": priority})
    return f"Created {ticket_id} ({priority} priority)"


if __name__ == "__main__":
    mcp.run()  # stdio by default

Install and run it like this:

pip install "mcp>=2"
python server.py

# Inspect it the same way as the TypeScript version
npx @modelcontextprotocol/inspector python server.py

This version passed the same client tests as the TypeScript server. If you have older code that imports FastMCP from mcp.server.fastmcp, either migrate it to MCPServer or pin mcp below version 2.

Step 6: Go Remote With Streamable HTTP

Stdio is perfect for tools that run on a developer's own machine. When many users or agents need the same server, run it as a web service over Streamable HTTP instead. The TypeScript SDK serves the same createServer factory over HTTP, and optional adapter packages integrate with Express, Fastify, Hono and plain Node.js.

The 2026-07-28 specification makes remote servers much easier to scale. Because the protocol is now stateless, any request can go to any server instance behind an ordinary load balancer, with no shared session store. Before you expose a server on the internet, though, you must add authorisation. Remote MCP servers act as OAuth resource servers, and the 2026-07-28 revision tightens several rules, including issuer validation and a preference for Client ID Metadata Documents over dynamic client registration. Our guide to AI agent identity and permissions explains the identity side in detail.

Security Checklist for Your MCP Server

An MCP server hands an AI model real power over your systems. Before production, make sure you can tick every item:

  • The server uses its own credentials with the narrowest permissions possible, never a shared admin key.
  • Write and delete tools are narrow, validated and logged, and high-impact actions require human approval in the host.
  • Inputs are validated by schema and checked again against business rules inside the handler.
  • Secrets and personal data never appear in tool descriptions, results or logs.
  • Results returned from external content, such as emails or web pages, are treated as untrusted data that may contain prompt injection.
  • Remote servers require authenticated, scoped tokens and enforce rate limits.
  • Every tool call is logged with the caller's identity, the arguments and the outcome.

Our guides to AI agent security and API security best practices go deeper on each control.

Common Mistakes and How to Fix Them

ProblemLikely causeFix
Client cannot connect or shows parse errorsconsole.log writing to standard outputLog with console.error only
"Cannot use import statement" errorProject is not an ES moduleRun npm pkg set type=module
Import errors after an upgradeMixing v1 and v2 package pathsUse @modelcontextprotocol/server imports throughout
Model picks the wrong toolVague names or overlapping toolsRename, merge tools and improve descriptions
Agent gets slow and expensiveHuge tool results filling the contextPaginate, filter and summarise results
Inspector works, host does notRelative paths or a missing runtime in the host's environmentUse absolute paths and check the host's logs

Oversized results deserve special attention. Every token a tool returns competes for the model's limited attention, which is why context engineering matters as much for server authors as for agent builders.

Publishing and Maintaining Your Server

If you want others to use your server, publish it as an npm or PyPI package and list it in the official MCP Registry, which stores each server's metadata in a server.json file under a verified namespace. Then maintain it like any other product: version your tools, avoid breaking input schemas, document changes and test against new SDK releases. As a rough estimate, a demo server like this takes an hour or two, while a production server for a real system, with authorisation, tests and monitoring, usually takes one to four weeks.

Frequently Asked Questions

Which language is best for building an MCP server?

Use the language your team and target system already use. TypeScript and Python have the most mature official SDKs and examples, while Go and C# also support the 2026-07-28 specification.

Do I need the v2 TypeScript SDK?

For new projects, yes. Version 2 implements the 2026-07-28 specification and is the stable release line. Version 1 is still maintained for existing servers, but new code should start on v2.

Can an MCP server call other APIs?

Yes. Most MCP servers are thin wrappers around existing REST or GraphQL APIs, databases or command-line tools. The server translates between MCP tool calls and those systems.

How do I debug an MCP server?

Start with the MCP Inspector to call tools directly and view raw messages. Log to standard error, check your host application's MCP logs and test each tool's error paths, not just the happy path.

How long does it take to build an MCP server?

A simple server with a few tools takes an hour or two. A production server with authorisation, tests, monitoring and documentation typically takes one to four weeks, depending on the system behind it.

Is it safe to let an AI agent use my MCP server?

It can be, if you apply least privilege, validate inputs, require approval for high-impact actions and treat external content as untrusted. Never give an agent broader access than the task requires.

Turn Your Systems Into AI-Ready Tools

You now know how to build MCP server tools, test them, connect them to an AI client and harden them for production. Start with one read-only tool on a real system, learn from how agents use it, then add carefully scoped write tools. If you would like an experienced team to design and build secure MCP servers for your product or internal platforms, contact us to discuss your project.

Want this built for you?

Our team offers Website Deploy On Vercel — get a free quote.

View Services