How to Build Custom MCP Servers in 2026 (And Connect Them to OpenClaw)
How to Build Custom MCP Servers in 2026 (And Connect Them to OpenClaw)

How to Build Custom MCP Servers in 2026 (And Connect Them to OpenClaw)

Last updated: March 2026 | No prior coding experience needed | Works with Claude Desktop, OpenClaw, Cursor, and more


What Is an MCP Server, Actually?

Imagine you have an AI assistant — Claude, OpenClaw, Cursor, whatever — and you want it to check your Google Sheets, send a WhatsApp message, or fetch the latest price of a product from a website.

Out of the box, it can’t do those things. It’s locked inside a conversation window.

An MCP server is the bridge that changes that. It’s a small program you build (or install) that gives your AI assistant new abilities — like new tools in a toolbox. The AI calls your server, your server does the actual work (fetching data, sending messages, running code), and hands the result back.

MCP stands for Model Context Protocol — an open standard created by Anthropic and now supported by Claude, OpenClaw, Cursor, VS Code, and hundreds of other tools. Think of it like USB: one standard connector, works with everything.

Three things an MCP server can give your AI:

  • Tools — actions the AI can take (“send this email”, “search this database”)
  • Resources — data the AI can read (“here’s the content of this file”, “here are today’s orders”)
  • Prompts — pre-built templates for common tasks

This guide focuses on Tools, since they’re the most useful for beginners and cover 90% of real-world use cases.


What You’ll Need

  • A computer with internet access
  • Node.js installed (for the JavaScript path) — download from nodejs.org
  • Python installed (for the Python path) — comes pre-installed on Mac/Linux; download from python.org for Windows
  • A text editor — VS Code is recommended (free, download from code.visualstudio.com)
  • An AI client to test with — Claude Desktop (free) or OpenClaw (if you followed our setup guide)

That’s it. No server, no cloud account, no credit card needed to build your first MCP server.


Understanding the Concept First (Read This Before Coding)

Before you write a single line of code, understand this mental model:

Your AI assistant is like a manager who can think but has no hands. Your MCP server is like an assistant with hands but no brain. The manager tells the assistant what to do; the assistant does it and reports back.

You → AI (the brain) → MCP Server (the hands) → External World
                    ←               ←

When you ask your AI “what’s the weather in Mumbai?”, here’s what actually happens if you’ve built a weather MCP server:

  1. You type the question
  2. The AI recognises it needs the weather tool
  3. The AI calls your MCP server: get_weather(city="Mumbai")
  4. Your server calls a weather API
  5. Your server returns: "Mumbai: 32°C, Humid, Partly Cloudy"
  6. The AI reads this and responds to you naturally

You built step 4 and 5. Everything else is handled automatically.


Option A: Build with Python (Easier for Beginners)

Python is beginner-friendly and has the simplest syntax for MCP servers. Use this path if you’re new to coding or more comfortable with Python.

Step 1: Install the MCP Python Library

Open your terminal (Mac/Linux) or Command Prompt (Windows) and run:

pip install mcp

That’s the only dependency you need for a basic server.

Step 2: Create Your First MCP Server

Create a new folder called my-mcp-server and inside it create a file called server.py.

Paste this complete, working example:

from mcp.server.fastmcp import FastMCP

# Give your server a name
mcp = FastMCP("My First MCP Server")

# Tool 1: A simple calculator
@mcp.tool()
def calculate(expression: str) -> str:
    """Calculate a mathematical expression. Example: '2 + 2' or '100 * 0.18'"""
    try:
        result = eval(expression)
        return f"Result: {result}"
    except Exception as e:
        return f"Error: {str(e)}"

# Tool 2: Word counter
@mcp.tool()
def count_words(text: str) -> str:
    """Count the number of words in a piece of text."""
    words = len(text.split())
    chars = len(text)
    return f"Words: {words}, Characters: {chars}"

# Tool 3: Rupee to Dollar converter
@mcp.tool()
def convert_currency(amount: float, from_currency: str, to_currency: str) -> str:
    """Convert between INR and USD using approximate rates."""
    rates = {
        "INR_TO_USD": 0.012,
        "USD_TO_INR": 84.0,
    }
    key = f"{from_currency.upper()}_TO_{to_currency.upper()}"
    if key in rates:
        converted = amount * rates[key]
        return f"{amount} {from_currency.upper()} = {converted:.2f} {to_currency.upper()}"
    return f"Conversion from {from_currency} to {to_currency} not supported."

# Start the server
if __name__ == "__main__":
    mcp.run()

Step 3: Run and Test It

python server.py

The server starts and waits for connections. Now connect it to your AI client (see the “Connecting to OpenClaw” section below).

What Makes This Work

Look at the @mcp.tool() decorator above each function. This is what tells the MCP library “this function is a tool the AI can call.”

The docstring (the text in triple quotes below the function name) is critically important — the AI reads this to understand when and how to use the tool. Write clear, descriptive docstrings. A tool with a bad description won’t get called even if the code is perfect.


Option B: Build with Node.js / JavaScript

Use this path if you’re comfortable with JavaScript, already have Node.js installed, or want to build something that integrates with web APIs.

Step 1: Set Up Your Project

mkdir my-mcp-server
cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk

Step 2: Create the Server File

Create a file called index.js and paste this:

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

// Create the server
const server = new McpServer({
  name: "My First MCP Server",
  version: "1.0.0"
});

// Tool 1: Calculator
server.registerTool(
  "calculate",
  {
    title: "Calculator",
    description: "Calculate a mathematical expression like '2 + 2' or '100 * 0.18'",
    inputSchema: {
      expression: z.string().describe("The math expression to calculate")
    }
  },
  async ({ expression }) => {
    try {
      const result = Function('"use strict"; return (' + expression + ')')();
      return { content: [{ type: "text", text: `Result: ${result}` }] };
    } catch (e) {
      return { content: [{ type: "text", text: `Error: ${e.message}` }] };
    }
  }
);

// Tool 2: Word counter
server.registerTool(
  "count_words",
  {
    title: "Word Counter",
    description: "Count the number of words and characters in a piece of text",
    inputSchema: {
      text: z.string().describe("The text to count words in")
    }
  },
  async ({ text }) => {
    const words = text.trim().split(/\s+/).length;
    const chars = text.length;
    return {
      content: [{ type: "text", text: `Words: ${words}, Characters: ${chars}` }]
    };
  }
);

// Tool 3: Currency converter
server.registerTool(
  "convert_currency",
  {
    title: "Currency Converter",
    description: "Convert between INR and USD",
    inputSchema: {
      amount: z.number().describe("The amount to convert"),
      from_currency: z.string().describe("Source currency: INR or USD"),
      to_currency: z.string().describe("Target currency: INR or USD")
    }
  },
  async ({ amount, from_currency, to_currency }) => {
    const rates = { INR_TO_USD: 0.012, USD_TO_INR: 84.0 };
    const key = `${from_currency.toUpperCase()}_TO_${to_currency.toUpperCase()}`;
    if (rates[key]) {
      const converted = (amount * rates[key]).toFixed(2);
      return {
        content: [{ type: "text", text: `${amount} ${from_currency} = ${converted} ${to_currency}` }]
      };
    }
    return { content: [{ type: "text", text: "Conversion not supported." }] };
  }
);

// Start the server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP Server running");
}

main().catch(console.error);

Step 3: Update package.json

Open package.json and add "type": "module" so Node.js handles the imports correctly:

{
  "type": "module",
  ...
}

Step 4: Run It

node index.js

Connect Your MCP Server to Claude Desktop

This is the easiest way to test your server. Claude Desktop supports MCP natively.

Find your config file:

  • Mac: ~/Library/Application Support/Claude/claude_desktop_config.json
  • Windows: %APPDATA%\Claude\claude_desktop_config.json

Edit the file (create it if it doesn’t exist) and add your server:

For Python:

{
  "mcpServers": {
    "my-server": {
      "command": "python",
      "args": ["/absolute/path/to/your/server.py"]
    }
  }
}

For Node.js:

{
  "mcpServers": {
    "my-server": {
      "command": "node",
      "args": ["/absolute/path/to/your/index.js"]
    }
  }
}

Important: Always use the absolute path. On Mac/Linux, run pwd inside your project folder to get it. On Windows, run cd in Command Prompt.

Restart Claude Desktop. You’ll see a hammer icon (🔨) in the chat interface — click it to see your tools listed. Now ask Claude: “Can you calculate 15% of 8500 for me?” and it will use your calculator tool.


Connect Your MCP Server to OpenClaw

OpenClaw connects to MCP servers through a tool called mcporter. This is the official bridge between OpenClaw and the MCP ecosystem.

Step 1: Install mcporter

npm install -g mcporter

Step 2: Start Your MCP Server

Make sure your Python or Node.js server is running first.

For Python servers, you need to run it in HTTP mode:

# Change the last line of server.py to:
if __name__ == "__main__":
    mcp.run(transport="streamable-http", port=3000)

Then run:

python server.py

Your server is now accessible at http://localhost:3000/mcp.

For Node.js servers, add an HTTP transport option (see the MCP SDK docs for HTTP setup, or keep using stdio for Claude Desktop testing first).

Step 3: Register with mcporter

npx mcporter config add my-server http://localhost:3000/mcp --scope home

Verify it’s connected:

npx mcporter list

You should see your server listed with its tools.

Step 4: Test from OpenClaw

In your OpenClaw chat (via Telegram, WhatsApp, or the web UI), ask:

“Use the calculate tool to find 18% GST on ₹25,000”

OpenClaw will call your MCP server through mcporter and return the result.

Note: Native MCP support in OpenClaw is actively being developed. The mcporter bridge is the current recommended approach. If you run into issues, the OpenClaw GitHub issues page is the best place to track progress and find workarounds.


Build Something Useful: A Real-World Example

The calculator above was for learning. Here’s a more practical example — an MCP server that fetches the latest USD/INR exchange rate from a free API.

Python version:

from mcp.server.fastmcp import FastMCP
import urllib.request
import json

mcp = FastMCP("Exchange Rate Server")

@mcp.tool()
def get_exchange_rate(from_currency: str, to_currency: str) -> str:
    """Get the current exchange rate between two currencies. 
    Example: from_currency='USD', to_currency='INR'"""
    try:
        url = f"https://open.er-api.com/v6/latest/{from_currency.upper()}"
        with urllib.request.urlopen(url) as response:
            data = json.loads(response.read())
        rate = data["rates"].get(to_currency.upper())
        if rate:
            return f"1 {from_currency.upper()} = {rate} {to_currency.upper()} (live rate)"
        return f"Currency {to_currency} not found."
    except Exception as e:
        return f"Error fetching rate: {str(e)}"

if __name__ == "__main__":
    mcp.run()

Now your AI can answer “What’s the current dollar rate?” with live data — something it couldn’t do before.


Common Beginner Mistakes

1. The AI doesn’t call your tool even when it should

Almost always a bad docstring. The AI decides which tool to use based on your description. Be specific: instead of """Get weather""" write """Get current weather conditions for any city. Returns temperature, humidity, and conditions."""

2. Server starts but Claude Desktop doesn’t show it

Check the path in your config file. It must be the absolute path, not a relative one like ./server.py. Use pwd (Mac/Linux) or cd (Windows) to get the exact path.

3. Python: ModuleNotFoundError: No module named 'mcp'

You installed mcp in a different Python environment. Try:

python3 -m pip install mcp
python3 server.py

4. Node.js: SyntaxError: Cannot use import statement

You forgot to add "type": "module" to package.json. Add it and restart.

5. Never write to stdout in your MCP server

This is critical — MCP uses stdout to communicate with the AI client via JSON-RPC. If your code prints anything to stdout (like print("debug info")), it will corrupt the protocol and break everything. Always write debug info to stderr:

import sys
print("debug info", file=sys.stderr)  # Safe
# or in Node.js:
console.error("debug info");  // Safe — goes to stderr

What to Build Next

Once your first server works, the possibilities are wide:

For productivity:

  • A server that reads your Google Sheets and lets your AI query it
  • A server that sends Telegram notifications when a condition is met
  • A server that checks product prices on Flipkart/Amazon and alerts you to drops

For Indian users specifically:

  • A GST calculator that handles all tax slabs
  • A server that fetches stock prices from NSE/BSE
  • A UPI payment status checker (if your bank has an API)

For developers:

  • A server that queries your database and lets the AI write SQL naturally
  • A server that deploys code or triggers GitHub Actions
  • A server that monitors your server logs and summarises errors

Key Terms Glossary

TermWhat it means
MCPModel Context Protocol — the open standard for AI tool integration
ToolA function your AI can call to do something
ResourceData your AI can read (files, API responses)
TransportHow the AI and server talk — stdio (local) or HTTP (remote)
stdioStandard input/output — the simplest transport, used for local servers
mcporterThe bridge tool that connects MCP servers to OpenClaw
FastMCPA Python library that makes building MCP servers much easier
Claude DesktopAnthropic’s desktop app — the easiest client to test MCP servers with

Related Posts

Start here if you’re new to AI agents:

OpenClaw specifically:

Go deeper with AI tools:


Have a question or ran into an error not covered here? Drop it in the comments — I’ll update the guide. For the latest on MCP and AI tools in India, subscribe to the AIInsider newsletter.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *