กลับไปหน้าคู่มือ
ขั้นสูงสำหรับนักพัฒนา

สร้าง MCP Server สำหรับ OpenClaw

คู่มือสร้าง MCP Server ที่ช่วยให้ OpenClaw เชื่อมต่อกับบริการภายนอกได้

20 นาที
2026-03-18

สร้าง MCP Server สำหรับ OpenClaw

MCP (Model Context Protocol) ช่วยให้ OpenClaw เชื่อมต่อกับบริการภายนอกได้

MCP คืออะไร?

MCP เป็นโปรโตคอลมาตรฐานที่ช่วยให้ AI models สามารถเรียกใช้ tools ภายนอกได้ เช่น API, Database, CLI tools

เลือกภาษาที่จะใช้

**Python (FastMCP):**

pip install fastmcp

**TypeScript (MCP SDK):**

npm install @modelcontextprotocol/sdk

ตัวอย่าง: สร้าง MCP Server ด้วย Python

from fastmcp import FastMCP

mcp = FastMCP("my-server")

@mcp.tool() def get_weather(city: str) -> str: """ดึงข้อมูลสภาพอากาศของเมืองที่ระบุ""" # เรียก weather API return f"อากาศที่ {city}: 32°C แดดจัด"

@mcp.tool() def translate_text(text: str, target_lang: str) -> str: """แปลข้อความเป็นภาษาที่ระบุ""" # เรียก translation API return f"แปลแล้ว: {text}"

if __name__ == "__main__": mcp.run()

ตัวอย่าง: สร้าง MCP Server ด้วย TypeScript

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";

const server = new McpServer({ name: "my-server", version: "1.0.0" });

server.tool("get_weather", { city: "string" }, async ({ city }) => { return { content: [{ type: "text", text: อากาศที่ ${city}: 32°C }] }; });

server.run();

คอนฟิก OpenClaw ให้ใช้ MCP Server

เพิ่มใน .openclaw/config.json:

{
  "mcpServers": {
    "my-server": {
      "command": "python",
      "args": ["my_server.py"]
    }
  }
}

ทดสอบ MCP Server

# ทดสอบด้วย MCP Inspector
npx @modelcontextprotocol/inspector my_server.py

# ทดสอบผ่าน OpenClaw openclaw "ดูสภาพอากาศที่กรุงเทพ"

Best Practices

- ใส่ description ที่ชัดเจนให้ทุก tool

  • จัดการ error อย่างเหมาะสม
  • ใช้ type hints เพื่อให้ AI เข้าใจ parameters
  • ทดสอบด้วย MCP Inspector ก่อน deploy