Building Your First MCP Server: Complete Step-by-Step Tutorial
Learn how to build a Model Context Protocol (MCP) server from scratch. Connect Claude to external tools and data sources in under 30 minutes.
Building Your First MCP Server: Complete Step-by-Step Tutorial
The Model Context Protocol (MCP) is transforming how AI assistants like Claude interact with external tools and data sources. Instead of copying and pasting information or manually switching between applications, MCP enables Claude to directly access your tools, databases, and APIs.
In this comprehensive tutorial, you will learn how to build your first MCP server from scratch, connect it to Claude, and unlock powerful automation capabilities.
What is an MCP Server and Why Build One?
An MCP server acts as a bridge between Claude and your external resources. Think of it as a translator that allows Claude to:
- Query databases directly without manual data extraction
- Execute API calls to third-party services
- Access file systems for reading and writing documents
- Trigger automation workflows based on natural language commands
- Integrate with business tools like CRM, ERP, and project management systems
Benefits of Building Your Own MCP Server
Custom Integration: Connect Claude to proprietary systems and internal tools unique to your organization.
Data Security: Keep sensitive data within your infrastructure while still leveraging AI capabilities.
Workflow Automation: Create powerful automation workflows tailored to your specific business processes.
Cost Efficiency: Reduce manual data entry and context switching between applications.
Prerequisites: What You Need
Before we begin, make sure you have:
Technical Requirements
- Node.js 18+ installed on your machine
- TypeScript knowledge (basic familiarity)
- Claude Desktop or Claude Code installed
- Code editor (VS Code recommended)
- Terminal access (Command Prompt, PowerShell, or Bash)
Knowledge Prerequisites
- Basic JavaScript/TypeScript syntax
- Understanding of APIs and HTTP requests
- Familiarity with JSON data structures
- Command line basics
Time Required: 30-45 minutes
Step 1: Set Up Your Development Environment
First, create a new directory for your MCP server project:
mkdir my-first-mcp-server
cd my-first-mcp-server
npm init -y
Install the required dependencies:
npm install @modelcontextprotocol/sdk
npm install --save-dev typescript @types/node
Initialize TypeScript Configuration
Create a tsconfig.json file:
npx tsc --init
Update the tsconfig.json with these recommended settings:
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true
}
}
Step 2: Create Your MCP Server File
Create a src directory and your main server file:
mkdir src
touch src/server.ts
Open src/server.ts and add the basic server structure:
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js";
// Create the MCP server instance
const server = new Server(
{
name: "my-first-mcp-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
console.log("MCP Server starting...");
Step 3: Define Your First Tool
Let us create a simple calculator tool that Claude can use. Add this code to define a "calculate" tool:
// Define available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "calculate",
description: "Performs basic arithmetic calculations (add, subtract, multiply, divide)",
inputSchema: {
type: "object",
properties: {
operation: {
type: "string",
enum: ["add", "subtract", "multiply", "divide"],
description: "The mathematical operation to perform",
},
num1: {
type: "number",
description: "The first number",
},
num2: {
type: "number",
description: "The second number",
},
},
required: ["operation", "num1", "num2"],
},
},
],
};
});
Step 4: Implement Tool Logic
Now implement the actual calculation logic:
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "calculate") {
const { operation, num1, num2 } = request.params.arguments;
let result: number;
switch (operation) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 === 0) {
throw new Error("Cannot divide by zero");
}
result = num1 / num2;
break;
default:
throw new Error(`Unknown operation: ${operation}`);
}
return {
content: [
{
type: "text",
text: `Result: ${result}`,
},
],
};
}
throw new Error(`Unknown tool: ${request.params.name}`);
});
Step 5: Start the Server Transport
Complete your server file by adding the transport layer:
// Start the server
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.log("MCP Server running on stdio");
}
main().catch((error) => {
console.error("Server error:", error);
process.exit(1);
});
Step 6: Build and Test Your Server
Add build scripts to your package.json:
{
"scripts": {
"build": "tsc",
"start": "node dist/server.js",
"dev": "tsc && node dist/server.js"
}
}
Build your server:
npm run build
Step 7: Connect to Claude
Now connect your MCP server to Claude Desktop or Claude Code.
For Claude Desktop
Edit your Claude Desktop configuration file:
Windows: %APPDATA%\Claude\claude_desktop_config.json
Mac: ~/Library/Application Support/Claude/claude_desktop_config.json
Add your server configuration:
{
"mcpServers": {
"my-first-mcp-server": {
"command": "node",
"args": ["/absolute/path/to/my-first-mcp-server/dist/server.js"]
}
}
}
For Claude Code
Add to your .claude/mcp_config.json:
{
"mcpServers": {
"my-first-mcp-server": {
"command": "node",
"args": ["./my-first-mcp-server/dist/server.js"]
}
}
}
Restart Claude to load your new MCP server.
Testing Your MCP Server
Once connected, test your calculator tool by asking Claude:
"Can you calculate 156 multiplied by 42 using the calculate tool?"
Claude should respond with the result: 6,552
Try different operations:
- "Add 250 and 780"
- "Divide 1000 by 25"
- "Subtract 45 from 100"
Debugging Common Issues
Issue: Server Won't Start
Solution: Check for TypeScript errors:
npm run build
Look for compilation errors and fix any type issues.
Issue: Claude Can't Find the Server
Solution: Verify the path in your configuration file is absolute and correct. Use forward slashes even on Windows.
Issue: Tool Not Appearing in Claude
Solution:
- Restart Claude completely
- Check server logs for errors
- Verify the server is listed in Claude's MCP servers panel
Issue: "Cannot divide by zero" Error
Solution: This is expected behavior. Your error handling is working correctly!
Next Steps: Expanding Your MCP Server
Now that you have a working MCP server, consider adding:
Database Integration
Connect to PostgreSQL, MySQL, or MongoDB to allow Claude to query your data.
File System Access
Enable Claude to read and write files on your system.
API Integration
Connect to external APIs like Slack, GitHub, or your internal services.
Best Practices for MCP Server Development
Security Considerations
Validate all inputs: Always validate and sanitize user inputs before processing.
Use environment variables: Store sensitive data like API keys in environment variables, never hardcode them.
Implement rate limiting: Prevent abuse by limiting the frequency of tool calls.
Log all operations: Maintain audit logs of tool usage for security and debugging.
Performance Optimization
Cache frequently accessed data: Reduce API calls and database queries by caching results.
Use async/await properly: Ensure all asynchronous operations are properly handled.
Implement timeouts: Set reasonable timeouts for long-running operations.
Handle errors gracefully: Provide clear error messages that help users understand what went wrong.
Real-World Use Cases
Customer Support Automation
Build an MCP server that connects Claude to your customer support database, enabling instant access to customer history, ticket status, and product information.
Data Analysis Workflows
Create tools that allow Claude to query your analytics database, generate reports, and visualize data trends without manual intervention.
DevOps Automation
Connect Claude to your deployment pipelines, allowing it to check build status, deploy applications, and monitor system health.
Content Management
Enable Claude to create, update, and publish content directly to your CMS, streamlining content workflows.
Conclusion
Congratulations! You have built your first MCP server and connected Claude to external tools. This opens up endless possibilities for automation and integration.
The calculator example is simple, but the same principles apply to building sophisticated tools that connect Claude to databases, APIs, file systems, and business applications.
Next Steps:
- Explore the MCP Builder skill for automated MCP server generation
- Read Understanding the Model Context Protocol for deeper technical insights
- Join the ClaudeSkillsHQ community to share your MCP servers and learn from others
Start building, experiment with different integrations, and transform how you interact with Claude!