AI
MCP
Protocol
Claude
Integration
Advanced

MCP คืออะไร? Model Context Protocol อธิบายง่ายๆ

เรียนรู้ MCP (Model Context Protocol) มาตรฐานใหม่สำหรับเชื่อมต่อ AI กับ tools และ data sources พร้อมตัวอย่างการใช้งานกับ Claude และ applications อื่นๆ

AI Unlocked Team
01/02/2568
MCP คืออะไร? Model Context Protocol อธิบายง่ายๆ

MCP คืออะไร? Model Context Protocol อธิบายง่ายๆ

MCP (Model Context Protocol) เป็นมาตรฐานเปิด (open standard) ที่พัฒนาโดย Anthropic สำหรับเชื่อมต่อ AI models กับ tools และ data sources ต่างๆ บทความนี้จะอธิบายว่า MCP คืออะไร ทำไมจึงสำคัญ และวิธีเริ่มต้นใช้งาน

MCP คืออะไร?

Model Context Protocol (MCP) เป็น protocol มาตรฐานที่กำหนดวิธีการสื่อสารระหว่าง AI applications (clients) กับ external systems (servers) ทำให้ AI สามารถเข้าถึงข้อมูลและทำงานกับเครื่องมือต่างๆ ได้อย่างปลอดภัยและเป็นระบบ

แนวคิดหลัก

ก่อน MCP:
┌──────────┐     ┌──────────────────────────────────┐
│   AI     │────▶│ Custom Integration 1 (GitHub)    │
│ Claude   │────▶│ Custom Integration 2 (Slack)     │
│          │────▶│ Custom Integration 3 (Database)  │
│          │────▶│ Custom Integration 4 (...)       │
└──────────┘     └──────────────────────────────────┘
❌ ทุก integration ต้องเขียนใหม่ทุกครั้ง

หลัง MCP:
┌──────────┐     ┌──────────┐     ┌────────────────┐
│   AI     │────▶│   MCP    │────▶│ GitHub Server  │
│ Claude   │     │ Protocol │────▶│ Slack Server   │
│          │     │          │────▶│ DB Server      │
└──────────┘     └──────────┘     └────────────────┘
✅ มาตรฐานเดียว ใช้ได้กับทุก server

MCP Architecture

┌─────────────────────────────────────────────────────────────────┐
│                    MCP Architecture                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌──────────────────────────────────────────────────────────┐  │
│  │                     MCP Host                              │  │
│  │  (Claude Desktop, IDE, Custom App)                       │  │
│  └───────────────────────────┬──────────────────────────────┘  │
│                              │                                  │
│                    ┌─────────┴─────────┐                       │
│                    │   MCP Protocol    │                       │
│                    │   (JSON-RPC)      │                       │
│                    └─────────┬─────────┘                       │
│                              │                                  │
│          ┌───────────────────┼───────────────────┐             │
│          │                   │                   │             │
│          ▼                   ▼                   ▼             │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────┐       │
│  │ MCP Server 1 │   │ MCP Server 2 │   │ MCP Server 3 │       │
│  │ (Files)      │   │ (Database)   │   │ (GitHub)     │       │
│  └──────────────┘   └──────────────┘   └──────────────┘       │
│          │                   │                   │             │
│          ▼                   ▼                   ▼             │
│  ┌──────────────┐   ┌──────────────┐   ┌──────────────┐       │
│  │ Local Files  │   │ PostgreSQL   │   │ GitHub API   │       │
│  └──────────────┘   └──────────────┘   └──────────────┘       │
└─────────────────────────────────────────────────────────────────┘

Components ของ MCP

1. MCP Host

Application ที่ต้องการใช้ AI capabilities เช่น Claude Desktop, VS Code, หรือ custom applications

2. MCP Client

Component ที่จัดการการเชื่อมต่อกับ MCP servers

3. MCP Server

Service ที่ให้บริการ tools, resources, หรือ prompts ผ่าน MCP protocol

4. Capabilities

MCP servers สามารถให้บริการ:

Resources (ข้อมูล)

{
  "resources": [
    {
      "uri": "file:///path/to/document.md",
      "name": "Project README",
      "mimeType": "text/markdown"
    }
  ]
}

Tools (เครื่องมือ)

{
  "tools": [
    {
      "name": "search_files",
      "description": "Search for files in the project",
      "inputSchema": {
        "type": "object",
        "properties": {
          "query": { "type": "string" }
        },
        "required": ["query"]
      }
    }
  ]
}

Prompts (templates)

{
  "prompts": [
    {
      "name": "code_review",
      "description": "Review code for best practices",
      "arguments": [
        {
          "name": "code",
          "description": "The code to review",
          "required": true
        }
      ]
    }
  ]
}

การใช้งาน MCP กับ Claude Desktop

ติดตั้ง MCP Server

  1. สร้างไฟล์ config ที่ ~/Library/Application Support/Claude/claude_desktop_config.json (Mac) หรือ %APPDATA%/Claude/claude_desktop_config.json (Windows)
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/path/to/allowed/directory"
      ]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "your-token"
      }
    }
  }
}
  1. Restart Claude Desktop

  2. ใช้งานได้เลย! Claude จะสามารถเข้าถึง files และ GitHub ได้

ตัวอย่างการใช้งาน

User: "ช่วยดู README.md ในโปรเจค และสรุปให้หน่อย"

Claude: [ใช้ MCP filesystem server อ่านไฟล์]
"จากการอ่าน README.md พบว่าโปรเจคนี้เป็น..."

User: "สร้าง issue บน GitHub สำหรับ bug ที่พบ"

Claude: [ใช้ MCP GitHub server สร้าง issue]
"สร้าง issue เรียบร้อยแล้ว: https://github.com/..."

สร้าง MCP Server เอง

Basic MCP Server (Python)

# my_mcp_server.py
import asyncio
import json
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import (
    Tool, TextContent, Resource, Prompt, PromptMessage
)

# Create server instance
server = Server("my-server")

# Define resources
@server.list_resources()
async def list_resources():
    return [
        Resource(
            uri="data://users",
            name="User Database",
            description="Access to user information",
            mimeType="application/json"
        )
    ]

@server.read_resource()
async def read_resource(uri: str):
    if uri == "data://users":
        users = await get_users_from_database()
        return json.dumps(users)
    raise ValueError(f"Unknown resource: {uri}")

# Define tools
@server.list_tools()
async def list_tools():
    return [
        Tool(
            name="search_users",
            description="Search for users by name or email",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query"
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Max results",
                        "default": 10
                    }
                },
                "required": ["query"]
            }
        ),
        Tool(
            name="create_user",
            description="Create a new user",
            inputSchema={
                "type": "object",
                "properties": {
                    "name": {"type": "string"},
                    "email": {"type": "string"}
                },
                "required": ["name", "email"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "search_users":
        results = await search_users(
            arguments["query"],
            arguments.get("limit", 10)
        )
        return [TextContent(type="text", text=json.dumps(results))]

    elif name == "create_user":
        user = await create_user(
            arguments["name"],
            arguments["email"]
        )
        return [TextContent(type="text", text=f"Created user: {user['id']}")]

    raise ValueError(f"Unknown tool: {name}")

# Define prompts
@server.list_prompts()
async def list_prompts():
    return [
        Prompt(
            name="user_report",
            description="Generate a user activity report",
            arguments=[
                {
                    "name": "user_id",
                    "description": "User ID to report on",
                    "required": True
                },
                {
                    "name": "period",
                    "description": "Report period (day/week/month)",
                    "required": False
                }
            ]
        )
    ]

@server.get_prompt()
async def get_prompt(name: str, arguments: dict):
    if name == "user_report":
        user_id = arguments["user_id"]
        period = arguments.get("period", "week")

        user_data = await get_user_data(user_id, period)

        return [
            PromptMessage(
                role="user",
                content=TextContent(
                    type="text",
                    text=f"""Generate a detailed activity report for user {user_id}.

Period: {period}
Data: {json.dumps(user_data)}

Include:
1. Summary of activities
2. Key metrics
3. Trends and patterns
4. Recommendations"""
                )
            )
        ]

    raise ValueError(f"Unknown prompt: {name}")

# Helper functions (implement based on your needs)
async def get_users_from_database():
    # Your database logic
    return [{"id": 1, "name": "John"}]

async def search_users(query: str, limit: int):
    # Your search logic
    return []

async def create_user(name: str, email: str):
    # Your create logic
    return {"id": 123, "name": name, "email": email}

async def get_user_data(user_id: str, period: str):
    # Your data retrieval logic
    return {}

# Run server
async def main():
    async with stdio_server() as (read_stream, write_stream):
        await server.run(read_stream, write_stream)

if __name__ == "__main__":
    asyncio.run(main())

MCP Server (TypeScript)

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

const server = new Server(
  {
    name: "my-server",
    version: "1.0.0",
  },
  {
    capabilities: {
      resources: {},
      tools: {},
    },
  }
);

// List resources
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
  resources: [
    {
      uri: "config://app",
      name: "App Configuration",
      mimeType: "application/json",
    },
  ],
}));

// Read resource
server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
  if (request.params.uri === "config://app") {
    const config = await getAppConfig();
    return {
      contents: [
        {
          uri: request.params.uri,
          mimeType: "application/json",
          text: JSON.stringify(config),
        },
      ],
    };
  }
  throw new Error(`Unknown resource: ${request.params.uri}`);
});

// List tools
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "deploy",
      description: "Deploy the application",
      inputSchema: {
        type: "object",
        properties: {
          environment: {
            type: "string",
            enum: ["staging", "production"],
          },
          version: {
            type: "string",
          },
        },
        required: ["environment"],
      },
    },
  ],
}));

// Call tool
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "deploy") {
    const { environment, version } = request.params.arguments as {
      environment: string;
      version?: string;
    };

    const result = await deployApp(environment, version);

    return {
      content: [
        {
          type: "text",
          text: `Deployed to ${environment}: ${result.url}`,
        },
      ],
    };
  }
  throw new Error(`Unknown tool: ${request.params.name}`);
});

// Helper functions
async function getAppConfig() {
  return { version: "1.0.0", env: "development" };
}

async function deployApp(env: string, version?: string) {
  return { url: `https://${env}.example.com` };
}

// Start server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
}

main();

MCP Servers ที่มีให้ใช้

Official Servers

ServerDescriptionUse Case
@modelcontextprotocol/server-filesystemFile system accessอ่าน/เขียนไฟล์
@modelcontextprotocol/server-githubGitHub integrationจัดการ repos, issues
@modelcontextprotocol/server-gitlabGitLab integrationจัดการ GitLab
@modelcontextprotocol/server-slackSlack integrationส่งข้อความ, อ่านช่อง
@modelcontextprotocol/server-postgresPostgreSQLQuery database
@modelcontextprotocol/server-sqliteSQLiteLocal database
@modelcontextprotocol/server-memoryKnowledge graphเก็บความรู้
@modelcontextprotocol/server-puppeteerWeb automationScrape, automate
@modelcontextprotocol/server-brave-searchWeb searchSearch the web
@modelcontextprotocol/server-google-mapsGoogle MapsLocation data

Community Servers

  • server-notion: Notion integration
  • server-linear: Linear project management
  • server-obsidian: Obsidian vault access
  • server-docker: Docker management

Best Practices

1. Security

# Always validate input
@server.call_tool()
async def call_tool(name: str, arguments: dict):
    # Validate arguments
    if name == "execute_query":
        query = arguments.get("query", "")

        # Prevent SQL injection
        if any(keyword in query.upper() for keyword in ["DROP", "DELETE", "TRUNCATE"]):
            raise ValueError("Dangerous query not allowed")

        # Use parameterized queries
        return await execute_safe_query(query)

2. Error Handling

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    try:
        result = await execute_tool(name, arguments)
        return [TextContent(type="text", text=json.dumps(result))]
    except PermissionError:
        return [TextContent(type="text", text="Error: Permission denied")]
    except Exception as e:
        logger.error(f"Tool error: {e}")
        return [TextContent(type="text", text=f"Error: {str(e)}")]

3. Rate Limiting

from functools import wraps
import time

def rate_limit(calls_per_minute=60):
    min_interval = 60.0 / calls_per_minute
    last_called = {}

    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            key = func.__name__
            now = time.time()

            if key in last_called:
                elapsed = now - last_called[key]
                if elapsed < min_interval:
                    await asyncio.sleep(min_interval - elapsed)

            last_called[key] = time.time()
            return await func(*args, **kwargs)
        return wrapper
    return decorator

@server.call_tool()
@rate_limit(calls_per_minute=30)
async def call_tool(name: str, arguments: dict):
    # Tool implementation
    pass

4. Logging

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("mcp-server")

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    logger.info(f"Tool called: {name}")
    logger.debug(f"Arguments: {arguments}")

    try:
        result = await execute_tool(name, arguments)
        logger.info(f"Tool {name} completed successfully")
        return result
    except Exception as e:
        logger.error(f"Tool {name} failed: {e}")
        raise

Use Cases

1. Development Workflow

{
  "mcpServers": {
    "git": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-git"]
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "your-token"
      }
    }
  }
}

2. Data Analysis

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "postgresql://..."
      }
    },
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "./data"]
    }
  }
}

3. Customer Support

{
  "mcpServers": {
    "slack": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-slack"],
      "env": {
        "SLACK_TOKEN": "your-token"
      }
    },
    "knowledge-base": {
      "command": "python",
      "args": ["./kb_server.py"]
    }
  }
}

สรุป

MCP เป็นมาตรฐานที่จะเปลี่ยนวิธีที่เราสร้าง AI applications ทำให้การเชื่อมต่อ AI กับระบบต่างๆ ง่ายขึ้นและเป็นมาตรฐานเดียวกัน


อ่านบทความที่เกี่ยวข้อง


พร้อมเริ่มใช้ MCP แล้วหรือยัง?

ติดต่อทีม AI Unlocked สำหรับคำปรึกษาและการพัฒนา AI solutions ที่ใช้ MCP


เขียนโดย

AI Unlocked Team