Ever felt like Claude Code is powerful, but you’re leaving capabilities on the table because you haven’t figured out how to build your own tools? You’re not alone. The Model Context Protocol (MCP) ecosystem looks intimidating at first—servers, transport, tool discovery, JSON-RPC messages. But here’s the thing: building your first MCP server is genuinely straightforward once you understand the core concepts. In this article, we’re going to walk through the entire process from zero to a working server that Claude Code can discover and use.
By the end, you’ll have a running MCP server with a custom tool that Claude Code can call. No magic. No hidden complexity. Just honest, practical steps.
What Is an MCP Server (and Why Should You Care)?
Let’s start with the basics. The Model Context Protocol is a standardized way for Claude to talk to external tools and data sources. An MCP server is just a program that:
- Listens for requests from Claude Code
- Performs some action (call an API, query a database, run a script)
- Sends results back to Claude Code
Think of it as building a bridge between Claude’s reasoning and your specific workflows. Instead of pasting data or context into the chat manually, your MCP server makes that happen automatically.
Why does this matter? Because the alternative is brittle. Copying API responses into conversations. Asking Claude to parse unstructured output. Maintaining context manually. An MCP server eliminates all that friction. Claude Code gets what it needs, when it needs it, formatted the way it expects.
The real power becomes apparent when you think about the compound effect. Every time you’d normally say “Hold on, let me check the API” or “Let me look up that database value,” your MCP server can do it in the background. Claude Code continues reasoning without interruption. You stay in flow. The quality of Claude’s responses improves because it has accurate, up-to-date information at decision time.
Prerequisites: What You’ll Need
Before we dive in, make sure you have:
- Node.js 18+ (we’re using TypeScript, which needs Node)
- Claude Code installed and working (version 0.8.0 or later recommended)
- A text editor (VS Code recommended, but any editor works)
- Basic TypeScript familiarity (we’ll explain the syntax, but if you’ve written JavaScript, you’ll follow along)
- A terminal (Bash, PowerShell, or your shell of choice)
- npm or yarn (comes with Node.js)
Not familiar with TypeScript? Don’t panic. We’ll keep it simple, and TypeScript’s type system actually makes MCP servers easier to reason about, not harder. It catches type mismatches before they become runtime errors, which is invaluable when debugging server integration issues.
If you don’t have Node.js installed, grab it from nodejs.org. The LTS version is fine. Once installed, verify it with:
node --version
npm --version
Step 1: Project Initialization and Structure
Let’s create a new project directory and set up the scaffolding.
mkdir my-first-mcp-server
cd my-first-mcp-server
npm init -y
npm install --save-dev typescript @types/node ts-node
npm install @modelcontextprotocol/sdk
After running these commands, your node_modules directory has everything needed. The @modelcontextprotocol/sdk package gives us the types and utilities to build MCP servers.
Now create a tsconfig.json to configure TypeScript:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
This tells TypeScript to compile our source files from src/ into dist/. Create those directories now:
mkdir src dist
Your folder structure should look like this:
my-first-mcp-server/
├── src/
├── dist/
├── node_modules/
├── package.json
├── tsconfig.json
└── package-lock.json
Perfect. Now we have a blank canvas.
Step 2: Building Your First MCP Server
Let’s create the actual server. Create a file at src/index.ts:
Server,
StdioServerTransport,
} from "@modelcontextprotocol/sdk/server/index.js";
ListToolsRequestSchema,
CallToolRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
// Initialize the server with basic metadata
const server = new Server(
{
name: "hello-world-server",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
},
);
// Handle tool listing
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "greet",
description: "Greets a person by name and returns a friendly message",
inputSchema: {
type: "object",
properties: {
name: {
type: "string",
description: "The name of the person to greet",
},
},
required: ["name"],
},
},
],
};
});
// Handle tool calls
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "greet") {
const name = request.params.arguments?.name;
if (typeof name !== "string") {
return {
content: [
{
type: "text",
text: "Error: name parameter must be a string",
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: `Hello, ${name}! Welcome to your first MCP server. You're doing great!`,
},
],
};
}
return {
content: [
{
type: "text",
text: `Unknown tool: ${request.params.name}`,
},
],
isError: true,
};
});
// Start the server on stdio transport
const transport = new StdioServerTransport();
server.connect(transport);
console.error("MCP Server running on stdio transport");
Let’s break down what’s happening here:
Initialization: We create a Server instance with metadata (name and version). The capabilities object tells Claude Code what this server can do—in this case, we’re declaring that we support tools.
Tool Listing: When Claude Code asks “what tools do you have?”, the ListToolsRequestSchema handler responds with a list of available tools. Each tool has a name, description, and input schema (what arguments it accepts). The input schema uses JSON Schema, which is standard for describing data structures.
Tool Calling: When Claude Code wants to actually use a tool, it sends a request through the CallToolRequestSchema handler. We check the tool name, validate the arguments, and return a result or error.
Transport: We use StdioServerTransport, which means the server communicates with Claude Code through standard input/output. No network sockets, no complicated setup—just piped data.
Now compile the TypeScript:
npx tsc
This generates JavaScript in the dist/ folder. You should see:
dist/
├── index.js
├── index.d.ts
└── index.js.map
If you get an error about TypeScript not being installed globally, that’s fine. The npx tsc command will use the version you installed locally.
Step 3: Testing with claude mcp serve
Before registering the server with Claude Code, let’s test it directly. Claude Code includes a command-line utility for running MCP servers:
claude mcp serve node dist/index.js
Expected output:
MCP Server running on stdio transport
[Server listening on stdio]
The server is now running. It won’t do anything visible yet because it’s waiting for Claude Code to connect. Leave this running in a terminal and open another terminal window.
In a new terminal (in the same project directory), test the server with Claude’s tool discovery:
echo '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' | node dist/index.js
Expected output:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"tools": [
{
"name": "greet",
"description": "Greets a person by name and returns a friendly message",
"inputSchema": {
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "The name of the person to greet"
}
},
"required": ["name"]
}
}
]
}
}
Fantastic! The server listed its tools. Now let’s actually call one:
echo '{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "greet", "arguments": {"name": "Alex"}}}' | node dist/index.js
Expected output:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"content": [
{
"type": "text",
"text": "Hello, Alex! Welcome to your first MCP server. You're doing great!"
}
]
}
}
There it is. Your MCP server is working. It accepted a tool call, processed the arguments, and returned a formatted response. This is the core loop of every MCP interaction. You’ve just manually replicated what Claude Code will do automatically once the server is registered.
Step 4: Registering the Server with Claude Code
Now comes the integration. Claude Code reads from a configuration file (typically in your user directory) that tells it which MCP servers to connect to. On macOS/Linux, this is usually ~/.claude/servers.json. On Windows, it’s typically in your AppData folder.
Let’s create or edit the configuration file. First, find where Claude Code stores its configuration:
macOS/Linux:
cat ~/.claude/servers.json
Windows (PowerShell):
type $env:APPDATA\Claude\servers.json
If the file doesn’t exist, that’s fine. We’ll create it. Create a servers.json file with this content:
{
"mcpServers": {
"hello-world": {
"command": "node",
"args": ["/full/path/to/my-first-mcp-server/dist/index.js"],
"env": {}
}
}
}
Important: Replace /full/path/to/my-first-mcp-server with the absolute path to your project. Get the full path with:
macOS/Linux:
pwd
Windows (PowerShell):
(Get-Location).Path
On Windows, the path might look like C:\Users\YourName\my-first-mcp-server\dist\index.js. Backslashes in JSON need to be escaped, so it would be C:\\Users\\YourName\\my-first-mcp-server\\dist\\index.js in the JSON file. Actually, forward slashes work too and are cleaner: C:/Users/YourName/my-first-mcp-server/dist/index.js.
Save the configuration file in the appropriate location for your OS. Now restart Claude Code. It will automatically discover and connect to your MCP server on startup.
To verify, open Claude Code and run:
/mcp
This command lists all connected MCP servers. You should see your hello-world server listed. If it’s not there, check that the path in servers.json is correct and absolute.
Step 5: Using the Server from Claude Code
Now for the magic moment. In Claude Code, try:
Call the greet tool with name="Jordan"
Claude Code will:
- Discover that the
greettool exists (via thetools/listhandler) - Call the tool with your arguments (via the
tools/callhandler) - Parse the response
- Show you the result
You should see:
Hello, Jordan! Welcome to your first MCP server. You're doing great!
Congratulations. Your MCP server is live and Claude Code is using it.
Common Gotchas and How to Avoid Them
Before you go building complex servers, let’s talk about the potholes:
Absolute Paths in Configuration: If you use a relative path in servers.json, Claude Code won’t find it. Always use absolute paths. This trips up nearly everyone on their first try. On Windows, also watch for backslash escaping.
Stdio vs. Network Transport: We’re using stdio because it’s the simplest and most reliable for local development. Later, you might use HTTP or WebSocket transport for remote servers. Stick with stdio until you have a specific reason not to.
JSON-RPC Escaping: When testing with echo, you need to be careful with quotes. If your arguments contain special characters, they might get lost. Use a proper JSON library in your integration tests. On Windows, PowerShell’s quoting rules are different from bash—test your command carefully.
Error Handling: Notice how we check if name is a string before using it? Always validate inputs from Claude Code. Assume nothing about types or structure. A single validation mistake can crash your server, and then Claude Code can’t call any of your tools.
Logging to Stderr: Important: log debugging information to stderr, not stdout. The stdout channel is reserved for MCP protocol messages. If you pollute stdout, Claude Code can’t parse the responses. Use console.error() for logs.
Forgetting to Recompile: If you edit your TypeScript files, you need to run npx tsc again. Your running server won’t automatically pick up changes. Stop it, recompile, and restart.
Path Issues on Windows: Windows paths in JSON need careful handling. Either escape backslashes (C:\\path) or use forward slashes (C:/path). Forward slashes are less error-prone.
Understanding the JSON-RPC Protocol
Now that you’ve tested your server, let’s dig into what’s actually happening. MCP uses JSON-RPC 2.0, a lightweight protocol for remote procedure calls. When you ran that echo command with the JSON payload, you were speaking the language that Claude Code uses under the hood.
Every MCP message has this structure:
{
"jsonrpc": "2.0",
"id": "<unique identifier>",
"method": "<method name>",
"params": {
/* method-specific parameters */
}
}
The id is crucial—it matches requests to responses. When your server sends a response, it includes the same id so Claude Code knows which request it’s answering. The method tells the server what to do. For tools, we’ve seen two: tools/list (what tools do you have?) and tools/call (please execute this tool).
Why does this matter? Because understanding the protocol means understanding what could go wrong and how to debug it. If Claude Code sends a request with id: 42, and your server responds with id: 43, things will break. If your server doesn’t respond within a timeout (usually a few seconds), Claude Code will give up and report an error.
This is also why logging to stdout is so dangerous. Every character you print to stdout is part of the protocol stream. A stray console.log() can corrupt the entire message. That’s why we use console.error() for debugging—stderr is separate and doesn’t interfere.
Expanding Your Server with More Tools
Once you have the pattern down, adding more tools is straightforward. In the ListToolsRequestSchema handler, add another object to the tools array:
{
name: "add",
description: "Adds two numbers together",
inputSchema: {
type: "object",
properties: {
a: { type: "number", description: "First number" },
b: { type: "number", description: "Second number" },
},
required: ["a", "b"],
},
}
Then in the CallToolRequestSchema handler, add a case for it:
if (request.params.name === "add") {
const a = request.params.arguments?.a;
const b = request.params.arguments?.b;
if (typeof a !== "number" || typeof b !== "number") {
return {
content: [
{ type: "text", text: "Error: both arguments must be numbers" },
],
isError: true,
};
}
return {
content: [{ type: "text", text: `${a} + ${b} = ${a + b}` }],
};
}
Compile and restart. That’s it. Now Claude Code knows about both tools.
You can extend this pattern indefinitely. Want a tool that fetches weather data? Add it to the tools array and handle it in the CallToolRequestSchema handler. Want a tool that queries a database? Same approach. The pattern scales cleanly because each tool is just another conditional branch.
Real-World Example: Building a File System Tool
Let’s build something slightly more realistic. Imagine you want Claude Code to read files from your computer. Here’s a read-file tool:
// Add to tools array:
{
name: "read-file",
description: "Reads the contents of a file on the system",
inputSchema: {
type: "object",
properties: {
filepath: {
type: "string",
description: "Absolute path to the file to read",
},
},
required: ["filepath"],
},
}
// Add to CallToolRequestSchema handler:
if (request.params.name === "read-file") {
const filepath = request.params.arguments?.filepath;
if (typeof filepath !== "string") {
return {
content: [{ type: "text", text: "Error: filepath must be a string" }],
isError: true,
};
}
try {
// Prevent directory traversal attacks
const absolutePath = path.resolve(filepath);
const content = fs.readFileSync(absolutePath, "utf-8");
return {
content: [{ type: "text", text: content }],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error reading file: ${error instanceof Error ? error.message : "Unknown error"}`,
},
],
isError: true,
};
}
}
Notice the security consideration: we use path.resolve() to prevent Claude Code from reading files outside the intended directory. Always sanitize inputs, especially when accessing the filesystem or databases.
Now Claude Code can ask you “read me the README.md file” and your server will fetch it automatically. No more copy-pasting.
Input Validation and Error Handling
One thing we’ve glossed over a bit: how serious should you be about validation? The answer is very. Claude Code can send malformed requests, intentionally or by accident. A single unhandled error can crash your entire server.
Here’s a more robust approach to input validation:
function validateToolInput(
toolName: string,
requiredFields: string[],
arguments: unknown,
): { valid: boolean; error?: string } {
if (typeof arguments !== "object" || arguments === null) {
return { valid: false, error: "Arguments must be an object" };
}
const args = arguments as Record<string, unknown>;
for (const field of requiredFields) {
if (!(field in args)) {
return {
valid: false,
error: `Missing required field: ${field}`,
};
}
}
return { valid: true };
}
// Usage in CallToolRequestSchema handler:
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const { name, arguments: args } = request.params;
if (name === "greet") {
const validation = validateToolInput(name, ["name"], args);
if (!validation.valid) {
return {
content: [
{ type: "text", text: validation.error || "Validation failed" },
],
isError: true,
};
}
// ... rest of logic
}
} catch (error) {
return {
content: [
{
type: "text",
text: `Internal error: ${error instanceof Error ? error.message : "Unknown error"}`,
},
],
isError: true,
};
}
});
This approach centralizes validation and ensures you always handle errors gracefully. Never let an exception escape your handlers uncaught—Claude Code expects a structured response, not a stack trace.
Environment Variables and Configuration
Real servers need configuration. API keys, database URLs, file paths. You pass these through environment variables that Claude Code sets when starting your server.
In your servers.json, you can specify environment variables:
{
"mcpServers": {
"api-server": {
"command": "node",
"args": ["/path/to/server/dist/index.js"],
"env": {
"API_KEY": "your-secret-key-here",
"DATABASE_URL": "postgresql://localhost/mydb",
"DEBUG": "false"
}
}
}
}
Then in your server code, read them:
const apiKey = process.env.API_KEY;
const databaseUrl = process.env.DATABASE_URL;
const debug = process.env.DEBUG === "true";
if (!apiKey) {
console.error("ERROR: API_KEY environment variable is required");
process.exit(1);
}
Always validate that required environment variables are present on startup. Better to fail fast during initialization than to crash mid-call.
Handling Async Operations
Most real tools do something asynchronous—fetch from an API, query a database, write files. The MCP SDK handles this seamlessly because all handlers are async:
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "fetch-weather") {
const city = request.params.arguments?.city;
try {
// This will wait for the fetch to complete
const response = await fetch(
`https://api.weather.example.com/current?city=${encodeURIComponent(city)}`,
);
const data = await response.json();
return {
content: [
{
type: "text",
text: JSON.stringify(data, null, 2),
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Failed to fetch weather: ${error instanceof Error ? error.message : "Unknown error"}`,
},
],
isError: true,
};
}
}
return {
content: [{ type: "text", text: `Unknown tool: ${request.params.name}` }],
isError: true,
};
});
Claude Code will wait for your promise to resolve. If it takes too long (usually 30 seconds or more), Claude Code might timeout and report an error. For long-running operations, consider breaking them into smaller, faster tool calls or caching results.
Testing Your Server Locally
Before you register your server with Claude Code, it’s smart to write some basic tests. Create a src/server.test.ts file:
// Mock transport for testing
class MockTransport {
async read(): Promise<unknown> {
return null;
}
async write(message: unknown): Promise<void> {}
async close(): Promise<void> {}
}
async function testServer() {
// Instantiate your server (from index.ts)
// Call handlers manually with test data
// Verify responses
console.log("✓ All tests passed");
}
testServer().catch(console.error);
Run this with npx ts-node src/server.test.ts. Manual testing with raw JSON-RPC (like we did earlier) is equally valid, but automated tests ensure you catch regressions.
Debugging Server Issues
When things don’t work, here’s a systematic approach:
Is the server starting? Run claude mcp serve node dist/index.js and watch for errors. If TypeScript compilation failed, you’ll see errors here.
Is Claude Code connecting? Check your Claude Code logs. On macOS, these live in ~/Library/Logs/Claude. On Windows, check %APPDATA%\Claude\logs. Look for connection messages or errors.
Is the tool being discovered? Use the raw JSON-RPC test we did earlier. If tools/list doesn’t return your tool, the server isn’t advertising it properly.
Is the tool being called correctly? Again, use the JSON-RPC test to simulate a tool call. This isolates the server logic from Claude Code’s integration.
Are arguments being passed? Log the request.params object and check what Claude Code is actually sending. Sometimes the argument names don’t match what you expected.
If you get stuck, add console.error() statements liberally throughout your code, then run the raw JSON-RPC tests. You’ll see your debug output in the terminal.
Production Considerations
Once your MCP server works locally, you might want to deploy it for real use. Here are some production-level considerations:
Process Management: Don’t rely on running Node directly. Use a process manager like pm2 or systemd to keep your server alive if it crashes. Claude Code will try to restart it, but having your own supervision is safer.
npm install -g pm2
pm2 start "node dist/index.js" --name mcp-server
pm2 startup
pm2 save
Logging: Set up proper logging with timestamps and levels. The simple console.error() approach works for development, but production deserves structured logs that you can search and filter.
function log(level: string, message: string, data?: unknown) {
const timestamp = new Date().toISOString();
const logEntry = { timestamp, level, message, data };
console.error(JSON.stringify(logEntry));
}
log("INFO", "Tool called", { toolName: "greet", arguments: { name: "Alex" } });
Health Checks: If your server depends on external resources (APIs, databases), verify they’re available on startup. Fail fast if dependencies aren’t met.
async function checkDependencies() {
try {
const response = await fetch(process.env.API_URL || "");
if (!response.ok) throw new Error("API returned error");
console.error("✓ API dependency verified");
} catch (error) {
console.error("✗ API dependency failed:", error);
process.exit(1);
}
}
// Call before server.connect()
await checkDependencies();
Rate Limiting: If your tools call external APIs, consider adding rate limiting to avoid hitting API quotas. Implement a simple token bucket or use a library like bottleneck.
Timeouts: Always set timeouts on external requests. Hanging requests block Claude Code.
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
try {
const response = await fetch(url, { signal: controller.signal });
// ...
} finally {
clearTimeout(timeout);
}
Real-World Troubleshooting: When Things Go Wrong
Even with perfect code, you’ll run into integration issues. Let’s walk through the most common ones and how to fix them.
Claude Code doesn’t see my server at all. This is usually a path issue. Verify the path in servers.json is absolute (not relative). On Windows, make sure backslashes are escaped. Try printing the path to your terminal and copying it directly into the config. Also verify that the Node process can execute the file: run node /full/path/to/dist/index.js manually in your terminal. If Node can’t run it, Claude Code can’t either.
The server starts but Claude Code says “connection refused.” The server is running but Claude Code can’t reach it. This usually means the stdio transport isn’t working. Verify that your code calls server.connect(transport) and that you’re not accidentally suppressing the connection. Also check that you’re not printing to stdout except for MCP protocol messages—if you console.log() anything before server.connect(), it might corrupt the protocol stream.
Claude Code connects but tools don’t show up. The server is running but not advertising tools. Check your ListToolsRequestSchema handler. Is it returning a properly formatted response? Try the manual JSON-RPC test: pipe a tools/list request to your server and check the output. If the output is malformed or empty, your handler isn’t working correctly.
Tool calls fail with “invalid input.” The validation logic is rejecting Claude Code’s input. Check that your required fields exactly match the schema you advertised. If you said inputSchema.required: ["name"], Claude Code will send name. If it’s not showing up, maybe Claude Code is sending username or fullName instead. Log the request.params and see what’s actually being sent.
Tool calls timeout. Your tool is taking too long. If it’s an async operation (API call, database query), check that you’re not missing an await. If the operation legitimately takes time, consider caching results or breaking the tool into smaller operations. Most timeout limits are 30 seconds—if you need longer, restructure the workflow.
The server crashes with “out of memory.” If you’re handling large files or datasets, you might be loading them all into memory at once. For file operations, use streams instead of readFileSync. For large data, paginate or chunk the results.
Building Tools That Scale: Performance and Reliability
Once your basic server works, think about making it production-ready. Here’s what real systems care about.
Caching results. If your tool makes external API calls, cache the results. A simple in-memory cache might look like:
const cache = new Map<string, { result: unknown; timestamp: number }>();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
function getCachedResult(key: string): unknown | null {
const cached = cache.get(key);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return cached.result;
}
cache.delete(key);
return null;
}
function setCachedResult(key: string, result: unknown): void {
cache.set(key, { result, timestamp: Date.now() });
}
This is extremely simple but surprisingly effective. If Claude Code calls the same tool twice in five minutes, the second call returns instantly from cache.
Connection pooling. If your tool connects to a database, don’t create a new connection for each request. Use a connection pool. Most database clients have this built-in—check your driver’s documentation.
Graceful degradation. What happens if an external service is down? Instead of failing completely, can you return cached results? Partial results? A helpful error message? Think about the user experience.
Monitoring and metrics. In production, you want to know how often each tool is called, how long it takes, and how often it fails. Log these metrics:
interface ToolMetrics {
name: string;
callCount: number;
totalDuration: number;
errorCount: number;
averageDuration: number;
}
const metrics = new Map<string, ToolMetrics>();
function recordToolCall(name: string, duration: number, error: boolean): void {
let m = metrics.get(name) || {
name,
callCount: 0,
totalDuration: 0,
errorCount: 0,
averageDuration: 0,
};
m.callCount++;
m.totalDuration += duration;
if (error) m.errorCount++;
m.averageDuration = m.totalDuration / m.callCount;
metrics.set(name, m);
console.error(
JSON.stringify({
event: "tool_call",
metrics: Object.fromEntries(metrics),
}),
);
}
Now you can see which tools are actually being used and whether they’re performant.
Building Tools That Interact: Complex Tool Orchestration
As your server grows, you might create tools that call other tools. For example, you might have a “deploy-app” tool that internally calls your “run-tests” tool to verify everything works before deploying.
In MCP, you can implement this by having one tool handler call another internally:
async function deployApp(appName: string): Promise<string> {
// First, run tests internally
const testResults = await runTests(appName);
if (!testResults.success) {
return `Deployment cancelled: tests failed. ${testResults.output}`;
}
// Tests passed, proceed with deployment
// ... deployment logic ...
return "Deployment successful";
}
async function runTests(
appName: string,
): Promise<{ success: boolean; output: string }> {
// Test logic here
return { success: true, output: "All tests passed" };
}
This is perfectly valid. Claude Code only knows about the “deploy-app” tool, but internally you’re organizing complex logic. The key is that each tool should still have a clear, documented purpose.
Beyond Tools: Resources and Prompts
MCP supports more than just tools. Servers can also advertise resources (files, data sources) and prompts (predefined templates). We’ve focused on tools here because they’re the most immediately useful, but once you’re comfortable with the basics, explore the full MCP spec.
Resources let Claude Code access structured data without polling. For example, you might expose a “project-files” resource that lists all files in a project, and Claude Code can query it when it needs to understand the codebase structure. Prompts let you bundle Claude with predefined instructions. For example, you might have a “code-review” prompt that includes all your team’s code review guidelines, and Claude Code can use it automatically when reviewing code.
Both follow the same request-response pattern as tools, and adding them to your server follows the exact same approach we’ve outlined here.
Security Considerations for MCP Servers
Before you deploy your server to production (especially if it touches sensitive data), think carefully about security. Your MCP server is a potential attack surface, and mistakes can have real consequences.
Input validation is mandatory. Every single input from Claude Code should be validated. Never trust the type, length, or format of arguments. We showed examples of this earlier, but it bears repeating because it’s the number one source of server crashes and security issues. Treat all external input as potentially hostile. Check that arguments are the right type, that strings aren’t absurdly long, and that they don’t contain injection payloads.
Prevent directory traversal. If your tools access the filesystem, sanitize paths. Use path.resolve() to get the canonical absolute path, then verify it’s within an allowed directory. Don’t let Claude Code escape your intended sandbox.
Don’t log sensitive data. If your tools work with API keys, passwords, or personal information, never log them. Be especially careful with error messages—they might expose internal structure or secrets. Log enough to debug, but redact anything that could be sensitive.
Use environment variables for secrets. Never hardcode API keys, database URLs, or other credentials in your code. Always use environment variables. In production, use your deployment platform’s secret management system (like AWS Secrets Manager or Azure Key Vault).
Rate limit and throttle. If your server calls external APIs, implement rate limiting to prevent abuse. A compromised Claude Code instance could accidentally hammer your external service. Add timeouts as we discussed earlier, and consider adding retry logic with exponential backoff.
Validate timestamps and sessions. If your tools work with user sessions or time-sensitive data, validate that sessions are still valid before processing. A stale session shouldn’t be able to perform sensitive operations.
Next Steps and Resources
You’ve now built and deployed your first MCP server. From here:
- Expand your toolset: Add more tools relevant to your workflow. Each tool should do one thing well.
- Integrate with your systems: Connect your MCP server to databases, APIs, or services you use daily.
- Share with others: If you build something useful, consider open-sourcing it. The MCP community is growing rapidly.
- Study existing servers: Look at open-source MCP implementations to see patterns and best practices. The MCP GitHub organization has several examples.
- Monitor and iterate: Watch how Claude Code uses your tools. Are there common errors? Are there tools Claude Code can’t find? Use these signals to improve.
The fact that you’ve come this far means you understand the fundamentals. MCP servers are just programs that respond to structured requests. Everything else is implementation detail. Security, performance, reliability—these are all refinements on the core pattern you’ve learned.
Key Takeaways
Building an MCP server is not as complicated as it might initially seem. You need:
- An initialized Node.js project with the MCP SDK
- A server file that handles
tools/listandtools/callrequests - Proper TypeScript compilation
- Registration in Claude Code’s configuration
- Validation of all inputs from Claude Code
Start simple. Your first server should do one thing well. Once you understand the pattern, scaling to multiple tools and complex logic becomes natural.
The MCP ecosystem is designed to be accessible. There’s no magic here—just a protocol for Claude Code to ask “what can you do?” and then to call those actions when needed.
Now go build something useful. And remember: the fact that you’re here, reading about MCP servers, means you’re already past the steepest part of the learning curve.
—iNet