สร้าง MCP Server เสริมพลัง AI ทดสอบ API

Ashley Innocent

Ashley Innocent

19 March 2026

สร้าง MCP Server เสริมพลัง AI ทดสอบ API

Apidog สำหรับองค์กร

ติดตั้งภายในองค์กร

SSO & RBAC

รองรับ SOC 2

สำรวจ Apidog Enterprise

สรุปใจความสำคัญ

สร้างเซิร์ฟเวอร์ MCP ด้วย TypeScript ที่เปิดเผยเครื่องมือสามอย่าง: run_test, validate_schema, และ list_environments กำหนดค่าใน ~/.claude/settings.json สำหรับ Claude Code หรือ .cursor/mcp.json สำหรับ Cursor จากนั้นเอเจนต์ AI ของคุณจะสามารถรันการทดสอบ Apidog, ตรวจสอบความถูกต้องของสคีมา OpenAPI และดึงข้อมูลสภาพแวดล้อมได้โดยไม่ต้องออกจากอินเทอร์เฟซการแชท ซอร์สโค้ดทั้งหมดมีประมาณ 150 บรรทัด และใช้แพ็คเกจ @modelcontextprotocol/sdk

สร้างเซิร์ฟเวอร์ MCP ที่ช่วยให้ Claude Code, Cursor, และเอเจนต์ AI อื่นๆ สามารถรันการทดสอบ Apidog API, ตรวจสอบความถูกต้องของสคีมา และเปรียบเทียบการตอบสนองได้ โดยไม่ต้องออกจากอินเทอร์เฟซการแชท

💡
คุณกำลังอยู่ในช่วงของการเขียนโค้ด เอเจนต์ AI ของคุณเพิ่งสร้างเอนด์พอยต์ API เสร็จ แทนที่จะคัดลอกโค้ด, เปิด Apidog, สร้างคอลเลกชันการทดสอบ, และรันการตรวจสอบด้วยตนเอง คุณต้องการพิมพ์คำสั่งเดียวและได้ผลลัพธ์กลับมา
ปุ่ม

นี่คือสิ่งที่ Model Context Protocol (MCP) ทำให้เป็นไปได้ MCP ช่วยให้เอเจนต์ AI สามารถเข้าถึงเครื่องมือภายนอกผ่านอินเทอร์เฟซที่เป็นมาตรฐาน สร้างเซิร์ฟเวอร์ MCP สำหรับ Apidog แล้วเอเจนต์ AI ของคุณจะสามารถรันการทดสอบ, ตรวจสอบความถูกต้องของสคีมา, และดึงข้อมูลสภาพแวดล้อมได้โดยไม่ต้องเปลี่ยนบริบท

MCP คืออะไร?

MCP (Model Context Protocol) คือโปรโตคอลสำหรับเอเจนต์ AI ในการเข้าถึงเครื่องมือและแหล่งข้อมูลภายนอก คิดว่ามันเป็นระบบปลั๊กอินที่ทำงานได้ทั่วทั้ง Claude Code, Cursor และไคลเอนต์อื่นๆ ที่เข้ากันได้กับ MCP

เซิร์ฟเวอร์ MCP จะเปิดเผย เครื่องมือ (ฟังก์ชันที่เอเจนต์สามารถเรียกใช้ได้) และ ทรัพยากร (ข้อมูลที่เอเจนต์สามารถอ่านได้) เซิร์ฟเวอร์ MCP ของ Apidog ของคุณจะเปิดเผยเครื่องมือสำหรับการทดสอบ API

┌─────────────────┐         ┌──────────────────┐         ┌─────────────┐
│  AI Agent       │         │  MCP Server      │         │  Apidog     │
│  (Claude Code)  │◄───────►│  (Your Code)     │◄───────►│  API        │
└─────────────────┘   JSON  └──────────────────┘  HTTP   └─────────────┘

ขั้นตอนที่ 1: ตั้งค่าโปรเจกต์

สร้างโปรเจกต์ TypeScript ใหม่:

mkdir apidog-mcp-server
cd apidog-mcp-server
npm init -y
npm install @modelcontextprotocol/sdk zod
npm install -D typescript @types/node

สร้าง tsconfig.json:

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

เพิ่มสคริปต์ build ลงใน package.json:

{
  "scripts": {
    "build": "tsc",
    "start": "node dist/index.js"
  }
}

ขั้นตอนที่ 2: สร้างโครงเซิร์ฟเวอร์ MCP

สร้าง src/index.ts:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "apidog",
  version: "1.0.0",
  description: "Apidog API testing tools for AI agents"
});

// Tools will be defined here

const transport = new StdioServerTransport();
await server.connect(transport);

โครงนี้สร้างเซิร์ฟเวอร์ MCP และเชื่อมต่อเข้ากับ stdio transport โดย transport นี้จะจัดการการสื่อสารระหว่างเอเจนต์ AI และเซิร์ฟเวอร์ของคุณผ่าน standard input/output

ขั้นตอนที่ 3: กำหนดเครื่องมือ run_test

เพิ่มเครื่องมือแรกใน src/index.ts:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "apidog",
  version: "1.0.0",
  description: "Apidog API testing tools for AI agents"
});

// Tool: run_test
server.tool(
  "run_test",
  {
    projectId: z.string().describe("Apidog project ID (found in project URL)"),
    environmentId: z.string().optional().describe("Optional environment ID for test execution"),
    testSuiteId: z.string().optional().describe("Optional test suite ID to run specific suite")
  },
  async ({ projectId, environmentId, testSuiteId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY environment variable not set"
        }]
      };
    }

    // Build API URL
    let url = `https://api.apidog.com/v1/projects/${projectId}/tests/run`;
    const params = new URLSearchParams();
    if (environmentId) params.append("environmentId", environmentId);
    if (testSuiteId) params.append("testSuiteId", testSuiteId);
    if (params.toString()) url += `?${params.toString()}`;

    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${apiKey}`,
          "Content-Type": "application/json"
        }
      });

      if (!response.ok) {
        const error = await response.text();
        return {
          content: [{
            type: "text",
            text: `API Error: ${response.status} ${error}`
          }]
        };
      }

      const results = await response.json();
      return {
        content: [{
          type: "text",
          text: JSON.stringify(results, null, 2)
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `Request failed: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);

คำจำกัดความของเครื่องมือประกอบด้วยสามส่วน:

  1. ชื่อrun_test (เอเจนต์จะเลือกเครื่องมือตามชื่อ ดังนั้นควรตั้งชื่อให้สื่อความหมาย)
  2. สคีมา — การตรวจสอบความถูกต้องของ Zod สำหรับพารามิเตอร์พร้อมคำอธิบาย
  3. แฮนเดลอร์ — ฟังก์ชันอะซิงโครนัสที่เรียก Apidog API

ขั้นตอนที่ 4: เพิ่มเครื่องมือ validate_schema

เพิ่มการตรวจสอบความถูกต้องของสคีมาเพื่อตรวจจับข้อผิดพลาดของ OpenAPI ก่อนการใช้งาน:

// Tool: validate_schema
server.tool(
  "validate_schema",
  {
    schema: z.object({}).describe("OpenAPI 3.x schema object to validate"),
    strict: z.boolean().optional().default(false).describe("Enable strict mode for additional checks")
  },
  async ({ schema, strict }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY environment variable not set"
        }]
      };
    }

    try {
      const response = await fetch("https://api.apidog.com/v1/schemas/validate", {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${apiKey}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ schema, strict })
      });

      const result = await response.json();

      if (!response.ok) {
        return {
          content: [{
            type: "text",
            text: `Validation failed: ${JSON.stringify(result.errors, null, 2)}`
          }]
        };
      }

      return {
        content: [{
          type: "text",
          text: result.valid
            ? "Schema is valid OpenAPI 3.x"
            : `Warnings: ${JSON.stringify(result.warnings, null, 2)}`
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `Validation failed: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);

ขั้นตอนที่ 5: เพิ่มเครื่องมือ list_environments

เพิ่มเครื่องมือเพื่อดึงข้อมูลสภาพแวดล้อมการทดสอบที่มีอยู่:

// Tool: list_environments
server.tool(
  "list_environments",
  {
    projectId: z.string().describe("Apidog project ID")
  },
  async ({ projectId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY environment variable not set"
        }]
      };
    }

    try {
      const response = await fetch(
        `https://api.apidog.com/v1/projects/${projectId}/environments`,
        {
          headers: {
            "Authorization": `Bearer ${apiKey}`
          }
        }
      );

      if (!response.ok) {
        const error = await response.text();
        return {
          content: [{
            type: "text",
            text: `API Error: ${response.status} ${error}`
          }]
        };
      }

      const environments = await response.json();
      return {
        content: [{
          type: "text",
          text: environments.length === 0
            ? "No environments found for this project"
            : environments.map((e: any) =>
                `- ${e.name} (ID: ${e.id})${e.isDefault ? " [default]" : ""}`
              ).join("\n")
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `Request failed: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);

ขั้นตอนที่ 6: Build และ Test

Build เซิร์ฟเวอร์:

npm run build

ทดสอบด้วยไคลเอนต์ MCP ง่ายๆ สร้าง test-client.js:

import { spawn } from "child_process";

const server = spawn("node", ["dist/index.js"], {
  env: { ...process.env, APIDOG_API_KEY: "your-api-key" }
});

server.stdout.on("data", (data) => {
  console.log(`Server output: ${data}`);
});

server.stderr.on("data", (data) => {
  console.error(`Server error: ${data}`);
});

// Send a test message
const message = {
  jsonrpc: "2.0",
  id: 1,
  method: "initialize",
  params: {
    protocolVersion: "2024-11-05",
    capabilities: {},
    clientInfo: { name: "test-client", version: "1.0.0" }
  }
};

server.stdin.write(JSON.stringify(message) + "\n");

ขั้นตอนที่ 7: ตั้งค่าสำหรับ Claude Code

เพิ่มเซิร์ฟเวอร์ MCP ลงในการตั้งค่า Claude Code ของคุณ:

สร้างหรือแก้ไข ~/.claude/settings.json:

{
  "mcpServers": {
    "apidog": {
      "command": "node",
      "args": ["/absolute/path/to/apidog-mcp-server/dist/index.js"],
      "env": {
        "APIDOG_API_KEY": "your-api-key-here"
      }
    }
  }
}

รีสตาร์ท Claude Code เครื่องมือ Apidog ควรปรากฏขึ้นเมื่อคุณขอความช่วยเหลือเกี่ยวกับการทดสอบ API

การใช้งานใน Claude Code:

ใช้เครื่องมือ run_test เพื่อรันการทดสอบในโปรเจกต์ Apidog ของฉัน
Project ID: proj_12345
Environment: staging
ตรวจสอบความถูกต้องของสคีมา OpenAPI นี้ตามกฎของ Apidog:
[วางสคีมา]
แสดงสภาพแวดล้อมทั้งหมดสำหรับโปรเจกต์ proj_12345

ขั้นตอนที่ 8: ตั้งค่าสำหรับ Cursor

Cursor ใช้การกำหนดค่า MCP ที่คล้ายกัน สร้างไฟล์ .cursor/mcp.json ในโปรเจกต์ของคุณ:

{
  "mcpServers": {
    "apidog": {
      "command": "node",
      "args": ["/absolute/path/to/apidog-mcp-server/dist/index.js"],
      "env": {
        "APIDOG_API_KEY": "your-api-key-here"
      }
    }
  }
}

การใช้งานใน Cursor:

@apidog run_test projectId="proj_12345" environmentId="staging"

ซอร์สโค้ดฉบับสมบูรณ์

นี่คือไฟล์ src/index.ts ฉบับสมบูรณ์:

import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "apidog",
  version: "1.0.0",
  description: "Apidog API testing tools for AI agents"
});

// Tool: run_test
server.tool(
  "run_test",
  {
    projectId: z.string().describe("Apidog project ID"),
    environmentId: z.string().optional().describe("Environment ID"),
    testSuiteId: z.string().optional().describe("Test suite ID")
  },
  async ({ projectId, environmentId, testSuiteId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY not set"
        }]
      };
    }

    let url = `https://api.apidog.com/v1/projects/${projectId}/tests/run`;
    const params = new URLSearchParams();
    if (environmentId) params.append("environmentId", environmentId);
    if (testSuiteId) params.append("testSuiteId", testSuiteId);
    if (params.toString()) url += `?${params.toString()}`;

    try {
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${apiKey}`,
          "Content-Type": "application/json"
        }
      });

      const results = await response.json();
      return {
        content: [{
          type: "text",
          text: JSON.stringify(results, null, 2)
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `Request failed: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);

// Tool: validate_schema
server.tool(
  "validate_schema",
  {
    schema: z.object({}).describe("OpenAPI schema"),
    strict: z.boolean().optional().default(false)
  },
  async ({ schema, strict }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY not set"
        }]
      };
    }

    const response = await fetch("https://api.apidog.com/v1/schemas/validate", {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ schema, strict })
    });

    const result = await response.json();
    return {
      content: [{
        type: "text",
        text: result.valid
          ? "Schema is valid"
          : `Issues: ${JSON.stringify(result.errors || result.warnings, null, 2)}`
      }]
    };
  }
);

// Tool: list_environments
server.tool(
  "list_environments",
  {
    projectId: z.string().describe("Apidog project ID")
  },
  async ({ projectId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "Error: APIDOG_API_KEY not set"
        }]
      };
    }

    const response = await fetch(
      `https://api.apidog.com/v1/projects/${projectId}/environments`,
      {
        headers: { "Authorization": `Bearer ${apiKey}` }
      }
    );

    const environments = await response.json();
    return {
      content: [{
        type: "text",
        text: environments.map((e: any) =>
          `- ${e.name} (${e.id})${e.isDefault ? " [default]" : ""}`
        ).join("\n")
      }]
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);

สิ่งที่คุณสร้างขึ้น

ส่วนประกอบ วัตถุประสงค์
เซิร์ฟเวอร์ MCP เชื่อมต่อเอเจนต์ AI เข้ากับ Apidog API
run_test รันคอลเลกชันการทดสอบด้วยโปรแกรม
validate_schema ตรวจจับข้อผิดพลาดของ OpenAPI ก่อนการใช้งาน
list_environments ค้นหาสภาพแวดล้อมการทดสอบที่มีอยู่
การตรวจสอบความถูกต้องด้วย Zod การจัดการพารามิเตอร์ที่ปลอดภัยต่อชนิดข้อมูล
Stdio transport ใช้งานได้กับ Claude Code, Cursor, และไคลเอนต์ MCP อื่นๆ

ขั้นตอนต่อไป

ขยายเซิร์ฟเวอร์:

ข้อควรพิจารณาในการใช้งานจริง:

แชร์กับทีมของคุณ:

การแก้ไขปัญหาทั่วไป

เซิร์ฟเวอร์ MCP ไม่โหลดใน Claude Code:

เครื่องมือไม่ปรากฏหลังจากการกำหนดค่า:

คำขอ API ล้มเหลวด้วยรหัส 401:

ข้อผิดพลาดในการตรวจสอบความถูกต้องของ Zod:

ข้อผิดพลาดในการคอมไพล์ TypeScript:

การทดสอบเซิร์ฟเวอร์ MCP ของคุณในเครื่อง

ก่อนที่จะนำไปใช้จริง ให้ทดสอบเซิร์ฟเวอร์ของคุณในเครื่อง:

การทดสอบด้วยตนเองด้วย stdio:

# เริ่มเซิร์ฟเวอร์
node dist/index.js

# ในเทอร์มินัลอื่น ส่งข้อความทดสอบ
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | node dist/index.js

ผลลัพธ์ที่คาดหวัง:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "tools": [
      { "name": "run_test", "description": "...", "inputSchema": {...} },
      { "name": "validate_schema", "description": "...", "inputSchema": {...} },
      { "name": "list_environments", "description": "...", "inputSchema": {...} }
    ]
  }
}

ทดสอบการเรียกใช้เครื่องมือ:

echo '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_environments","arguments":{"projectId":"your-project-id"}}}' | node dist/index.js

ตอนนี้เอเจนต์ AI ของคุณสามารถเข้าถึงความสามารถในการทดสอบของ Apidog ได้โดยตรงแล้ว ไม่ต้องคัดลอกและวางระหว่างแชทกับเบราว์เซอร์อีกต่อไป ไม่ต้องรันการทดสอบด้วยตนเองอีกต่อไป เพียงพิมพ์คำสั่ง คุณก็จะได้ผลลัพธ์กลับมา

นั่นคือพลังของ MCP: ขยายขีดความสามารถของเอเจนต์ AI ของคุณด้วยเครื่องมือเฉพาะทาง และปล่อยให้พวกมันทำงานตามที่ควรจะเป็น — ช่วยให้คุณส่งมอบงานได้เร็วขึ้น

ประเด็นสำคัญ

ปุ่ม

คำถามที่พบบ่อย

MCP ใน AI คืออะไร?MCP (Model Context Protocol) คือโปรโตคอลมาตรฐานที่ช่วยให้เอเจนต์ AI สามารถเข้าถึงเครื่องมือและแหล่งข้อมูลภายนอกได้ ลองนึกภาพว่าเป็นระบบปลั๊กอินสำหรับเอเจนต์ AI

ฉันจะสร้างเซิร์ฟเวอร์ MCP สำหรับ Apidog ได้อย่างไร?ติดตั้ง @modelcontextprotocol/sdk, กำหนดเครื่องมือด้วย Zod validation, ใช้ handlers ที่เรียก Apidog API, และเชื่อมต่อผ่าน StdioServerTransport

ฉันสามารถใช้สิ่งนี้กับ Cursor ได้หรือไม่?ได้ เพิ่มการกำหนดค่าเซิร์ฟเวอร์ MCP ลงใน .cursor/mcp.json ใน root ของโปรเจกต์คุณ เซิร์ฟเวอร์เดียวกันนี้ใช้งานได้กับ Claude Code, Cursor และไคลเอนต์ MCP อื่นๆ

ฉันควรเปิดเผยเครื่องมืออะไรบ้าง?เริ่มต้นด้วย run_test สำหรับการรันคอลเลกชันการทดสอบ, validate_schema สำหรับการตรวจสอบความถูกต้องของ OpenAPI, และ list_environments สำหรับการดึงข้อมูลสภาพแวดล้อมที่มีอยู่

เซิร์ฟเวอร์ Apidog MCP พร้อมใช้งานจริงแล้วหรือยัง?โค้ดในบทช่วยสอนนี้เป็นจุดเริ่มต้น คุณควรเพิ่มตรรกะการลองใหม่ (retry logic), การจำกัดอัตรา (rate limiting), การจัดการข้อผิดพลาดที่เหมาะสม, และการจัดเก็บคีย์ API ที่ปลอดภัยก่อนนำไปใช้งานจริง

ฉันจำเป็นต้องมี Apidog API key หรือไม่?ใช่ ตั้งค่า APIDOG_API_KEY เป็นตัวแปรสภาพแวดล้อม เซิร์ฟเวอร์จะอ่านค่านี้เมื่อรันเพื่อตรวจสอบสิทธิ์คำขอ API

ฉันสามารถแชร์เซิร์ฟเวอร์ MCP นี้กับทีมของฉันได้หรือไม่?ได้ เผยแพร่ไปยัง npm เป็นแพ็คเกจส่วนตัว, จัดทำเอกสารตัวแปรสภาพแวดล้อมที่จำเป็น, และรวมตัวอย่างการกำหนดค่า MCP ไว้ด้วย

ฝึกการออกแบบ API แบบ Design-first ใน Apidog

ค้นพบวิธีที่ง่ายขึ้นในการสร้างและใช้ API

สร้าง MCP Server เสริมพลัง AI ทดสอบ API