MCP Learning Project

MCP Learning Project

A comprehensive tutorial project that teaches Model Context Protocol (MCP) development from beginner to advanced levels, covering both server-side and client-side development.

Category
访问服务器

README

MCP Learning Project - Complete Guide

This is a comprehensive tutorial project that teaches Model Context Protocol (MCP) development from beginner to advanced levels. You'll learn both server-side (backend) and client-side (frontend) development.

🎯 What You'll Learn

Beginner Level:

  • ✅ Basic MCP server structure and concepts
  • ✅ Simple tool creation and registration
  • ✅ Parameter handling and validation
  • ✅ Basic client connection and tool calling

Intermediate Level:

  • ✅ State management between tool calls
  • ✅ Resource management (serving data to AI)
  • ✅ Data processing and complex operations
  • ✅ Client-server communication patterns

Advanced Level:

  • ✅ CRUD operations with persistent state
  • ✅ Comprehensive error handling
  • ✅ Prompt templates for AI interactions
  • ✅ Best practices and production considerations

📁 Project Structure

mcp-learning-project/
├── src/
│   ├── server.ts          # MCP Learning Server (backend)
│   └── client.ts          # MCP Learning Client (frontend)
├── dist/                  # Compiled JavaScript
├── package.json           # Dependencies and scripts
├── tsconfig.json          # TypeScript configuration
└── README.md             # This file

🚀 Quick Start

1. Setup Project

# Create project directory
mkdir mcp-learning-project
cd mcp-learning-project

# Initialize npm project
npm init -y

# Install dependencies
npm install @modelcontextprotocol/sdk

# Install dev dependencies
npm install --save-dev typescript @types/node tsx

2. Create Package.json

{
  "name": "mcp-learning-project",
  "version": "1.0.0",
  "description": "Learn MCP development from beginner to advanced",
  "main": "dist/server.js",
  "type": "module",
  "scripts": {
    "build": "tsc",
    "start:server": "node dist/server.js",
    "start:client": "node dist/client.js dist/server.js",
    "dev:server": "tsx src/server.ts",
    "dev:client": "tsx src/client.ts dist/server.js",
    "demo": "npm run build && npm run start:client"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^0.4.0"
  },
  "devDependencies": {
    "@types/node": "^20.0.0",
    "tsx": "^4.0.0",
    "typescript": "^5.0.0"
  }
}

3. Create TypeScript Config

Create tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "ESNext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "declaration": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

4. Save the Code Files

  • Save the MCP Learning Server code as src/server.ts
  • Save the MCP Learning Client code as src/client.ts

5. Build and Run

# Build the project
npm run build

# Run the interactive client (this will also start the server)
npm run demo

🎓 Learning Path

Phase 1: Understanding the Basics

  1. Start the interactive client:

    npm run demo
    
  2. Try basic commands:

    mcp-learning> help
    mcp-learning> tools
    mcp-learning> call hello_world {"name": "Alice"}
    
  3. Learn about resources:

    mcp-learning> resources
    mcp-learning> read mcp-concepts
    

Phase 2: Hands-on Practice

  1. Run the beginner demo:

    mcp-learning> demo beginner
    
  2. Practice tool calls:

    mcp-learning> call calculator {"operation": "add", "a": 5, "b": 3}
    mcp-learning> call calculator {"operation": "divide", "a": 10, "b": 0}
    
  3. Understand state management:

    mcp-learning> call counter {"action": "get"}
    mcp-learning> call counter {"action": "increment", "amount": 5}
    mcp-learning> call counter {"action": "get"}
    

Phase 3: Advanced Concepts

  1. Run intermediate demo:

    mcp-learning> demo intermediate
    
  2. Work with complex data:

    mcp-learning> call data_processor {"data": [5, 2, 8, 1, 9], "operation": "sort"}
    mcp-learning> call data_processor {"data": [5, 2, 8, 1, 9], "operation": "average"}
    
  3. CRUD operations:

    mcp-learning> call task_manager {"action": "create", "task": {"title": "Learn MCP", "priority": "high"}}
    mcp-learning> call task_manager {"action": "list"}
    

Phase 4: Production Ready

  1. Run advanced demo:

    mcp-learning> demo advanced
    
  2. Learn error handling:

    mcp-learning> call error_demo {"error_type": "none"}
    mcp-learning> call error_demo {"error_type": "validation"}
    
  3. Study best practices:

    mcp-learning> read best-practices
    

🔧 Key Concepts Explained

1. MCP Server (Backend)

The server provides capabilities to AI models:

// Server setup
const server = new Server({
  name: 'my-server',
  version: '1.0.0'
}, {
  capabilities: {
    tools: {},      // Functions AI can call
    resources: {},  // Data AI can read  
    prompts: {}     // Templates AI can use
  }
});

// Tool registration
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: 'my_tool',
      description: 'What this tool does',
      inputSchema: { /* JSON Schema */ }
    }
  ]
}));

// Tool implementation
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;
  // Process the tool call and return results
  return {
    content: [{
      type: 'text',
      text: 'Tool response'
    }]
  };
});

2. MCP Client (Frontend)

The client connects to servers and uses their capabilities:

// Client setup
const client = new Client({
  name: 'my-client',
  version: '1.0.0'
}, {
  capabilities: { /* client capabilities */ }
});

// Connect to server
const transport = new StdioClientTransport(/* server process */);
await client.connect(transport);

// Discover server capabilities
const tools = await client.listTools();
const resources = await client.listResources();

// Use server tools
const result = await client.callTool({
  name: 'tool_name',
  arguments: { /* tool parameters */ }
});

3. Communication Flow

┌─────────────┐      ┌─────────────┐      ┌─────────────┐
│   AI Model  │ ───▶ │ MCP Client  │ ───▶ │ MCP Server  │
│             │      │ (Frontend)  │      │ (Backend)   │
│             │ ◀─── │             │ ◀─── │             │
└─────────────┘      └─────────────┘      └─────────────┘
     ▲                      │                      │
     │                      │                      │
     └──────────────────────┴──────────────────────┘
              Uses server capabilities

🧪 Experimentation Ideas

Create Your Own Tools:

  1. Weather Tool:

    {
      name: 'weather',
      description: 'Get weather information',
      inputSchema: {
        type: 'object',
        properties: {
          city: { type: 'string', description: 'City name' },
          units: { type: 'string', enum: ['celsius', 'fahrenheit'], default: 'celsius' }
        },
        required: ['city']
      }
    }
    
  2. File System Tool:

    {
      name: 'file_operations',
      description: 'Basic file system operations',
      inputSchema: {
        type: 'object',
        properties: {
          action: { type: 'string', enum: ['list', 'read', 'write'] },
          path: { type: 'string', description: 'File or directory path' },
          content: { type: 'string', description: 'Content to write' }
        },
        required: ['action', 'path']
      }
    }
    
  3. Database Tool:

    {
      name: 'database',
      description: 'Simple in-memory database operations',
      inputSchema: {
        type: 'object',
        properties: {
          action: { type: 'string', enum: ['create', 'read', 'update', 'delete'] },
          table: { type: 'string', description: 'Table name' },
          data: { type: 'object', description: 'Data to store/update' },
          id: { type: 'string', description: 'Record ID' }
        },
        required: ['action', 'table']
      }
    }
    

Create Custom Resources:

  1. Configuration Resource:

    {
      uri: 'config://app-settings',
      name: 'Application Settings',
      description: 'Current application configuration',
      mimeType: 'application/json'
    }
    
  2. Documentation Resource:

    {
      uri: 'docs://api-reference',
      name: 'API Reference',
      description: 'Complete API documentation',
      mimeType: 'text/markdown'
    }
    

Create Interactive Prompts:

  1. Code Review Prompt:
    {
      name: 'code-review',
      description: 'Start a code review session',
      arguments: [
        {
          name: 'language',
          description: 'Programming language',
          required: true
        },
        {
          name: 'focus',
          description: 'Review focus (security, performance, style)',
          required: false
        }
      ]
    }
    

🐛 Debugging and Troubleshooting

Common Issues:

  1. Server Won't Start:

    # Check if TypeScript compiled correctly
    npm run build
    
    # Look for compilation errors
    npx tsc --noEmit
    
    # Check for missing dependencies
    npm install
    
  2. Client Can't Connect:

    # Make sure server path is correct
    node dist/client.js dist/server.js
    
    # Check if server process starts
    node dist/server.js
    
  3. Tool Calls Fail:

    // Add debugging to your server
    console.error(`[DEBUG] Tool called: ${name}`, JSON.stringify(args));
    
    // Validate input parameters carefully
    if (typeof args.requiredParam === 'undefined') {
      throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter');
    }
    

Debug Mode:

Enable verbose logging in both server and client:

// In server
console.error('[SERVER]', 'Detailed log message');

// In client  
console.log('[CLIENT]', 'Connection status:', connected);

🚀 Next Steps: Building Production Servers

1. Add Real Functionality:

Replace demo tools with actual useful functionality:

// Example: Real file system access
private async handleFileOperations(args: any) {
  const { action, path, content } = args;
  
  switch (action) {
    case 'read':
      return {
        content: [{
          type: 'text',
          text: await fs.readFile(path, 'utf-8')
        }]
      };
    case 'write':
      await fs.writeFile(path, content);
      return {
        content: [{
          type: 'text', 
          text: `File written: ${path}`
        }]
      };
  }
}

2. Add External Integrations:

// Example: HTTP API integration
private async handleApiCall(args: any) {
  const { url, method, data } = args;
  
  const response = await fetch(url, {
    method,
    headers: { 'Content-Type': 'application/json' },
    body: data ? JSON.stringify(data) : undefined
  });
  
  return {
    content: [{
      type: 'text',
      text: JSON.stringify({
        status: response.status,
        data: await response.json()
      }, null, 2)
    }]
  };
}

3. Add Persistence:

import * as fs from 'fs/promises';

class PersistentMCPServer {
  private dataFile = './mcp-data.json';
  
  async loadState(): Promise<Map<string, any>> {
    try {
      const data = await fs.readFile(this.dataFile, 'utf-8');
      return new Map(Object.entries(JSON.parse(data)));
    } catch {
      return new Map();
    }
  }
  
  async saveState(state: Map<string, any>): Promise<void> {
    const data = Object.fromEntries(state);
    await fs.writeFile(this.dataFile, JSON.stringify(data, null, 2));
  }
}

4. Add Authentication:

private validateAuth(headers: any): boolean {
  const token = headers['authorization'];
  return token === 'Bearer your-secret-token';
}

private async handleSecureTool(args: any, headers: any) {
  if (!this.validateAuth(headers)) {
    throw new McpError(ErrorCode.InvalidParams, 'Authentication required');
  }
  
  // Continue with tool logic...
}

📚 Additional Resources

Official Documentation:

Community Examples:

Advanced Topics:

  • HTTP transport for web services
  • WebSocket transport for real-time communication
  • Custom transport implementations
  • Performance optimization techniques
  • Security best practices

🎯 Learning Exercises

Exercise 1: Extend the Calculator

Add more operations: power, sqrt, factorial, sin, cos

Exercise 2: Build a Note-Taking System

Create tools for creating, editing, searching, and organizing notes with tags.

Exercise 3: Add External API Integration

Integrate with a real API (weather, news, stock prices) and create corresponding tools.

Exercise 4: Build a Project Manager

Create a comprehensive project management system with tasks, deadlines, priorities, and progress tracking.

Exercise 5: Add Real-Time Features

Implement tools that can send notifications or updates back to the client.

🏆 Mastery Checklist

Beginner Level ✅

  • [ ] Understand MCP architecture (client, server, transport)
  • [ ] Create basic tools with input validation
  • [ ] Handle simple tool calls and responses
  • [ ] Read and understand error messages

Intermediate Level ✅

  • [ ] Implement stateful tools with persistence
  • [ ] Create and serve resources to AI
  • [ ] Handle complex data processing
  • [ ] Implement proper error handling patterns

Advanced Level ✅

  • [ ] Build CRUD operations with complex state
  • [ ] Create interactive prompt templates
  • [ ] Implement production-ready error handling
  • [ ] Understand security and authentication concepts
  • [ ] Optimize performance for production use

Expert Level 🚀

  • [ ] Build custom transport layers
  • [ ] Create MCP server frameworks
  • [ ] Implement advanced security measures
  • [ ] Build distributed MCP architectures
  • [ ] Contribute to the MCP ecosystem

🎉 Congratulations!

You now have a complete understanding of MCP development from both frontend and backend perspectives. You can:

  • Build MCP servers that provide tools, resources, and prompts
  • Create MCP clients that interact with servers effectively
  • Handle errors gracefully and implement proper validation
  • Manage state between tool calls and across sessions
  • Follow best practices for production-ready implementations

The interactive learning environment in this project gives you hands-on experience with all MCP concepts. Use this as a foundation to build your own specialized MCP servers for any domain or use case!

Happy coding! 🚀

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选