Hands-on tutorial

MCP Tutorial: Build Your First Model Context Protocol Server (2026)

Model Context Protocol (MCP) is the open standard that lets AI assistants like Claude connect to external tools, databases, and APIs. Think of it as USB-C for AI — one protocol, infinite integrations. This tutorial walks you through building your first MCP server from scratch, with real code you can run today.

Last updated: July 2026 · 20 min read · Includes complete, runnable code examples

What Is MCP and Why It Matters

Model Context Protocol (MCP) is an open standard created by Anthropic that defines how AI applications communicate with external data sources and tools. Before MCP, every AI integration was custom — you had to write bespoke code for each tool, each provider, each use case.

MCP changes this by providing a universal protocol. Build an MCP server once, and it works with every MCP-compatible client — Claude Desktop, Claude Code, VS Code with Copilot, Cursor, and any future client that adopts the standard.

Think of the pre-USB era: every device had a different connector. USB standardized connectivity. MCP does the same for AI tool integration.

MCP Architecture at a Glance

MCP Clients

  • Claude Desktop
  • Claude Code
  • VS Code
  • Cursor
  • Custom apps

AI applications that consume tools and resources

MCP Protocol

  • JSON-RPC 2.0
  • stdio transport
  • SSE transport
  • Capability negotiation

The standardized communication layer

MCP Servers

  • File systems
  • Databases
  • APIs
  • Dev tools
  • Custom tools

Services that expose tools and resources

Clients←→ JSON-RPC ←→Servers

Tools

Functions the AI can call — search, create, update, delete. Each tool has a name, description, and typed input schema.

Resources

Read-only data the AI can access — files, database rows, API responses. Resources are identified by URIs.

Prompts

Reusable prompt templates the server defines. Clients can discover and use them with user arguments.

MCP vs Function Calling vs Tool Use

MCP is often confused with OpenAI's function calling or Anthropic's tool use. They solve related but different problems. Function calling and tool use are API parameters — you define tools per request. MCP is a protocol — you build servers that any client can connect to.

AspectMCPFunction Calling (OpenAI)Tool Use (Anthropic API)
StandardOpen protocol (JSON-RPC over stdio/SSE)Provider-specific API parameterProvider-specific API parameter
InteroperabilityAny MCP client ↔ any MCP serverLocked to one provider (OpenAI, etc.)Locked to one provider (Anthropic, etc.)
Server lifecyclePersistent process — maintains stateStateless per API callStateless per API call
DiscoveryServer advertises capabilities dynamicallyTools defined in each requestTools defined in each request
Transportstdio (local), SSE/HTTP (remote)HTTP APIHTTP API
ResourcesNative resource exposure (files, data)Not supportedNot supported
PromptsServer can define reusable promptsNot supportedNot supported
Who builds itAny developer — open ecosystemApplication developer per requestApplication developer per request

Key insight: MCP and function calling are not competing standards. MCP operates at the application layer — it defines how clients discover and invoke tools. Under the hood, an MCP client might use function calling to let the LLM select which MCP tools to invoke. They are complementary.

Build Your First MCP Server: Step-by-Step Tutorial

Let's build a real MCP server from scratch. By the end, you'll have a working server with resources and tools that connects to Claude Desktop or Claude Code.

1

Set up the project

Initialize a new TypeScript project with the MCP SDK.

# Create project directory
mkdir my-mcp-server && cd my-mcp-server

# Initialize npm project
npm init -y

# Install MCP SDK and TypeScript
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node tsx

# Initialize TypeScript config
npx tsc --init --target ES2022 --module Node16 \
  --moduleResolution Node16 --outDir dist

The @modelcontextprotocol/sdk package provides the core Server class and transport layers. Zod is used for schema validation of tool inputs. We use tsx for development to avoid a compilation step.

2

Define resources

Expose data that clients can read — files, database records, or API responses.

// src/index.ts
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: "my-first-mcp-server",
  version: "1.0.0",
});

// Expose a static resource
server.resource(
  "project-readme",
  "file://readme",
  async (uri) => ({
    contents: [{
      uri: uri.href,
      text: "# My Project\nThis is the project README.",
      mimeType: "text/markdown",
    }],
  })
);

// Expose a dynamic resource (e.g., system info)
server.resource(
  "system-info",
  "system://info",
  async (uri) => ({
    contents: [{
      uri: uri.href,
      text: JSON.stringify({
        platform: process.platform,
        nodeVersion: process.version,
        uptime: process.uptime(),
        memoryUsage: process.memoryUsage().heapUsed,
      }, null, 2),
      mimeType: "application/json",
    }],
  })
);

Resources are read-only data that the MCP client (like Claude) can access. Each resource has a unique URI and returns content with a MIME type. Resources let Claude see your data without you having to paste it into the chat.

3

Create tools

Define tools that Claude can call to perform actions — the core of MCP's power.

// Add tools to the same server instance

// Tool: Search notes
server.tool(
  "search-notes",
  "Search through saved notes by keyword",
  { query: z.string().describe("Search keyword") },
  async ({ query }) => {
    const notes = [
      { id: 1, title: "Meeting notes", content: "Discussed Q3 roadmap and hiring plan" },
      { id: 2, title: "Architecture decision", content: "Moving to event-driven architecture" },
      { id: 3, title: "Bug report", content: "Memory leak in the connection pool" },
    ];
    const matches = notes.filter(
      (n) => n.title.toLowerCase().includes(query.toLowerCase()) ||
             n.content.toLowerCase().includes(query.toLowerCase())
    );
    return {
      content: [{
        type: "text" as const,
        text: matches.length > 0
          ? JSON.stringify(matches, null, 2)
          : `No notes found matching "${query}"`,
      }],
    };
  }
);

// Tool: Create a note
server.tool(
  "create-note",
  "Create a new note with a title and content",
  {
    title: z.string().describe("Note title"),
    content: z.string().describe("Note content"),
  },
  async ({ title, content }) => {
    // In a real app, save to a database
    const id = Date.now();
    return {
      content: [{
        type: "text" as const,
        text: `Note created successfully: { id: ${id}, title: "${title}" }`,
      }],
    };
  }
);

// Tool: Get current weather (external API example)
server.tool(
  "get-weather",
  "Get current weather for a city",
  { city: z.string().describe("City name") },
  async ({ city }) => {
    // Replace with a real weather API call
    const mockWeather = {
      city,
      temperature: "22°C",
      condition: "Partly cloudy",
      humidity: "65%",
    };
    return {
      content: [{
        type: "text" as const,
        text: JSON.stringify(mockWeather, null, 2),
      }],
    };
  }
);

Tools are functions that Claude can invoke. Each tool has a name, description, input schema (using Zod), and a handler function. The description helps Claude understand when to use the tool. Zod schemas provide runtime validation and generate JSON Schema for the protocol.

4

Connect to Claude Desktop / Claude Code

Wire up the transport layer and configure your MCP client.

// Add the transport and start the server (bottom of src/index.ts)

async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("MCP server running on stdio");
}

main().catch(console.error);

The stdio transport communicates over standard input/output, which is how Claude Desktop and Claude Code launch and communicate with MCP servers.

Client configuration

// Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json
// Claude Code: ~/.claude/claude_code_config.json (or project-level .mcp.json)
{
  "mcpServers": {
    "my-first-server": {
      "command": "npx",
      "args": ["tsx", "/absolute/path/to/my-mcp-server/src/index.ts"]
    }
  }
}

Add your server to the MCP configuration file. Claude will automatically start the server process and discover its tools and resources. For Claude Code, you can also use a project-level .mcp.json file.

✅ Test your server

After adding the configuration, restart Claude Desktop or run claude in your terminal for Claude Code. You should see your server's tools available. Try asking:

  • "Search my notes for architecture"
  • "Create a note about the new MCP server I just built"
  • "What's the weather in San Francisco?"
  • "Show me the project README"

Real-World MCP Use Cases

MCP is not just a demo protocol. It's already powering production workflows at companies using Claude for engineering, support, data analysis, and operations. Here are the most impactful use cases.

File system access

Let Claude read and write files on your machine. The official filesystem MCP server provides sandboxed access to specified directories — perfect for code generation, documentation, and file management tasks.

Example prompt: "Read the contents of src/config.ts and suggest improvements"

Database queries

Connect Claude to PostgreSQL, SQLite, or any database. An MCP server can expose read-only queries as tools, letting Claude analyze data, generate reports, and answer questions about your database contents.

Example prompt: "How many users signed up last week? Break it down by referral source."

API integrations

Wrap any REST or GraphQL API as an MCP server. GitHub, Jira, Slack, Linear — Claude can read issues, post messages, create PRs, and manage workflows through tool calls to your MCP servers.

Example prompt: "Create a GitHub issue for the bug we just discussed, labeled as P1."

Development tools

Run linters, test suites, build commands, and deployment scripts. MCP servers can execute shell commands in controlled environments, giving Claude the ability to verify and test its own code changes.

Example prompt: "Run the test suite and fix any failing tests."

Knowledge bases

Index documentation, wikis, or code repositories and expose them as searchable resources. Claude can retrieve relevant context before answering questions, dramatically improving accuracy on domain-specific topics.

Example prompt: "Based on our architecture docs, what's the right way to add a new microservice?"

Monitoring and observability

Connect to Datadog, Grafana, CloudWatch, or custom dashboards. An MCP server can fetch metrics, logs, and alerts, letting Claude diagnose production issues and suggest fixes based on real data.

Example prompt: "Why is API latency spiking? Check the last hour of logs and metrics."

MCP Servers Directory

You don't have to build every MCP server from scratch. A growing ecosystem of official and community servers covers the most common integrations. Here are the most popular ones as of mid-2026.

ServerAuthorDescriptionType
FilesystemAnthropicRead/write files in sandboxed directoriesOfficial
GitHubGitHubIssues, PRs, code search, repository managementOfficial
PostgreSQLAnthropicRead-only SQL queries against PostgreSQL databasesOfficial
PuppeteerAnthropicBrowser automation, screenshots, page interactionOfficial
Brave SearchBraveWeb search with Brave's privacy-focused search engineOfficial
SlackAnthropicRead channels, post messages, manage Slack workspacesOfficial
MemoryAnthropicPersistent memory storage using a knowledge graphOfficial
FetchAnthropicHTTP requests to any URL with content extractionOfficial
LinearCommunityIssue tracking, project management via Linear APICommunity
NotionCommunityRead and write Notion pages and databasesCommunity
DockerCommunityManage containers, images, and Docker Compose stacksCommunity
SentryCommunityError tracking, issue management, performance monitoringCommunity

For the full directory with installation instructions, visit the official MCP servers repository on GitHub.

Learn MCP and AI Tool Building Live

Want hands-on guidance building MCP servers and AI agents? Our live workshop covers practical tool building with Claude Code, including MCP integration patterns used in production.

🔥 Live Workshop: Use Claude Code to 10x Your Engineering Output

Sunday 16th Aug 2026 · 8:30 PM IST · 2 hours · ₹1,499 · Full refund guarantee

Reserve seat

Not ready to register? Get the session outline free:

Not ready to commit?

Get the full session outline + a reminder before the session.

No spam. Just the session details + one reminder email.

Related Resources

Continue learning about AI agents, MCP, and modern AI development with these guides.