Chapter 1: Introduction to MCP Protocol Basics

Haiyue
16min

Chapter 1: Introduction to MCP Protocol Basics

Learning Objectives

  1. Understand the basic concepts and design philosophy of MCP protocol
  2. Master the architecture and core components of MCP protocol
  3. Learn the differences and advantages between MCP and traditional APIs
  4. Familiarize with MCP application scenarios and ecosystem

1.1 MCP Protocol Overview

What is MCP Protocol

Model Context Protocol (MCP) is an open standard protocol designed to provide AI models with a secure, standardized way to connect to external data sources and tools. Developed by Anthropic, MCP addresses the standardization challenges of context acquisition and tool invocation in AI applications.

Core Design Philosophy of MCP

// Example of MCP's core design principles
interface MCPDesignPrinciples {
  // 1. Security First - All operations require explicit authorization
  security: 'explicit-permissions';

  // 2. Standardization - Unified interface and protocol
  standardization: 'unified-interface';

  // 3. Extensibility - Support for plugins and extensions
  extensibility: 'plugin-architecture';

  // 4. Type Safety - Strong type definitions
  typeSafety: 'schema-validation';
}

// MCP's core value proposition
const mcpValueProposition = {
  forDevelopers: [
    'Unified development interface',
    'Rich ecosystem',
    'Powerful security mechanisms',
    'Easy to integrate and extend'
  ],

  forAIModels: [
    'Standardized tool access',
    'Structured data acquisition',
    'Secure external interaction',
    'Dynamic context updates'
  ],

  forUsers: [
    'More powerful AI capabilities',
    'Secure and reliable services',
    'Rich application scenarios',
    'Consistent user experience'
  ]
};

1.2 MCP Protocol Architecture

Core Component Architecture

// MCP protocol's core architecture
interface MCPArchitecture {
  // Client - AI model or application
  client: {
    role: 'consumer';
    capabilities: ['call-tools', 'read-resources', 'use-prompts'];
    responsibilities: ['authenticate', 'make-requests', 'handle-responses'];
  };

  // Server - Provides functionality and data
  server: {
    role: 'provider';
    capabilities: ['expose-tools', 'serve-resources', 'provide-prompts'];
    responsibilities: ['validate-requests', 'execute-operations', 'return-results'];
  };

  // Transport layer - Communication protocol
  transport: {
    protocol: 'JSON-RPC 2.0';
    methods: ['stdio', 'websocket', 'http'];
    features: ['bidirectional', 'real-time', 'streaming'];
  };
}

// MCP message flow example
class MCPMessageFlow {
  // Initialize handshake
  async initialize(): Promise<void> {
    const initRequest = {
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: {
        protocolVersion: '2024-11-05',
        capabilities: {
          tools: {},
          resources: { subscribe: true },
          prompts: {}
        },
        clientInfo: {
          name: 'example-client',
          version: '1.0.0'
        }
      }
    };

    console.log('Sending initialization request:', JSON.stringify(initRequest, null, 2));
  }

  // Tool invocation
  async callTool(toolName: string, args: any): Promise<any> {
    const toolRequest = {
      jsonrpc: '2.0',
      id: 2,
      method: 'tools/call',
      params: {
        name: toolName,
        arguments: args
      }
    };

    console.log('Calling tool:', JSON.stringify(toolRequest, null, 2));

    // Simulate response
    return {
      jsonrpc: '2.0',
      id: 2,
      result: {
        content: [
          {
            type: 'text',
            text: 'Tool executed successfully'
          }
        ]
      }
    };
  }
}

The Three Core Components of MCP

// 1. Tools - Tool system
interface MCPTool {
  name: string;
  description: string;
  inputSchema: {
    type: 'object';
    properties: Record<string, any>;
    required?: string[];
  };
}

// Tool example: File reading
const fileReadTool: MCPTool = {
  name: 'read_file',
  description: 'Read file content from specified path',
  inputSchema: {
    type: 'object',
    properties: {
      path: {
        type: 'string',
        description: 'File path'
      },
      encoding: {
        type: 'string',
        description: 'File encoding, defaults to utf-8',
        default: 'utf-8'
      }
    },
    required: ['path']
  }
};

// 2. Resources - Resource system
interface MCPResource {
  uri: string;
  name: string;
  description?: string;
  mimeType?: string;
}

// Resource example: Configuration file
const configResource: MCPResource = {
  uri: 'config://app.json',
  name: 'Application Configuration',
  description: 'Application configuration information',
  mimeType: 'application/json'
};

// 3. Prompts - Prompt template system
interface MCPPrompt {
  name: string;
  description?: string;
  arguments?: Array<{
    name: string;
    description: string;
    required?: boolean;
  }>;
}

// Prompt template example: Code review
const codeReviewPrompt: MCPPrompt = {
  name: 'code_review',
  description: 'Code review prompt template',
  arguments: [
    {
      name: 'code',
      description: 'Code content to review',
      required: true
    },
    {
      name: 'language',
      description: 'Programming language',
      required: false
    }
  ]
};

1.3 Differences Between MCP and Traditional APIs

Traditional API vs MCP Protocol Comparison

// Traditional REST API approach
class TraditionalAPI {
  async getUser(id: string) {
    const response = await fetch(`/api/users/${id}`);
    return response.json();
  }

  async createUser(userData: any) {
    const response = await fetch('/api/users', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData)
    });
    return response.json();
  }
}

// MCP protocol approach
class MCPProtocol {
  // Implement user operations through tool calls
  async getUser(id: string) {
    return await this.callTool('get_user', { id });
  }

  async createUser(userData: any) {
    return await this.callTool('create_user', userData);
  }

  // Get data through resources
  async getUserResource(id: string) {
    return await this.readResource(`user://${id}`);
  }

  private async callTool(name: string, args: any) {
    // MCP tool call logic
    return { success: true, data: {} };
  }

  private async readResource(uri: string) {
    // MCP resource read logic
    return { content: 'resource data' };
  }
}

// Main differences comparison
const comparisonTable = {
  aspects: {
    purpose: {
      traditional: 'General-purpose network service interface',
      mcp: 'Context protocol designed specifically for AI models'
    },

    dataFlow: {
      traditional: 'Request-response pattern',
      mcp: 'Bidirectional communication, supports subscriptions and notifications'
    },

    security: {
      traditional: 'HTTP authentication, API keys',
      mcp: 'Explicit permission model and security sandbox'
    },

    typeSystem: {
      traditional: 'Usually based on JSON Schema or OpenAPI',
      mcp: 'Built-in strong type system and validation'
    },

    extensibility: {
      traditional: 'Version control and backward compatibility',
      mcp: 'Plugin architecture and dynamic extension'
    }
  }
};

1.4 MCP Application Scenarios

Main Application Scenarios

// 1. File system integration
class FileSystemMCPServer {
  tools = [
    {
      name: 'read_file',
      description: 'Read file content',
      handler: async (args: { path: string }) => {
        // Actual file reading logic
        return { content: 'file content' };
      }
    },
    {
      name: 'write_file',
      description: 'Write file',
      handler: async (args: { path: string; content: string }) => {
        // Actual file writing logic
        return { success: true };
      }
    }
  ];
}

// 2. Database integration
class DatabaseMCPServer {
  tools = [
    {
      name: 'query_database',
      description: 'Execute database query',
      handler: async (args: { sql: string; params?: any[] }) => {
        // Database query logic
        return { rows: [], count: 0 };
      }
    }
  ];

  resources = [
    {
      uri: 'db://users/schema',
      name: 'Users Table Schema',
      handler: async () => ({
        content: JSON.stringify({
          table: 'users',
          columns: ['id', 'name', 'email']
        })
      })
    }
  ];
}

// 3. API proxy service
class APIProxyMCPServer {
  tools = [
    {
      name: 'call_external_api',
      description: 'Call external API',
      handler: async (args: { endpoint: string; method: string; data?: any }) => {
        // API call logic
        return { response: 'api response' };
      }
    }
  ];
}

// 4. Content management system
class CMSMCPServer {
  resources = [
    {
      uri: 'cms://articles',
      name: 'Articles List',
      handler: async () => ({
        content: JSON.stringify([
          { id: 1, title: 'First Article' },
          { id: 2, title: 'Second Article' }
        ])
      })
    }
  ];

  prompts = [
    {
      name: 'generate_article',
      description: 'Prompt template for generating article content',
      handler: async (args: { topic: string; style: string }) => ({
        messages: [
          {
            role: 'user',
            content: {
              type: 'text',
              text: `Please write an article about ${args.topic} in ${args.style} style`
            }
          }
        ]
      })
    }
  ];
}

1.5 MCP Ecosystem

MCP Technology Stack

// MCP technology stack overview
interface MCPEcosystem {
  // Core protocol
  protocol: {
    specification: 'MCP Protocol Specification v1.0';
    transport: ['stdio', 'websocket', 'http'];
    messageFormat: 'JSON-RPC 2.0';
  };

  // Official SDKs
  officialSDKs: {
    typescript: '@modelcontextprotocol/sdk';
    python: 'mcp';
    // More language support under development
  };

  // Development tools
  devTools: {
    inspector: 'MCP Inspector';
    testing: 'MCP Test Suite';
    debugging: 'MCP Debug Tools';
  };

  // Community ecosystem
  community: {
    servers: 'Community MCP Servers';
    tools: 'Third-party Tools';
    examples: 'Code Examples and Templates';
  };
}

// MCP server example directory
const mcpServerExamples = {
  filesystem: {
    name: 'File System Server',
    description: 'Provides file operation capabilities',
    features: ['read', 'write', 'list', 'delete']
  },

  database: {
    name: 'Database Server',
    description: 'Database operation interface',
    features: ['query', 'insert', 'update', 'schema']
  },

  web: {
    name: 'Web Scraping Server',
    description: 'Web content scraping',
    features: ['fetch', 'parse', 'search', 'monitor']
  },

  git: {
    name: 'Git Server',
    description: 'Git version control operations',
    features: ['clone', 'commit', 'push', 'status']
  },

  memory: {
    name: 'Memory Server',
    description: 'Persistent memory system',
    features: ['store', 'retrieve', 'search', 'organize']
  }
};

1.6 Advantages and Features of MCP

Core Advantages

// Core advantages of MCP protocol
class MCPAdvantages {
  // 1. Security
  security = {
    explicitPermissions: 'Each operation requires explicit authorization',
    sandboxExecution: 'Tools execute in security sandbox',
    inputValidation: 'Strict input validation and type checking',
    auditTrail: 'Complete operation audit logs'
  };

  // 2. Standardization
  standardization = {
    unifiedInterface: 'Unified protocol interface',
    consistentAPI: 'Consistent API design',
    interoperability: 'Cross-platform and cross-language compatibility',
    versionControl: 'Protocol version management'
  };

  // 3. Extensibility
  extensibility = {
    pluginArchitecture: 'Plugin-based architecture design',
    customTools: 'Custom tool development',
    dynamicLoading: 'Dynamic loading and unloading',
    protocolExtensions: 'Protocol extension mechanisms'
  };

  // 4. Developer Experience
  developerExperience = {
    typeScript: 'Complete TypeScript support',
    documentation: 'Rich documentation and examples',
    tooling: 'Powerful development toolchain',
    community: 'Active community support'
  };
}

// Actual application impact comparison
const impactComparison = {
  beforeMCP: {
    challenges: [
      'Each AI application needs custom integration',
      'Lack of unified security standards',
      'Inconsistent tool and resource access',
      'High development and maintenance costs'
    ]
  },

  withMCP: {
    benefits: [
      'Develop once, use everywhere',
      'Unified security and permission model',
      'Standardized interface and protocol',
      'Rich ecosystem support'
    ]
  }
};

1.7 Quick Start Example

Simplest MCP Server

// A simplest MCP Server example
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';

// Create MCP server
const server = new Server(
  {
    name: 'hello-world-server',
    version: '1.0.0'
  },
  {
    capabilities: {
      tools: {},
      resources: {},
      prompts: {}
    }
  }
);

// Add a simple tool
server.setRequestHandler(
  'tools/list',
  async () => ({
    tools: [
      {
        name: 'say_hello',
        description: 'A simple tool to say hello',
        inputSchema: {
          type: 'object',
          properties: {
            name: {
              type: 'string',
              description: 'Name to greet'
            }
          }
        }
      }
    ]
  })
);

// Implement tool invocation
server.setRequestHandler(
  'tools/call',
  async (request) => {
    if (request.params.name === 'say_hello') {
      const name = request.params.arguments?.name || 'World';
      return {
        content: [
          {
            type: 'text',
            text: `Hello, ${name}!`
          }
        ]
      };
    }
    throw new Error(`Unknown tool: ${request.params.name}`);
  }
);

// Start server
const transport = new StdioServerTransport();
await server.connect(transport);
console.log('Hello World MCP Server is running!');

Project Structure Example

hello-world-mcp-server/
├── package.json
├── tsconfig.json
├── src/
│   ├── index.ts          # Main entry file
│   ├── tools/            # Tool definitions
│   │   └── hello.ts
│   ├── resources/        # Resource definitions
│   │   └── static.ts
│   └── prompts/          # Prompt templates
│       └── greeting.ts
├── dist/                 # Build output
├── tests/                # Test files
└── README.md             # Project documentation

Summary

MCP protocol brings standardization, security, and extensibility solutions to AI application development. Through this chapter, we learned:

  1. Core Concepts of MCP Protocol: Providing standardized external interaction capabilities for AI models
  2. Architecture Design: Client-server model based on JSON-RPC 2.0
  3. Three Core Components: Tools, Resources, Prompts
  4. Differences from Traditional APIs: Designed specifically for AI with stronger security and type system
  5. Application Scenarios: File systems, databases, API proxies, content management, etc.
  6. Ecosystem: SDKs, development tools, community resources

Next, we will learn how to set up an MCP Server development environment and start practical development.

Extended Reading