Sponsored by Deepsite.site

Model Context Protocol (MCP) Implementation

Created By
AshikNesin9 months ago
Learn MCP by building from Scarch
Content

Model Context Protocol (MCP) Implementation

This project implements the Model Context Protocol (MCP) for building AI tools. It provides a modular framework that can be used to create MCP-compatible servers and clients.


🔍 What is Model Context Protocol (MCP)?

The Model Context Protocol (MCP) is an open protocol that enables AI assistants to interact with external tools and data sources.

Key Features
  • List available tools and their capabilities
  • Call tools with parameters
  • Handle errors in a consistent way
  • Process tool results in a standardized format

📚 For a detailed overview, see MCP Notes.


✨ Features

CategoryFeatures
Core✅ JSON-RPC 2.0 message handling
✅ Protocol initialization
✅ Capability negotiation
Tools✅ Tool registration with JSON Schema
✅ Tool invocation and validation
✅ Standardized error handling
Transport✅ STDIO support
✅ HTTP+SSE Support
Testing✅ Test clients

📁 Project Structure

src/
├── core/           # Core MCP server implementation
├── transports/     # Transport layer implementations (stdio, HTTP+SSE)
├── tools/          # Tool definitions and handlers
├── examples/       # Example servers and clients
│   └── public/     # Static files for HTTP server
└── index.js        # Main entry point for the library

🚀 Getting Started

Prerequisites

  • Node.js 20.x or later
  • npm or pnpm

Installation

# Clone the repository
git clone https://github.com/AshikNesin/learn-mcp-by-building
cd learn-mcp-by-building

# Install dependencies
npm install
# or
pnpm install

🏃‍♂️ Running the Examples

STDIO Server and Client

Run the STDIO server:

npm run server:stdio
# or
node src/examples/stdio-server.js

Test with the STDIO client:

npm run client:stdio
# or
node src/examples/stdio-client.js

Run both together to see a complete test:

npm run test:stdio
# or
node src/examples/stdio-client.js | node src/examples/stdio-server.js

HTTP+SSE Server and Client

Run the HTTP+SSE server:

npm run server:sse
# or
node src/examples/http-sse-server.js --port 5000

Available options:

  • --port: Port to listen on (default: 5000)
  • --host: Host to bind to (default: localhost)
  • --path: Endpoint path (default: /sse)
  • --cors: Enable CORS (default: true)
  • --serve-static: Serve static files from src/examples/public (default: true)

Test with the HTTP+SSE client:

npm run client:sse
# or
node src/examples/http-sse-client.js --server http://localhost:5000/sse

Once running, you can also access the web-based client interface in your browser at http://localhost:5000:

SSE Client Interface

The interface provides a user-friendly way to interact with the MCP server, with a side-by-side layout showing the calculator controls and real-time logs.

🔍 Using the MCP Inspector

You can use the official MCP Inspector to debug the server:

npm run debug

The MCP Inspector provides a visual interface for monitoring and debugging MCP servers:

MCP Inspector


🧮 Calculator Tool

Operations

  • ➕ add
  • ➖ subtract
  • ✖️ multiply
  • ➗ divide

Parameters

  • operation - Operation type
  • a - First operand
  • b - Second operand

Error Handling

  • Division by zero
  • Invalid operations
  • Type validation
  • Missing parameters

🧑‍💻 Developing with the MCP Framework

Creating a New Server

import { McpServer } from '../core/index.js';
import { StdioTransport } from '../transports/index.js';
import { calculatorToolDefinition, handleCalculatorTool } from '../tools/index.js';

// Create server instance
const server = new McpServer(
  { name: 'my-server', version: '1.0.0' },
  { capabilities: { tools: { listChanged: true } } }
);

// Register tool handlers
server.setRequestHandler('tools/list', () => ({ tools: [calculatorToolDefinition] }));
server.setRequestHandler('tools/call', async (params) => {
  if (params.name === 'calculator') {
    return handleCalculatorTool(params.arguments);
  }
  throw new Error(`Tool ${params.name} not found`);
});

// Start the server
const transport = new StdioTransport();
server.connect(transport)
  .then(() => console.error('Server ready!'));

Creating a New Tool

  1. Create a new file in src/tools/:
// src/tools/my-tool.js
export const myToolDefinition = {
  name: 'my-tool',
  description: 'Description of my tool',
  inputSchema: {
    type: 'object',
    properties: {
      // Define parameters
    },
    required: []
  }
};

export async function handleMyTool(args) {
  // Implement tool logic
  return {
    content: [
      {
        type: 'text',
        text: 'Result from my tool'
      }
    ]
  };
}
  1. Export the tool in src/tools/index.js:
export * from './my-tool.js';

🛠️ Protocol Features

  • ✅ Capability negotiation
  • ✅ Tool list change notifications
  • ✅ Standardized error handling
  • ✅ JSON Schema validation
  • ✅ Structured tool results
  • ✅ Transport layer abstraction

📚 External Resources


📝 License

MIT

Recommend Servers
TraeBuild with Free GPT-4.1 & Claude 3.7. Fully MCP-Ready.
TimeA Model Context Protocol server that provides time and timezone conversion capabilities. This server enables LLMs to get current time information and perform timezone conversions using IANA timezone names, with automatic system timezone detection.
Howtocook Mcp基于Anduin2017 / HowToCook (程序员在家做饭指南)的mcp server,帮你推荐菜谱、规划膳食,解决“今天吃什么“的世纪难题; Based on Anduin2017/HowToCook (Programmer's Guide to Cooking at Home), MCP Server helps you recommend recipes, plan meals, and solve the century old problem of "what to eat today"
MCP AdvisorMCP Advisor & Installation - Use the right MCP server for your needs
Zhipu Web SearchZhipu Web Search MCP Server is a search engine specifically designed for large models. It integrates four search engines, allowing users to flexibly compare and switch between them. Building upon the web crawling and ranking capabilities of traditional search engines, it enhances intent recognition capabilities, returning results more suitable for large model processing (such as webpage titles, URLs, summaries, site names, site icons, etc.). This helps AI applications achieve "dynamic knowledge acquisition" and "precise scenario adaptation" capabilities.
ChatWiseThe second fastest AI chatbot™
EdgeOne Pages MCPAn MCP service designed for deploying HTML content to EdgeOne Pages and obtaining an accessible public URL.
Baidu Map百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Context7Context7 MCP Server -- Up-to-date code documentation for LLMs and AI code editors
AiimagemultistyleA Model Context Protocol (MCP) server for image generation and manipulation using fal.ai's Stable Diffusion model.
DeepChatYour AI Partner on Desktop
Playwright McpPlaywright MCP server
CursorThe AI Code Editor
BlenderBlenderMCP connects Blender to Claude AI through the Model Context Protocol (MCP), allowing Claude to directly interact with and control Blender. This integration enables prompt assisted 3D modeling, scene creation, and manipulation.
Visual Studio Code - Open Source ("Code - OSS")Visual Studio Code
Serper MCP ServerA Serper MCP Server
Tavily Mcp
Jina AI MCP ToolsA Model Context Protocol (MCP) server that integrates with Jina AI Search Foundation APIs.
Amap Maps高德地图官方 MCP Server
MiniMax MCPOfficial MiniMax Model Context Protocol (MCP) server that enables interaction with powerful Text to Speech, image generation and video generation APIs.
WindsurfThe new purpose-built IDE to harness magic