Skip to content

Latest commit

 

History

History
849 lines (681 loc) · 43.9 KB

File metadata and controls

849 lines (681 loc) · 43.9 KB

ชุมชนและการมีส่วนร่วม

วิธีการมีส่วนร่วมกับ MCP: เครื่องมือ, เอกสาร, โค้ด และอื่น ๆ

(คลิกที่ภาพด้านบนเพื่อดูวิดีโอของบทเรียนนี้)

ภาพรวม

บทเรียนนี้มุ่งเน้นไปที่วิธีการมีส่วนร่วมกับชุมชน MCP, การมีส่วนร่วมในระบบนิเวศ MCP และการปฏิบัติที่ดีที่สุดสำหรับการพัฒนาร่วมกัน การเข้าใจวิธีการเข้าร่วมโครงการ MCP แบบโอเพ่นซอร์สเป็นสิ่งสำคัญสำหรับผู้ที่ต้องการกำหนดรูปแบบอนาคตของเทคโนโลยีนี้

วัตถุประสงค์การเรียนรู้

เมื่อจบบทเรียนนี้ คุณจะสามารถ:

  • เข้าใจโครงสร้างของชุมชน MCP และระบบนิเวศ
  • มีส่วนร่วมอย่างมีประสิทธิภาพในฟอรัมและการสนทนาของชุมชน MCP
  • มีส่วนร่วมในที่เก็บข้อมูลโอเพ่นซอร์สของ MCP
  • สร้างและแบ่งปันเครื่องมือและเซิร์ฟเวอร์ MCP ที่กำหนดเอง
  • ปฏิบัติตามแนวทางปฏิบัติที่ดีที่สุดสำหรับการพัฒนาและความร่วมมือของ MCP
  • ค้นพบทรัพยากรและกรอบงานของชุมชนสำหรับการพัฒนา MCP

ระบบนิเวศชุมชน MCP

ระบบนิเวศ MCP ประกอบด้วยส่วนประกอบและผู้เข้าร่วมที่หลากหลายที่ทำงานร่วมกันเพื่อพัฒนาระเบียบวิธี

ส่วนประกอบหลักของชุมชน

  1. ผู้ดูแลแกนกลางโปรโตคอล: องค์กร GitHub ของ Model Context Protocol อย่างเป็นทางการ ดูแลข้อกำหนดแกน MCP และการดำเนินการอ้างอิง
  2. นักพัฒนาเครื่องมือ: บุคคลและทีมที่สร้างเครื่องมือและเซิร์ฟเวอร์ MCP
  3. ผู้ให้บริการการผนวกรวม: บริษัทที่ผนวกรวม MCP เข้ากับผลิตภัณฑ์และบริการของพวกเขา
  4. ผู้ใช้ปลายทาง: นักพัฒนาและองค์กรที่ใช้ MCP ในแอปพลิเคชันของตน
  5. ผู้มีส่วนร่วม: สมาชิกชุมชนที่มีส่วนร่วมด้วยโค้ด เอกสาร หรือทรัพยากรอื่น ๆ

ทรัพยากรของชุมชน

ช่องทางทางการ

ทรัพยากรที่ขับเคลื่อนโดยชุมชน

การมีส่วนร่วมใน MCP

ประเภทของการมีส่วนร่วม

ระบบนิเวศ MCP ยินดีรับการมีส่วนร่วมในหลายประเภท:

  1. การมีส่วนร่วมด้วยโค้ด:

    • การปรับปรุงแกนโปรโตคอล
    • การแก้ไขบั๊ก
    • การดำเนินการเครื่องมือและเซิร์ฟเวอร์
    • ไลบรารีลูกค้า/เซิร์ฟเวอร์ในภาษาต่าง ๆ
  2. เอกสาร:

    • ปรับปรุงเอกสารที่มีอยู่
    • สร้างบทแนะนำและคำแนะนำ
    • แปลเอกสาร
    • สร้างตัวอย่างและแอปพลิเคชันตัวอย่าง
  3. สนับสนุนชุมชน:

    • ตอบคำถามในฟอรัมและการสนทนา
    • ทดสอบและรายงานปัญหา
    • จัดกิจกรรมชุมชน
    • ให้คำปรึกษาแก่ผู้มีส่วนร่วมใหม่

กระบวนการมีส่วนร่วม: แกนโปรโตคอล

ในการมีส่วนร่วมกับแกนกลางโปรโตคอล MCP หรือการดำเนินการอย่างเป็นทางการ ให้ปฏิบัติตามหลักการจาก แนวทางการมีส่วนร่วมอย่างเป็นทางการ:

  1. ความเรียบง่ายและความเรียบง่ายขั้นต่ำ: ข้อกำหนด MCP ตั้งมาตรฐานสูงสำหรับการเพิ่มแนวคิดใหม่ การเพิ่มสิ่งใหม่ในข้อกำหนดง่ายกว่าการลบออก
  2. แนวทางที่จับต้องได้: การเปลี่ยนแปลงข้อกำหนดควรอิงกับความท้าทายในการนำไปปฏิบัติจริง ไม่ใช่แนวคิดสมมุติ
  3. ขั้นตอนของข้อเสนอ:
    • กำหนด: สำรวจกระบวนการปัญหา, ตรวจสอบว่าผู้ใช้ MCP รายอื่นเผชิญกับปัญหาเดียวกันหรือไม่
    • ต้นแบบ: สร้างตัวอย่างแก้ไขและสาธิตการใช้งานจริง
    • เขียน: อิงจากต้นแบบ เขียนข้อเสนอข้อกำหนด

การตั้งค่าสภาพแวดล้อมการพัฒนา

# สร้างโฟลกของที่เก็บข้อมูล
git clone https://github.com/YOUR-USERNAME/modelcontextprotocol.git
cd modelcontextprotocol

# ติดตั้ง dependencies
npm install

# สำหรับการเปลี่ยนแปลง schema ให้ตรวจสอบและสร้าง schema.json:
npm run check:schema:ts
npm run generate:schema

# สำหรับการเปลี่ยนแปลงเอกสาร
npm run check:docs
npm run format

# แสดงตัวอย่างเอกสารในเครื่อง (ไม่จำเป็น):
npm run serve:docs

ตัวอย่าง: การมีส่วนร่วมด้วยการแก้ไขบั๊ก

// โค้ดต้นฉบับที่มีบั๊กใน typescript-sdk
export function validateResource(resource: unknown): resource is MCPResource {
  if (!resource || typeof resource !== 'object') {
    return false;
  }
  
  // บั๊ก: ขาดการตรวจสอบคุณสมบัติ
  // การใช้งานปัจจุบัน:
  const hasName = 'name' in resource;
  const hasSchema = 'schema' in resource;
  
  return hasName && hasSchema;
}

// การใช้งานที่แก้ไขในส่วนร่วม
export function validateResource(resource: unknown): resource is MCPResource {
  if (!resource || typeof resource !== 'object') {
    return false;
  }
  
  // การตรวจสอบที่ดีขึ้น
  const hasName = 'name' in resource && typeof (resource as MCPResource).name === 'string';
  const hasSchema = 'schema' in resource && typeof (resource as MCPResource).schema === 'object';
  const hasDescription = !('description' in resource) || typeof (resource as MCPResource).description === 'string';
  
  return hasName && hasSchema && hasDescription;
}

ตัวอย่าง: การมีส่วนร่วมด้วยเครื่องมือใหม่ในไลบรารีมาตรฐาน

# ตัวอย่างการมีส่วนร่วม: เครื่องมือประมวลผลข้อมูล CSV สำหรับไลบรารีมาตรฐาน MCP

from mcp_tools import Tool, ToolRequest, ToolResponse, ToolExecutionException
import pandas as pd
import io
import json
from typing import Dict, Any, List, Optional

class CsvProcessingTool(Tool):
    """
    Tool for processing and analyzing CSV data.
    
    This tool allows models to extract information from CSV files,
    run basic analysis, and convert data between formats.
    """
    
    def get_name(self):
        return "csvProcessor"
        
    def get_description(self):
        return "Processes and analyzes CSV data"
    
    def get_schema(self):
        return {
            "type": "object",
            "properties": {
                "csvData": {
                    "type": "string", 
                    "description": "CSV data as a string"
                },
                "csvUrl": {
                    "type": "string",
                    "description": "URL to a CSV file (alternative to csvData)"
                },
                "operation": {
                    "type": "string",
                    "enum": ["summary", "filter", "transform", "convert"],
                    "description": "Operation to perform on the CSV data"
                },
                "filterColumn": {
                    "type": "string",
                    "description": "Column to filter by (for filter operation)"
                },
                "filterValue": {
                    "type": "string",
                    "description": "Value to filter for (for filter operation)"
                },
                "outputFormat": {
                    "type": "string",
                    "enum": ["json", "csv", "markdown"],
                    "default": "json",
                    "description": "Output format for the processed data"
                }
            },
            "oneOf": [
                {"required": ["csvData", "operation"]},
                {"required": ["csvUrl", "operation"]}
            ]
        }
    
    async def execute_async(self, request: ToolRequest) -> ToolResponse:
        try:
            # ดึงพารามิเตอร์
            operation = request.parameters.get("operation")
            output_format = request.parameters.get("outputFormat", "json")
            
            # รับข้อมูล CSV จากข้อมูลโดยตรงหรือ URL
            df = await self._get_dataframe(request)
            
            # ประมวลผลตามการดำเนินการที่ร้องขอ
            result = {}
            
            if operation == "summary":
                result = self._generate_summary(df)
            elif operation == "filter":
                column = request.parameters.get("filterColumn")
                value = request.parameters.get("filterValue")
                if not column:
                    raise ToolExecutionException("filterColumn is required for filter operation")
                result = self._filter_data(df, column, value)
            elif operation == "transform":
                result = self._transform_data(df, request.parameters)
            elif operation == "convert":
                result = self._convert_format(df, output_format)
            else:
                raise ToolExecutionException(f"Unknown operation: {operation}")
            
            return ToolResponse(result=result)
        
        except Exception as e:
            raise ToolExecutionException(f"CSV processing failed: {str(e)}")
    
    async def _get_dataframe(self, request: ToolRequest) -> pd.DataFrame:
        """Gets a pandas DataFrame from either CSV data or URL"""
        if "csvData" in request.parameters:
            csv_data = request.parameters.get("csvData")
            return pd.read_csv(io.StringIO(csv_data))
        elif "csvUrl" in request.parameters:
            csv_url = request.parameters.get("csvUrl")
            return pd.read_csv(csv_url)
        else:
            raise ToolExecutionException("Either csvData or csvUrl must be provided")
    
    def _generate_summary(self, df: pd.DataFrame) -> Dict[str, Any]:
        """Generates a summary of the CSV data"""
        return {
            "columns": df.columns.tolist(),
            "rowCount": len(df),
            "columnCount": len(df.columns),
            "numericColumns": df.select_dtypes(include=['number']).columns.tolist(),
            "categoricalColumns": df.select_dtypes(include=['object']).columns.tolist(),
            "sampleRows": json.loads(df.head(5).to_json(orient="records")),
            "statistics": json.loads(df.describe().to_json())
        }
    
    def _filter_data(self, df: pd.DataFrame, column: str, value: str) -> Dict[str, Any]:
        """Filters the DataFrame by a column value"""
        if column not in df.columns:
            raise ToolExecutionException(f"Column '{column}' not found")
            
        filtered_df = df[df[column].astype(str).str.contains(value)]
        
        return {
            "originalRowCount": len(df),
            "filteredRowCount": len(filtered_df),
            "data": json.loads(filtered_df.to_json(orient="records"))
        }
    
    def _transform_data(self, df: pd.DataFrame, params: Dict[str, Any]) -> Dict[str, Any]:
        """Transforms the data based on parameters"""
        # การใช้งานจะรวมถึงการแปลงข้อมูลหลายรูปแบบ
        return {
            "status": "success",
            "message": "Transformation applied"
        }
    
    def _convert_format(self, df: pd.DataFrame, format: str) -> Dict[str, Any]:
        """Converts the DataFrame to different formats"""
        if format == "json":
            return {
                "data": json.loads(df.to_json(orient="records")),
                "format": "json"
            }
        elif format == "csv":
            return {
                "data": df.to_csv(index=False),
                "format": "csv"
            }
        elif format == "markdown":
            return {
                "data": df.to_markdown(),
                "format": "markdown"
            }
        else:
            raise ToolExecutionException(f"Unsupported output format: {format}")

แนวทางการมีส่วนร่วม

เพื่อให้การมีส่วนร่วมกับโครงการ MCP ประสบความสำเร็จ:

  1. เริ่มต้นเล็ก ๆ: เริ่มจากเอกสาร แก้ไขบั๊ก หรือปรับปรุงเล็กน้อย
  2. ปฏิบัติตามคู่มือสไตล์: ปฏิบัติตามรูปแบบการเขียนโค้ดและข้อกำหนดของโปรเจค
  3. เขียนการทดสอบ: รวมการทดสอบหน่วยสำหรับโค้ดของคุณ
  4. เขียนเอกสารการทำงาน: เพิ่มเอกสารที่ชัดเจนสำหรับฟีเจอร์หรือการเปลี่ยนแปลงใหม่
  5. ส่ง PR ที่เหมาะสม: ทำให้คำขอ Pull Request มุ่งเน้นเรื่องเดียวหรือฟีเจอร์เดียว
  6. ตอบรับข้อเสนอแนะ: ตอบสนองต่อข้อเสนอแนะจากการมีส่วนร่วมของคุณ

ขั้นตอนตัวอย่างของการทำงานร่วมกัน

# โคลนที่เก็บข้อมูล
git clone https://github.com/modelcontextprotocol/typescript-sdk.git
cd typescript-sdk

# สร้างสาขาใหม่สำหรับการมีส่วนร่วมของคุณ
git checkout -b feature/my-contribution

# ทำการเปลี่ยนแปลงของคุณ
# ...

# รันการทดสอบเพื่อให้แน่ใจว่าการเปลี่ยนแปลงของคุณไม่ทำให้ฟังก์ชันเดิมเสียหาย
npm test

# คอมมิตการเปลี่ยนแปลงของคุณพร้อมข้อความอธิบาย
git commit -am "Fix validation in resource handler"

# ผลักดันสาขาของคุณไปยังโฟกของคุณ
git push origin feature/my-contribution

# สร้างคำขอดึงจากสาขาของคุณไปยังที่เก็บหลัก
# จากนั้นมีส่วนร่วมกับความคิดเห็นและปรับปรุง PR ของคุณตามที่จำเป็น

การสร้างและแบ่งปันเซิร์ฟเวอร์ MCP

หนึ่งในวิธีที่มีคุณค่าที่สุดในการมีส่วนร่วมกับระบบนิเวศ MCP คือการสร้างและแบ่งปันเซิร์ฟเวอร์ MCP ที่กำหนดเอง ชุมชนได้สร้างเซิร์ฟเวอร์หลายร้อยสำหรับบริการและกรณีใช้งานต่าง ๆ แล้ว

กรอบงานสำหรับการพัฒนาเซิร์ฟเวอร์ MCP

มีกรอบงานหลายตัวที่พร้อมใช้งานเพื่อช่วยให้การพัฒนาเซิร์ฟเวอร์ MCP ง่ายขึ้น:

  1. SDK อย่างเป็นทางการ (สอดคล้องกับ ข้อกำหนด MCP 2025-11-25):

  2. กรอบงานของชุมชน:

    • MCP-Framework - สร้างเซิร์ฟเวอร์ MCP อย่างสง่างามและรวดเร็วด้วย TypeScript
    • MCP Declarative Java SDK - เซิร์ฟเวอร์ MCP แบบขับเคลื่อนด้วยคำอธิบายประกอบด้วย Java
    • Quarkus MCP Server SDK - กรอบงาน Java สำหรับเซิร์ฟเวอร์ MCP
    • Next.js MCP Server Template - โปรเจกต์เริ่มต้น Next.js สำหรับเซิร์ฟเวอร์ MCP

การพัฒนาเครื่องมือที่แชร์ได้

ตัวอย่าง .NET: การสร้างแพ็กเกจเครื่องมือที่แชร์ได้

// Create a new .NET library project
// dotnet new classlib -n McpFinanceTools

using Microsoft.Mcp.Tools;
using System.Threading.Tasks;
using System.Net.Http;
using System.Text.Json;

namespace McpFinanceTools
{
    // Stock quote tool
    public class StockQuoteTool : IMcpTool
    {
        private readonly HttpClient _httpClient;
        
        public StockQuoteTool(HttpClient httpClient = null)
        {
            _httpClient = httpClient ?? new HttpClient();
        }
        
        public string Name => "stockQuote";
        public string Description => "Gets current stock quotes for specified symbols";
        
        public object GetSchema()
        {
            return new {
                type = "object",
                properties = new {
                    symbol = new { 
                        type = "string",
                        description = "Stock symbol (e.g., MSFT, AAPL)" 
                    },
                    includeHistory = new { 
                        type = "boolean",
                        description = "Whether to include historical data",
                        default = false
                    }
                },
                required = new[] { "symbol" }
            };
        }
        
        public async Task<ToolResponse> ExecuteAsync(ToolRequest request)
        {
            // Extract parameters
            string symbol = request.Parameters.GetProperty("symbol").GetString();
            bool includeHistory = false;
            
            if (request.Parameters.TryGetProperty("includeHistory", out var historyProp))
            {
                includeHistory = historyProp.GetBoolean();
            }
            
            // Call external API (example)
            var quoteResult = await GetStockQuoteAsync(symbol);
            
            // Add historical data if requested
            if (includeHistory)
            {
                var historyData = await GetStockHistoryAsync(symbol);
                quoteResult.Add("history", historyData);
            }
            
            // Return formatted result
            return new ToolResponse {
                Result = JsonSerializer.SerializeToElement(quoteResult)
            };
        }
        
        private async Task<Dictionary<string, object>> GetStockQuoteAsync(string symbol)
        {
            // Implementation would call a real stock API
            // This is a simplified example
            return new Dictionary<string, object>
            {
                ["symbol"] = symbol,
                ["price"] = 123.45,
                ["change"] = 2.5,
                ["percentChange"] = 1.2,
                ["lastUpdated"] = DateTime.UtcNow
            };
        }
        
        private async Task<object> GetStockHistoryAsync(string symbol)
        {
            // Implementation would get historical data
            // Simplified example
            return new[]
            {
                new { date = DateTime.Now.AddDays(-7).Date, price = 120.25 },
                new { date = DateTime.Now.AddDays(-6).Date, price = 122.50 },
                new { date = DateTime.Now.AddDays(-5).Date, price = 121.75 }
                // More historical data...
            };
        }
    }
}

// Create package and publish to NuGet
// dotnet pack -c Release
// dotnet nuget push bin/Release/McpFinanceTools.1.0.0.nupkg -s https://api.nuget.org/v3/index.json -k YOUR_API_KEY

ตัวอย่าง Java: การสร้างแพ็กเกจ Maven สำหรับเครื่องมือ

// การกำหนดค่า pom.xml สำหรับแพ็คเกจเครื่องมือ MCP ที่แชร์ได้
<!-- 
<project>
    <groupId>com.example</groupId>
    <artifactId>mcp-weather-tools</artifactId>
    <version>1.0.0</version>
    
    <dependencies>
        <dependency>
            <groupId>com.mcp</groupId>
            <artifactId>mcp-server</artifactId>
            <version>1.0.0</version>
        </dependency>
    </dependencies>
    
    <distributionManagement>
        <repository>
            <id>github</id>
            <name>GitHub Packages</name>
            <url>https://maven.pkg.github.com/username/mcp-weather-tools</url>
        </repository>
    </distributionManagement>
</project>
-->

package com.example.mcp.weather;

import com.mcp.tools.Tool;
import com.mcp.tools.ToolRequest;
import com.mcp.tools.ToolResponse;
import com.mcp.tools.ToolExecutionException;

import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;

public class WeatherForecastTool implements Tool {
    private final HttpClient httpClient;
    private final String apiKey;
    
    public WeatherForecastTool(String apiKey) {
        this.httpClient = HttpClient.newHttpClient();
        this.apiKey = apiKey;
    }
    
    @Override
    public String getName() {
        return "weatherForecast";
    }
    
    @Override
    public String getDescription() {
        return "Gets weather forecast for a specified location";
    }
    
    @Override
    public Object getSchema() {
        Map<String, Object> schema = new HashMap<>();
        // คำจำกัดความสคีมา...
        return schema;
    }
    
    @Override
    public ToolResponse execute(ToolRequest request) {
        try {
            String location = request.getParameters().get("location").asText();
            int days = request.getParameters().has("days") ? 
                request.getParameters().get("days").asInt() : 3;
            
            // เรียกใช้ API สภาพอากาศ
            Map<String, Object> forecast = getForecast(location, days);
            
            // สร้างการตอบกลับ
            return new ToolResponse.Builder()
                .setResult(forecast)
                .build();
        } catch (Exception ex) {
            throw new ToolExecutionException("Weather forecast failed: " + ex.getMessage(), ex);
        }
    }
    
    private Map<String, Object> getForecast(String location, int days) {
        // การใช้งานจะเรียกใช้ API สภาพอากาศ
        // ตัวอย่างที่เรียบง่าย
        Map<String, Object> result = new HashMap<>();
        // เพิ่มข้อมูลพยากรณ์...
        return result;
    }
}

// สร้างและเผยแพร่ด้วย Maven
// mvn clean package
// mvn deploy

ตัวอย่าง Python: การเผยแพร่แพ็กเกจ PyPI

# โครงสร้างไดเรกทอรีสำหรับแพ็กเกจ PyPI:
# mcp_nlp_tools/
# ├── LICENSE
# ├── README.md
# ├── setup.py
# ├── mcp_nlp_tools/
# │   ├── __init__.py
# │   ├── sentiment_tool.py
# │   └── translation_tool.py

# ตัวอย่าง setup.py
"""
from setuptools import setup, find_packages

setup(
    name="mcp_nlp_tools",
    version="0.1.0",
    packages=find_packages(),
    install_requires=[
        "mcp_server>=1.0.0",
        "transformers>=4.0.0",
        "torch>=1.8.0"
    ],
    author="Your Name",
    author_email="your.email@example.com",
    description="MCP tools for natural language processing tasks",
    long_description=open("README.md").read(),
    long_description_content_type="text/markdown",
    url="https://github.com/username/mcp_nlp_tools",
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.8",
)
"""

# ตัวอย่างการใช้งานเครื่องมือ NLP (sentiment_tool.py)
from mcp_tools import Tool, ToolRequest, ToolResponse, ToolExecutionException
from transformers import pipeline
import torch

class SentimentAnalysisTool(Tool):
    """MCP tool for sentiment analysis of text"""
    
    def __init__(self, model_name="distilbert-base-uncased-finetuned-sst-2-english"):
        # โหลดโมเดลวิเคราะห์อารมณ์
        self.sentiment_analyzer = pipeline("sentiment-analysis", model=model_name)
    
    def get_name(self):
        return "sentimentAnalysis"
        
    def get_description(self):
        return "Analyzes the sentiment of text, classifying it as positive or negative"
    
    def get_schema(self):
        return {
            "type": "object",
            "properties": {
                "text": {
                    "type": "string", 
                    "description": "The text to analyze for sentiment"
                },
                "includeScore": {
                    "type": "boolean",
                    "description": "Whether to include confidence scores",
                    "default": True
                }
            },
            "required": ["text"]
        }
    
    async def execute_async(self, request: ToolRequest) -> ToolResponse:
        try:
            # ดึงพารามิเตอร์
            text = request.parameters.get("text")
            include_score = request.parameters.get("includeScore", True)
            
            # วิเคราะห์อารมณ์
            sentiment_result = self.sentiment_analyzer(text)[0]
            
            # จัดรูปแบบผลลัพธ์
            result = {
                "sentiment": sentiment_result["label"],
                "text": text
            }
            
            if include_score:
                result["score"] = sentiment_result["score"]
            
            # ส่งคืนผลลัพธ์
            return ToolResponse(result=result)
            
        except Exception as e:
            raise ToolExecutionException(f"Sentiment analysis failed: {str(e)}")

# เพื่อเผยแพร่:
# python setup.py sdist bdist_wheel
# python -m twine upload dist/*

การแบ่งปันแนวทางปฏิบัติที่ดีที่สุด

เมื่อแบ่งปันเครื่องมือ MCP กับชุมชน:

  1. เอกสารสมบูรณ์:

    • อธิบายวัตถุประสงค์ วิธีใช้ และตัวอย่าง
    • อธิบายพารามิเตอร์และค่าที่คืนกลับ
    • บันทึกการพึ่งพาภายนอกใด ๆ
  2. การจัดการข้อผิดพลาด:

    • ใช้งานการจัดการข้อผิดพลาดที่แข็งแกร่ง
    • ให้ข้อความข้อผิดพลาดที่มีประโยชน์
    • จัดการกรณีขอบเขตอย่างเหมาะสม
  3. พิจารณาประสิทธิภาพ:

    • ปรับให้เหมาะสมทั้งความเร็วและการใช้ทรัพยากร
    • ดำเนินการแคชชิ่งเมื่อเหมาะสม
    • คำนึงถึงความสามารถในการปรับขนาด
  4. ความปลอดภัย:

    • ใช้คีย์ API และการพิสูจน์ตัวตนที่ปลอดภัย
    • ตรวจสอบและทำความสะอาดข้อมูลเข้า
    • ดำเนินการจำกัดอัตราสำหรับการเรียก API ภายนอก
  5. การทดสอบ:

    • รวมการครอบคลุมการทดสอบอย่างครบถ้วน
    • ทดสอบกับประเภทข้อมูลเข้าต่าง ๆ และกรณีขอบเขต
    • บันทึกขั้นตอนการทดสอบ

ความร่วมมือและแนวปฏิบัติที่ดีที่สุดในชุมชน

การทำงานร่วมกันอย่างมีประสิทธิภาพคือกุญแจสู่ระบบนิเวศ MCP ที่เติบโต

ช่องทางการสื่อสาร

  • ประเด็นและการสนทนา GitHub
  • ชุมชนเทคโนโลยี Microsoft
  • ช่องทาง Discord และ Slack
  • Stack Overflow (แท็ก: model-context-protocol หรือ mcp)

การตรวจสอบโค้ด

เมื่อรีวิวการมีส่วนร่วมใน MCP:

  1. ความชัดเจน: โค้ดชัดเจนและมีเอกสารประกอบดีหรือไม่?
  2. ความถูกต้อง: ทำงานตามที่คาดหวังหรือไม่?
  3. ความสอดคล้อง: ปฏิบัติตามข้อกำหนดของโปรเจคหรือไม่?
  4. ความครบถ้วน: รวมทั้งการทดสอบและเอกสารหรือไม่?
  5. ความปลอดภัย: มีปัญหาด้านความปลอดภัยหรือไม่?

ความเข้ากันได้ของเวอร์ชัน

เมื่อพัฒนาสำหรับ MCP:

  1. การกำหนดเวอร์ชันโปรโตคอล: ปฏิบัติตามเวอร์ชันโปรโตคอล MCP ที่เครื่องมือรองรับ
  2. ความเข้ากันได้กับลูกค้า: คำนึงถึงความเข้ากันได้ย้อนหลัง
  3. ความเข้ากันได้กับเซิร์ฟเวอร์: ปฏิบัติตามแนวทางการดำเนินการเซิร์ฟเวอร์
  4. การเปลี่ยนแปลงที่ทำให้ระบบแตก: บันทึกการเปลี่ยนแปลงที่ทำลายความเข้ากันได้อย่างชัดเจน

ตัวอย่างโครงการชุมชน: MCP Tool Registry

การมีส่วนร่วมที่สำคัญในชุมชนอาจรวมถึงการพัฒนาทะเบียนเครื่องมือ MCP สาธารณะ

# ตัวอย่างสคีมา API ลงทะเบียนเครื่องมือชุมชน

from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel, Field, HttpUrl
from typing import List, Optional
import datetime
import uuid

# โมเดลสำหรับการลงทะเบียนเครื่องมือ
class ToolSchema(BaseModel):
    """JSON Schema for a tool"""
    type: str
    properties: dict
    required: List[str] = []

class ToolRegistration(BaseModel):
    """Information for registering a tool"""
    name: str = Field(..., description="Unique name for the tool")
    description: str = Field(..., description="Description of what the tool does")
    version: str = Field(..., description="Semantic version of the tool")
    schema: ToolSchema = Field(..., description="JSON Schema for tool parameters")
    author: str = Field(..., description="Author of the tool")
    repository: Optional[HttpUrl] = Field(None, description="Repository URL")
    documentation: Optional[HttpUrl] = Field(None, description="Documentation URL")
    package: Optional[HttpUrl] = Field(None, description="Package URL")
    tags: List[str] = Field(default_factory=list, description="Tags for categorization")
    examples: List[dict] = Field(default_factory=list, description="Example usage")

class Tool(ToolRegistration):
    """Tool with registry metadata"""
    id: uuid.UUID = Field(default_factory=uuid.uuid4)
    created_at: datetime.datetime = Field(default_factory=datetime.datetime.now)
    updated_at: datetime.datetime = Field(default_factory=datetime.datetime.now)
    downloads: int = Field(default=0)
    rating: float = Field(default=0.0)
    ratings_count: int = Field(default=0)

# แอปพลิเคชัน FastAPI สำหรับการลงทะเบียน
app = FastAPI(title="MCP Tool Registry")

# ฐานข้อมูลในหน่วยความจำสำหรับตัวอย่างนี้
tools_db = {}

@app.post("/tools", response_model=Tool)
async def register_tool(tool: ToolRegistration):
    """Register a new tool in the registry"""
    if tool.name in tools_db:
        raise HTTPException(status_code=400, detail=f"Tool '{tool.name}' already exists")
    
    new_tool = Tool(**tool.dict())
    tools_db[tool.name] = new_tool
    return new_tool

@app.get("/tools", response_model=List[Tool])
async def list_tools(tag: Optional[str] = None):
    """List all registered tools, optionally filtered by tag"""
    if tag:
        return [tool for tool in tools_db.values() if tag in tool.tags]
    return list(tools_db.values())

@app.get("/tools/{tool_name}", response_model=Tool)
async def get_tool(tool_name: str):
    """Get information about a specific tool"""
    if tool_name not in tools_db:
        raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
    return tools_db[tool_name]

@app.delete("/tools/{tool_name}")
async def delete_tool(tool_name: str):
    """Delete a tool from the registry"""
    if tool_name not in tools_db:
        raise HTTPException(status_code=404, detail=f"Tool '{tool_name}' not found")
    del tools_db[tool_name]
    return {"message": f"Tool '{tool_name}' deleted"}

สาระสำคัญ

  • ชุมชน MCP มีความหลากหลายและต้อนรับการมีส่วนร่วมในหลายประเภท
  • การมีส่วนร่วมใน MCP อาจครอบคลุมจากการปรับปรุงแกนโปรโตคอลไปจนถึงเครื่องมือที่กำหนดเอง
  • การปฏิบัติตามแนวทางการมีส่วนร่วมช่วยเพิ่มโอกาสในการยอมรับ PR ของคุณ
  • การสร้างและแบ่งปันเครื่องมือ MCP เป็นวิธีที่มีคุณค่าในการพัฒนาระบบนิเวศ
  • ความร่วมมือของชุมชนเป็นสิ่งจำเป็นสำหรับการเติบโตและการปรับปรุง MCP

แบบฝึกหัด

  1. ระบุพื้นที่ในระบบนิเวศ MCP ที่คุณสามารถมีส่วนร่วมได้ตามทักษะและความสนใจของคุณ
  2. Fork ที่เก็บ MCP และตั้งค่าสภาพแวดล้อมการพัฒนาในเครื่อง
  3. สร้างการปรับปรุงเล็ก ๆ การแก้ไขบั๊ก หรือเครื่องมือที่เป็นประโยชน์ต่อชุมชน
  4. เขียนเอกสารการมีส่วนร่วมของคุณพร้อมการทดสอบและเอกสารที่เหมาะสม
  5. ส่งคำขอการดึงโค้ด (pull request) ไปยังที่เก็บข้อมูลที่เหมาะสม

ทรัพยากรเพิ่มเติม


สิ่งถัดไป

ต่อไป: บทเรียนจากการนำไปใช้ในช่วงแรก


ข้อจำกัดความรับผิดชอบ: เอกสารนี้ได้รับการแปลโดยใช้บริการแปลภาษาด้วยปัญญาประดิษฐ์ Co-op Translator แม้เราจะพยายามรักษาความถูกต้อง แต่โปรดทราบว่าการแปลโดยอัตโนมัติอาจมีข้อผิดพลาดหรือความไม่ถูกต้อง เอกสารต้นฉบับในภาษาดั้งเดิมถือเป็นแหล่งข้อมูลที่มีความน่าเชื่อถือที่สุด สำหรับข้อมูลที่สำคัญควรใช้บริการแปลโดยมนุษย์มืออาชีพ เราไม่รับผิดชอบต่อความเข้าใจผิดหรือการตีความที่ผิดพลาดที่เกิดขึ้นจากการใช้การแปลนี้