tainanfidelis' blogby Tainan Fidelis

Building Your First MCP Server: A Practical Tutorial

28 de abril de 2026

Building Your First MCP Server: A Practical Tutorial

MCP is to AI what REST was to the web — a standard that makes everything interoperable. This MCP server tutorial walks you through building one from scratch in under 30 minutes.

I’m not writing this from a blog post I read. I run MCP servers in production through Paperclip and OpenClaw — systems where AI agents call custom tools across services in real time. That’s the lens here: practitioner-first, not toy demo.


What Is the Model Context Protocol?

Anthropic released MCP in November 2024. By March 2025, OpenAI and Google had adopted it. That’s unusually fast for infrastructure to converge on a standard — which tells you how real the need was.

The idea is simple: before MCP, every AI tool integration was bespoke. You’d build a custom function for Claude, a different one for GPT, another for your internal agent. Same problem, solved three times.

MCP fixes this by separating concerns cleanly:

  • MCP Client — the AI agent (Claude Desktop, Claude Code, your custom agent)
  • MCP Server — a process that exposes tools, resources, and prompts over a defined protocol

Any MCP client can talk to any MCP server. USB-C for AI agents.

The protocol runs over stdio (local) or HTTP with Server-Sent Events (remote). Your server declares its capabilities upfront, and the client negotiates what to use. Full spec at modelcontextprotocol.io.


Prerequisites

Before you start, you need:

  • Node.js 18+ (for TypeScript) or Python 3.10+ (for Python)
  • Basic familiarity with async/await in either language
  • A rough mental model of what an LLM agent does (call tools, read context, generate output)

This tutorial uses TypeScript. The MCP SDK exists for both languages, but the TypeScript version is more complete and what I run in production.


MCP Server Concepts

Three primitives. That’s it.

Tools — functions the agent can call. Think of them like API endpoints: the agent passes arguments, your server runs logic, returns a result. This is where most of your code goes.

Resources — data the agent can read. A markdown file, a database row, a config value. Resources are identified by a URI and the agent fetches them when it needs context.

Prompts — pre-built prompt templates your server exposes. Useful when you want to standardize how the agent approaches a recurring task.

For most use cases you’re building tools and maybe resources. Prompts are a power feature.


Step 1 — Scaffold Your MCP Server

Install the SDK:

mkdir my-mcp-server && cd my-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk
npm install -D typescript @types/node tsx

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./dist",
    "strict": true
  }
}

Now create src/server.ts — the skeleton:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 
// Create the server instance with a name and version
const server = new McpServer({
  name: "my-mcp-server",
  version: "1.0.0",
});
 
// Transport: stdio means this runs as a local process
// Claude Desktop or Claude Code will spawn it and talk over stdin/stdout
const transport = new StdioServerTransport();
 
// Start listening
await server.connect(transport);
console.error("MCP server running"); // Use stderr — stdout is reserved for protocol

That’s a valid (empty) MCP server. It speaks the protocol correctly — nothing exposed yet.


Step 2 — Define a Tool With Schema

Let’s build something real: a search_knowledge_base tool. This is the pattern I use in production for giving agents access to internal docs.

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
 
const server = new McpServer({
  name: "knowledge-base-server",
  version: "1.0.0",
});
 
server.tool(
  "search_knowledge_base",
 
  // Description: this is what the LLM reads to decide when to call this tool.
  // Write it like you're explaining to a smart person, not a search engine.
  "Search the internal knowledge base for documentation, guides, or references. Returns the most relevant results for a given query.",
 
  // Input schema using zod — the SDK validates this before calling your handler
  {
    query: z.string().describe("The search query string"),
    limit: z.number().optional().default(5).describe("Max number of results to return"),
  },
 
  async ({ query, limit }) => {
    // In production this hits a vector DB (Pinecone, pgvector, etc.)
    const results = await fakeSearch(query, limit);
 
    return {
      content: [
        {
          type: "text",
          text: JSON.stringify(results, null, 2),
        },
      ],
    };
  }
);
 
async function fakeSearch(query: string, limit: number) {
  return [
    { title: "Getting Started with DFL", score: 0.92, excerpt: "DevFellowship is a PBL-based..." },
    { title: "Web3 Integration Guide", score: 0.87, excerpt: "For Pods Finance, we use..." },
  ].slice(0, limit);
}
 
const transport = new StdioServerTransport();
await server.connect(transport);

The key insight: the description is prompt engineering. The LLM reads it at runtime to decide whether to call your tool. Be specific about what it does and when to use it. Vague descriptions produce unreliable tool calls.


Step 3 — Expose a Resource

Resources give the agent passive access to data — it reads them when building context, not when executing an action.

import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
 
// Static resource — a file or fixed content
server.resource(
  "company-readme",
  "company://readme",
  async (uri) => {
    const content = await fs.readFile("./README.md", "utf-8");
    return {
      contents: [{ uri: uri.href, mimeType: "text/markdown", text: content }],
    };
  }
);
 
// Dynamic resource with URI template — agent passes a parameter
server.resource(
  "fellow-profile",
  new ResourceTemplate("fellows://{fellowId}/profile", { list: undefined }),
  async (uri, { fellowId }) => {
    const profile = await db.fellows.findById(fellowId);
    return {
      contents: [{ uri: uri.href, mimeType: "application/json", text: JSON.stringify(profile) }],
    };
  }
);

Static resources: config, docs, system prompts. Dynamic resources (URI templates): entity lookups — users, records, anything with an ID.


Step 4 — Test With Claude Desktop / Claude Code

Edit the MCP config. On Mac for Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json. For Claude Code CLI: ~/.claude/claude_desktop_config.json. Same format:

{
  "mcpServers": {
    "knowledge-base": {
      "command": "npx",
      "args": ["tsx", "/path/to/my-mcp-server/src/server.ts"],
      "env": {
        "DATABASE_URL": "postgres://localhost/mydb"
      }
    }
  }
}

Restart Claude Desktop or reload Claude Code. Ask Claude: “Search the knowledge base for information about our onboarding process.” It should call search_knowledge_base and return results.

Debug tips:

# Run the server manually to see startup errors
npx tsx src/server.ts
 
# MCP servers log to stderr — stdout is the protocol channel
# console.log() to stdout will corrupt the protocol stream
# Always use: console.error("debug info")
 
# Check Claude Desktop logs on Mac:
tail -f ~/Library/Logs/Claude/mcp*.log

Most common mistake: logging to stdout instead of stderr. Your server appears connected, tools never work. That’s it.


Real-World Patterns

Things I learned running MCP servers in production that no tutorial told me.

Authentication

Pass credentials via env vars in the MCP config — never hardcode:

const API_KEY = process.env.UPSTREAM_API_KEY;
if (!API_KEY) throw new Error("UPSTREAM_API_KEY is required");
 
server.tool("call_api", "Call the upstream API", { endpoint: z.string() }, async ({ endpoint }) => {
  const res = await fetch(`https://api.example.com/${endpoint}`, {
    headers: { Authorization: `Bearer ${API_KEY}` },
  });
  return { content: [{ type: "text", text: await res.text() }] };
});

Error Handling

Return errors as text content — don’t throw. An uncaught exception kills the protocol session:

server.tool("risky_op", "...", { input: z.string() }, async ({ input }) => {
  try {
    const result = await doSomethingThatMightFail(input);
    return { content: [{ type: "text", text: result }] };
  } catch (err) {
    // Return as content — agent can see the error and decide what to do
    return {
      content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }],
      isError: true,
    };
  }
});

Rate Limiting

Implement backoff inside the handler — the agent just sees success or failure:

async function withRetry<T>(fn: () => Promise<T>, retries = 3): Promise<T> {
  for (let i = 0; i < retries; i++) {
    try {
      return await fn();
    } catch (err) {
      if (i === retries - 1) throw err;
      await new Promise((r) => setTimeout(r, 1000 * (i + 1))); // 1s, 2s, 3s
    }
  }
  throw new Error("unreachable");
}

Stateless vs. Stateful

Go stateless by default. Each tool call should be self-contained — read what you need, do the work, return the result. Don’t hold state in memory between calls.

Exception: browser automation, REPLs, session-heavy workflows — design for it explicitly.

For database access, API wrapping, file operations: stateless is simpler and easier to scale when you move to HTTP transport later.


Conclusion

MCP turns your existing tools and data into agent-native APIs. You’re not building for a specific AI client — you’re building for the protocol. Today that means Claude. Tomorrow it could be GPT, Gemini, or your own agent stack. The full spec and SDK docs live at modelcontextprotocol.io.

The pattern I’ve found most valuable: start with one tool that solves a real problem. In DevFellowship, the first MCP server I wired up gave agents read access to fellow profiles and project status. That single tool unlocked 10 automations I couldn’t have built before.

Build the server. Connect it to Claude Code. See what the agent does with it.

That’s where interesting things start happening.


Next: Context Engineering: How to Feed Your AI Agent the Right Information — the deeper layer that makes MCP tools actually useful.

Subscribe to get new posts before they’re indexed.

Thanks,
Tainan Fidelis.


Edit on GitHub