Pogton

Build Your Own MCP Server with TypeScript: A Complete Guide

Want to create custom tools for Claude? Here's how to build your own Model Context Protocol server with TypeScript and deploy it anywhere...

Written by
Anton AndresenFounder, Pogton Technologies
Published
Reading time
8 min read
Tags
Development
Build Your Own MCP Server with TypeScript: A Complete Guide

Have you ever wanted to give Claude custom superpowers?

That's exactly what Model Context Protocol (MCP) servers let you do... They're basically a way to extend AI clients like Claude, Cursor, or any other MCP-compatible tool with your own custom functions...

And honestly, it's way easier than you might think...

What the Heck is MCP Anyway?

MCP is a standardized protocol that lets you connect AI clients to external tools and data sources...

Think of it like giving your AI access to your APIs, databases, or any custom functionality you want... The amazing thing is that once you build an MCP server, it works with ALL modern MCP clients...

That means your server will work with:

  • Claude (via the desktop app or API)
  • Cursor (the AI code editor)
  • Any other MCP-compatible client

The cool part? You can build these servers in any language and deploy them anywhere... I'm gonna show you how to do it with TypeScript because, well, TypeScript is awesome...

Setting Up Your MCP Server

First, let's get the dependencies sorted...

You'll need the MCP SDK and some other basics:

npm install @modelcontextprotocol/sdk zod
# If you're using Nitro (like I am), you're already set
# For Express, add: npm install express @types/express

Important: MCP requires Node.js v18.x or higher to work properly...

The core idea is pretty simple... You create a server, register some tools, and handle HTTP requests using the StreamableHTTPServerTransport...

The Complete MCP Server Code

Here's the full implementation I'm using in my Nitro app:

import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";

export default defineEventHandler(async (event) => {
  if (['GET', 'DELETE'].includes(event.method)) {
    event.node.res.writeHead(405).end(JSON.stringify({
      jsonrpc: "2.0",
      error: {
        code: -32000,
        message: "Method not allowed."
      },
      id: null
    }))
  }

  if (event.method === 'POST') {
    const body = await readBody(event)
    try {
      const server = getServer()
      const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
        sessionIdGenerator: undefined,
      });
      
      event.node.res.on('close', () => {
        console.log('Request closed')
        transport.close()
        server.close()
      })
      
      await server.connect(transport)
      await transport.handleRequest(event.node.req, event.node.res, body)
      return
    } catch (error) {
      console.error('Error handling MCP request:', error);
      if (!event.node.res.headersSent) {
        return event.node.res.writeHead(500).end(JSON.stringify({
          jsonrpc: '2.0',
          error: {
            code: -32603,
            message: 'Internal server error',
          },
          id: null,
        }))
      }
    }
  }

  // Return 404 for all other methods
  return event.node.res.writeHead(404).end()
})

const getServer = () => {
  // Create an MCP server
  const server = new McpServer({
    name: "your-mcp-server-name",
    version: "1.0.0"
  });

  // Add an addition tool
  server.registerTool("add",
    {
      title: "Addition Tool",
      description: "Add two numbers",
      inputSchema: { a: z.number(), b: z.number() }
    },
    async ({ a, b }) => ({
      content: [{ type: "text", text: String(a + b) }]
    })
  )

  return server
}

Let me break this down for you...

How It Actually Works

The magic happens in a few key parts:

1. HTTP Method Handling We only accept POST requests because that's how MCP communication works... Everything else gets a nice error response...

2. Transport Layer The StreamableHTTPServerTransport handles the connection between Claude and your server... It's basically the bridge that makes everything work...

3. Server Creation We create a new MCP server instance with a name and version... This is what Claude will see when it connects...

4. Tool Registration This is where you define what your server can actually do... In this example, it's just adding two numbers, but you can build way more complex stuff...

The modern way to register tools uses server.registerTool() which gives you better TypeScript support and cleaner APIs...

Adapting for Express (Or Any Framework)

The beauty of this approach is that it works everywhere...

For Express, you'd do something like this:

import express from 'express';
// ... other imports

const app = express();
app.use(express.json());

app.post('/mcp', async (req, res) => {
  try {
    const server = getServer();
    const transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: undefined,
    });
    
    res.on('close', () => {
      transport.close();
      server.close();
    });
    
    await server.connect(transport);
    await transport.handleRequest(req, res, req.body);
  } catch (error) {
    console.error('MCP Error:', error);
    if (!res.headersSent) {
      res.status(500).json({
        jsonrpc: '2.0',
        error: { code: -32603, message: 'Internal server error' },
        id: null,
      });
    }
  }
});

Same logic, different framework... Pretty nice, right?

Important Note: The example above creates a new server instance for each request (stateless mode)... This is perfect for simple use cases, but if you need session management, you'd want to store transports by session ID...

Check out the official MCP SDK docs for examples of both stateless and session-based implementations...

Understanding MCP Capabilities

Before we dive into building tools, let's talk about what MCP servers can actually do...

There are three main types of features you can implement:

Tools - These are like POST endpoints... They perform actions and can have side effects:

server.registerTool("send-email",
  {
    title: "Send Email",
    description: "Send an email to someone",
    inputSchema: { 
      to: z.string().email(), 
      subject: z.string(), 
      body: z.string() 
    }
  },
  async ({ to, subject, body }) => {
    await sendEmail(to, subject, body);
    return {
      content: [{ type: "text", text: `Email sent to ${to}` }]
    };
  }
);

Resources - These are like GET endpoints... They provide data but shouldn't have side effects:

server.registerResource(
  "user-profile",
  new ResourceTemplate("users://{userId}/profile", { list: undefined }),
  {
    title: "User Profile",
    description: "Get user profile information"
  },
  async (uri, { userId }) => ({
    contents: [{
      uri: uri.href,
      text: JSON.stringify(await getUserProfile(userId))
    }]
  })
);

Prompts - These are reusable templates for AI interactions:

server.registerPrompt(
  "code-review",
  {
    title: "Code Review",
    description: "Review code for best practices",
    argsSchema: { code: z.string() }
  },
  ({ code }) => ({
    messages: [{
      role: "user",
      content: {
        type: "text",
        text: `Please review this code:\n\n${code}`
      }
    }]
  })
);

Pretty powerful stuff, right?

Building Useful Tools

The addition example is cute, but let's be real... You probably want to build something more useful...

Here are some ideas that actually make sense:

Database Queries

server.registerTool("query_users",
  {
    title: "Query Users",
    description: "Search for users in the database",
    inputSchema: { query: z.string(), limit: z.number().optional() }
  },
  async ({ query, limit = 10 }) => {
    const users = await db.user.findMany({
      where: { name: { contains: query } },
      take: limit
    });
    return { content: [{ type: "text", text: JSON.stringify(users) }] };
  }
)

API Integrations

server.registerTool("get_weather",
  {
    title: "Get Weather",
    description: "Get current weather for a location",
    inputSchema: { location: z.string() }
  },
  async ({ location }) => {
    const weather = await fetch(`https://api.weather.com/v1/current?location=${location}`);
    const data = await weather.json();
    return { content: [{ type: "text", text: JSON.stringify(data) }] };
  }
)

File Operations

server.registerTool("read_file",
  {
    title: "Read File",
    description: "Read contents of a file",
    inputSchema: { path: z.string() }
  },
  async ({ path }) => {
    const content = await fs.readFile(path, 'utf-8');
    return { content: [{ type: "text", text: content }] };
  }
)
)

The possibilities are honestly endless...

Deployment Made Easy

Since this is just HTTP, you can deploy it literally anywhere...

Vercel/Netlify: Perfect for simple tools and integrations Railway/Render: Great for more complex servers with databases Your own VPS: Full control, do whatever you want

Just make sure your endpoint is publicly accessible so Claude can reach it...

Testing Your MCP Server

There are a few ways to test your MCP server...

Option 1: MCP Inspector (Recommended) The easiest way is using the official MCP Inspector:

npx @modelcontextprotocol/inspector http://localhost:3000/routes/mcp

This gives you a nice web interface to test all your tools, resources, and prompts...

Option 2: Manual Testing You can also test with curl if you want to go old school:

curl -X POST http://localhost:3000/routes/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
      "name": "add",
      "arguments": { "a": 5, "b": 3 }
    },
    "id": 1
  }'

Option 3: Connect to Claude Desktop Once your server is running, you can add it to Claude Desktop's configuration and test it in real conversations...

Option 4: Connect to Cursor If you're using Cursor (the AI code editor), you can add your server to the MCP settings...

Open Cursor Settings and add this to your MCP configuration:

{
  "mcpServers": {
    "your-mcp-server-name": {
      "type": "http",
      "url": "http://localhost:3000/routes/mcp"
    }
  }
}

Then just let that connect, and your MCP server will be available for AI interactions...

What's Next?

This is just the beginning...

You could build MCP servers for pretty much anything:

  • Custom analytics dashboards
  • Internal company tools
  • Database management
  • File system operations
  • Third-party API integrations

The cool thing is that once you build it, Claude can use it naturally in conversation...

Want to see more advanced examples? I'm thinking about open-sourcing some of the MCP servers we use at Pogton... Would that be useful?

Let me know what kind of tools you'd want to build with this...

Share

Written by

Anton AndresenFounder, Pogton Technologies

Tech and AI entrepreneur. Founder of Pogton Technologies. Building technology companies with a focus on AI, software development and product.

Get in touch

Have a project in mind? Let's talk.

Tell us about your project and we'll get back to you within 24 hours with a tailored plan.