Build a Custom MCP Server for Claude Code: The Complete Guide

Learn how to build, test, and deploy a custom MCP server for Claude Code to connect your APIs, databases, and tools. This step-by-step guide covers configuration, security, advanced use cases, and seamless Apidog integration.

Audrey Lopez

Audrey Lopez

30 January 2026

Build a Custom MCP Server for Claude Code: The Complete Guide

Unlocking seamless integration between AI assistants and your internal systems is the next leap in developer productivity. The Model Context Protocol (MCP) makes this possible by providing a standardized, discoverable way for tools like Claude Code to interact with any API, database, or custom service—without hardcoded integrations.

If you're an API developer, backend engineer, or technical lead looking to supercharge your team's workflows, this guide delivers a clear, actionable roadmap to building your own MCP server. You’ll learn to architect, implement, and secure a server that extends Claude Code’s capabilities far beyond its defaults—empowering your team to automate, query, and orchestrate with unprecedented flexibility.

💡 Looking for an API testing platform that generates beautiful API documentation and enables high-productivity, all-in-one teamwork? Apidog replaces Postman at a far more affordable price and delivers everything your developer team needs.

button

What Is MCP and Why Should Developers Care?

The Value of MCP for API Teams

MCP (Model Context Protocol)—created by Anthropic—enables AI assistants like Claude Code to securely and dynamically discover, understand, and use external tools over a unified protocol. Unlike static API integrations, MCP lets you add new tools and endpoints without updating the AI client, making extensibility effortless.

Key benefits for engineering teams:

How MCP Works: Architecture Overview

Typical MCP Workflow

  1. Discovery: Claude Code queries your server for available tools.
  2. Schema Validation: The server returns schemas and definitions.
  3. Tool Selection: Claude Code matches user intent to available tools.
  4. Execution: Tool calls are sent with validated parameters.
  5. Response: The server processes the request and returns structured results.

Apidog will soon support MCP servers—allowing you to feed API docs directly into your AI workflows for instant, always-up-to-date reference.

We’re thrilled to share that MCP support is coming soon to Apidog! 🚀 Apidog MCP Server lets you feed API docs directly to Agentic AI, supercharging your vibe coding experience! Whether you're using Cursor, Cline, or Windsurf - it'll make your dev process faster and smoother.… pic.twitter.com/ew8U38mU0K
— Apidog (@ApidogHQ) March 19, 2025


Prerequisites: Setting Up Your Environment

Before building, ensure your development environment is ready. MCP servers are most commonly built in Python or TypeScript.

For Python:

For TypeScript/JavaScript:

Core Tools:

Environment Setup Steps

1. Install Claude Code CLI Globally

npm install -g @anthropic-ai/claude-code

Global install ensures claude is accessible system-wide and prevents path issues.

2. Verify Installation

claude --version
claude --help

3. Initial Permissions Setup (Critical!)

claude --dangerously-skip-permissions

MCP Server Configuration: Understanding Scopes

Why Scopes Matter

Misconfigured scopes are the #1 cause of “server not found” errors. Scopes control where and when Claude Code can see your server:

Scope Hierarchy

Example: Avoiding Common Mistakes

Wrong (local only):

claude mcp add my-server python3 /path/to/server.py

Right (global user scope):

claude mcp add --scope user my-server python3 /path/to/server.py

Organize for Maintainability

Structure your MCP servers for easy management:

mkdir -p ~/.claude-mcp-servers/apis/
mkdir -p ~/.claude-mcp-servers/utilities/
mkdir -p ~/.claude-mcp-servers/development/

Benefits: Easier updates, security, backup, and team sharing.

Troubleshooting Scope Issues


Step-by-Step: Build Your First MCP Server

1. Project Foundation

Create an isolated project directory:

cd ~/.claude-mcp-servers/
mkdir my-first-server
cd my-first-server
touch server.py requirements.txt .env

2. MCP Server Basics (Python Example)

Below is a minimal MCP server that implements the essential methods:

#!/usr/bin/env python3
import json, sys, os

# Unbuffered output for real-time communication
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)

def send_response(resp): print(json.dumps(resp), flush=True)

def handle_initialize(req_id):
    return {"jsonrpc": "2.0", "id": req_id, "result": {
        "protocolVersion": "2024-11-05",
        "capabilities": {"tools": {}},
        "serverInfo": {"name": "my-custom-server", "version": "1.0.0"}
    }}

def handle_tools_list(req_id):
    return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": [{
        "name": "hello_world",
        "description": "A simple demonstration tool",
        "inputSchema": {"type": "object", "properties": {"name": {
            "type": "string", "description": "Name to greet"}}, "required": ["name"]}
    }]}}

def handle_tool_call(req_id, params):
    tool, args = params.get("name"), params.get("arguments", {})
    if tool == "hello_world":
        name = args.get("name", "World")
        result = f"Hello, {name}! Your MCP server is working perfectly."
    else:
        return {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Unknown tool: {tool}"}}
    return {"jsonrpc": "2.0", "id": req_id, "result": {"content": [{"type": "text", "text": result}]}}

def main():
    while True:
        try:
            line = sys.stdin.readline()
            if not line: break
            req = json.loads(line.strip())
            m, req_id, params = req.get("method"), req.get("id"), req.get("params", {})
            if m == "initialize": resp = handle_initialize(req_id)
            elif m == "tools/list": resp = handle_tools_list(req_id)
            elif m == "tools/call": resp = handle_tool_call(req_id, params)
            else: resp = {"jsonrpc": "2.0", "id": req_id, "error": {"code": -32601, "message": f"Method not found: {m}"}}
            send_response(resp)
        except Exception: continue

if __name__ == "__main__": main()

Key Points:

3. Make the Server Executable

chmod +x server.py

4. Test Protocol Compliance

echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' | python3 server.py

You should see a valid JSON response with protocol version and capabilities.

5. Register with Claude Code

claude mcp add --scope user my-first-server python3 ~/.claude-mcp-servers/my-first-server/server.py
claude mcp list
claude mcp get my-first-server

Real-World Example: Integrate a Weather API

Let’s evolve your MCP server into a production-useful tool by connecting to the OpenWeatherMap API.

Server highlights:

Sample Implementation

import json, sys, os, requests

WEATHER_API_KEY = os.environ.get("OPENWEATHER_API_KEY", "your-api-key-here")

def get_weather(city):
    url = "http://api.openweathermap.org/data/2.5/weather"
    params = {"q": city, "appid": WEATHER_API_KEY, "units": "metric"}
    try:
        r = requests.get(url, params=params, timeout=10)
        data = r.json()
        if r.status_code == 200:
            return f"Weather in {city}: {data['main']['temp']}°C, {data['weather'][0]['description'].title()}, Humidity: {data['main']['humidity']}%"
        return f"Error fetching weather: {data.get('message', 'Unknown error')}"
    except requests.RequestException as e:
        return f"Network error: {str(e)}"

Tool schema and error handling are updated to match production needs.

Security: Store your API key in .env and never commit secrets to version control.


Testing and Debugging Your MCP Server

Manual Testing

Automated Test Example

import json, subprocess, sys
def test_mcp_method(method, params=None):
    req = {"jsonrpc": "2.0", "id": 1, "method": method, "params": params or {}}
    result = subprocess.run([sys.executable, "server.py"], input=json.dumps(req), capture_output=True, text=True, timeout=10)
    return json.loads(result.stdout.strip())

Integration Testing


Best Practices for Production MCP Servers

Security

Error Handling

Monitoring & Logging

Scalability


Advanced Use Cases and Patterns

Integrate with Databases, CI/CD, Analytics

Performance Optimization


Next Steps: Grow Your MCP Ecosystem

Mastering MCP unlocks new automation and integration possibilities for your team:

💡 Want a powerful API testing suite that delivers beautiful documentation, boosts team productivity, and replaces Postman at a better price? Try Apidog for all-in-one API design, testing, and collaboration.

button

Explore more

What is Qwen 3.5? How to Access the Qwen 3.5 API in 2026

What is Qwen 3.5? How to Access the Qwen 3.5 API in 2026

What is Qwen 3.5? Alibaba's 397B MoE native multimodal AI model released February 2026. Learn its Gated Delta Networks architecture, top benchmarks like 87.8 MMLU-Pro, and precise steps to access the Qwen 3.5 API via Alibaba Cloud.

16 February 2026

How to Use Qwen 3.5 API ?

How to Use Qwen 3.5 API ?

Master the Qwen 3.5 API with this technical guide. Learn to authenticate through Alibaba Cloud, send chat completions, enable multimodal reasoning, tool calling, and 1M context windows. Includes Python examples, advanced parameters, and a free Apidog download to streamline testing.

16 February 2026

How to Use Seedance 2.0 Right Now (No Waiting)

How to Use Seedance 2.0 Right Now (No Waiting)

This guide provides a clear, step-by-step approach to using Seedance 2.0 today. It draws from verified methods shared in the AI community, official ByteDance platforms, and real-world testing.

15 February 2026

Practice API Design-first in Apidog

Discover an easier way to build and use APIs