MCP Protocol Tutorial: AI Agents (2027)

Learn Anthropic's Model Context Protocol (MCP) for 2027 AI workflows with working TypeScript code, JSON-RPC tool servers, and client integration.

By CodeAcademix Engineering Team Last updated: December 1, 2026


1. What is the Model Context Protocol (MCP)?

As Large Language Models (LLMs) evolve heading into 2027 from isolated chat assistants into autonomous agents, their primary limitation has been contextual isolation. An LLM on its own cannot query your company database, read your local Git repository, or execute a calculation without an external integration layer.

Historically, every AI developer wrote proprietary, fragile "glue code" to connect specific models to specific tools. In November 2024, Anthropic open-sourced the Model Context Protocol (MCP) to solve this fragmentation.

MCP operates as an open, standardized protocol—frequently described as the "USB-C standard for AI applications." It defines a universal JSON-RPC 2.0 communication format between Clients (host applications such as Claude Desktop, developer IDEs, or agent frameworks) and Servers (lightweight services that expose tools, resources, and custom prompts).


2. Core Architecture & Protocol Mechanics

The architecture of an MCP ecosystem comprises three distinct participants:

┌────────────────────────────────────────────────────────┐
│                      MCP HOST                          │
│        (IDE, Claude Desktop, Autonomous Agent)         │
│                                                        │
│  ┌──────────────────────────────────────────────────┐  │
│  │                    MCP CLIENT                    │  │
│  └──────────────────────────────────────────────────┘  │
└───────────────────────────┬────────────────────────────┘
                            │
               Transport: Stdio or HTTP / SSE
               Protocol: JSON-RPC 2.0
                            │
┌───────────────────────────┴────────────────────────────┐
│                       MCP SERVER                       │
│  ┌───────────────┐ ┌────────────────┐ ┌─────────────┐  │
│  │     Tools     │ │   Resources    │ │   Prompts   │  │
│  │  (Functions)  │ │ (Data Streams) │ │ (Templates) │  │
│  └───────────────┘ └────────────────┘ └─────────────┘  │
└────────────────────────────────────────────────────────┘

The Three Primitive Capabilities

  1. Tools: Executable functions exposed to the model (e.g. running a calculation, executing SQL, making an HTTP API call). The model requests a tool execution, and the server returns the result.
  2. Resources: Read-only data sources resembling file endpoints or API payloads (e.g. documentation, system telemetry, database schemas).
  3. Prompts: Pre-structured prompt templates that guide user interactions with the model.

3. Building an MCP Server with TypeScript

In this section, we will build a production-ready, working MCP server in TypeScript that provides a mathematical calculator tool using standard I/O (stdio) transport.

Step 1: Environment Setup & Dependencies

Initialize a Node.js project and install the official SDK:

npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node

Configure your tsconfig.json with "module": "NodeNext" and "moduleResolution": "NodeNext".

Step 2: The Server Implementation

Create src/server.ts with the following complete, working code:

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";

// Initialize the MCP server instance
const server = new Server(
  {
    name: "codeacademix-calculator-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// Define tool schemas exposed to AI clients
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: [
      {
        name: "calculate",
        description: "Perform basic mathematical operations (add, subtract, multiply, divide).",
        inputSchema: {
          type: "object",
          properties: {
            operation: {
              type: "string",
              enum: ["add", "subtract", "multiply", "divide"],
              description: "The mathematical operation to execute.",
            },
            a: { type: "number", description: "First operand." },
            b: { type: "number", description: "Second operand." },
          },
          required: ["operation", "a", "b"],
        },
      },
    ],
  };
});

// Handle incoming tool execution requests
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "calculate") {
    const { operation, a, b } = args as {
      operation: "add" | "subtract" | "multiply" | "divide";
      a: number;
      b: number;
    };

    let result: number;
    switch (operation) {
      case "add":
        result = a + b;
        break;
      case "subtract":
        result = a - b;
        break;
      case "multiply":
        result = a * b;
        break;
      case "divide":
        if (b === 0) {
          throw new Error("Mathematical error: Division by zero is undefined.");
        }
        result = a / b;
        break;
      default:
        throw new Error(`Unsupported operation: ${operation}`);
    }

    return {
      content: [
        {
          type: "text",
          text: `Calculation: ${operation}(${a}, ${b}) = ${result}`,
        },
      ],
    };
  }

  throw new Error(`Requested tool not found: ${name}`);
});

// Start the server using stdio transport
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("CodeAcademix Calculator MCP Server running on stdio.");
}

main().catch((error) => {
  console.error("Fatal error starting MCP server:", error);
  process.exit(1);
});

4. Building the MCP Client Caller

An MCP Client connects to the server process, discovers its tools, and invokes them when needed.

Create src/client.ts:

import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";

async function runClient() {
  // Connect to the server process via stdio transport
  const transport = new StdioClientTransport({
    command: "node",
    args: ["./dist/server.js"],
  });

  const client = new Client(
    { name: "codeacademix-mcp-client", version: "1.0.0" },
    { capabilities: {} }
  );

  await client.connect(transport);

  // 1. Discover available tools
  const { tools } = await client.listTools();
  console.log("Connected! Available Tools:", tools.map((t) => t.name));

  // 2. Call the calculator tool
  const response = await client.callTool({
    name: "calculate",
    arguments: {
      operation: "multiply",
      a: 14,
      b: 3,
    },
  });

  console.log("Execution Result from MCP Server:", response.content);

  await client.close();
}

runClient().catch((err) => {
  console.error("Client execution failed:", err);
  process.exit(1);
});

5. Security & Production Best Practices

When deploying MCP servers in production environments:

  1. Process Isolation: MCP servers running via stdio execute with the permissions of the host process. When executing untrusted code or database queries, sandbox the server inside Docker containers or secure WebAssembly runtimes.
  2. Schema Strictness: Always validate incoming tool arguments using strict JSON schemas or Zod before passing them to operating system calls or database queries.
  3. Transport Selection: Use stdio for local developer tooling (e.g. desktop apps, local CLI tools) and Server-Sent Events (SSE) over HTTPS for distributed remote services.

6. Next Steps & Interactive Practice

Ready to deepen your backend and AI integration skills?