DEV Community

Cover image for كيفية بناء خادم MCP يمنح وكلاء الذكاء الاصطناعي قدرات اختبار API
Yusuf Khalidd
Yusuf Khalidd

Posted on • Originally published at apidog.com

كيفية بناء خادم MCP يمنح وكلاء الذكاء الاصطناعي قدرات اختبار API

الخلاصة

ابنِ خادم MCP باستخدام TypeScript لعرض ثلاث أدوات: run_test، و validate_schema، و list_environments. قم بتكوينه في ~/.claude/settings.json لـ Claude Code أو .cursor/mcp.json لـ Cursor. الآن يمكن لوكلاء الذكاء الاصطناعي لديك تنفيذ اختبارات Apidog، والتحقق من صحة مخططات OpenAPI، وجلب البيئات دون مغادرة واجهة الدردشة. الكود المصدري الكامل حوالي 150 سطرًا ويعتمد على حزمة @modelcontextprotocol/sdk.

جرّب Apidog اليوم

ابنِ خادم MCP يتيح لـ Claude Code وCursor والوكلاء الآخرين تشغيل اختبارات Apidog API، والتحقق من صحة المخططات، ومقارنة الاستجابات مباشرة من واجهة الدردشة.

💡أنت في منتصف جلسة برمجة. وكيل الذكاء الاصطناعي الخاص بك أنشأ نقطة نهاية API جديدة. بدلًا من نسخ الكود وفتح Apidog يدويًا، يمكنك الآن كتابة أمر واحد والحصول على النتائج فورًا.

هذه هي قوة بروتوكول سياق النموذج (MCP). MCP يتيح للوكلاء الوصول إلى أدوات خارجية عبر واجهة موحدة. ابنِ خادم MCP مخصص لـ Apidog، وسيتمكن وكيل الذكاء الاصطناعي الخاص بك من تنفيذ الاختبارات والتحقق من صحة المخططات وجلب البيئات بدون مغادرة السياق.

ما هو بروتوكول سياق النموذج (MCP)؟

MCP (Model Context Protocol) هو معيار يتيح لوكلاء الذكاء الاصطناعي التفاعل مع أدوات وبيانات خارجية عبر واجهة موحدة. فكر فيه كنظام إضافات يعمل مع Claude Code وCursor وغيرهم من العملاء المتوافقين مع MCP.

خادم MCP يعرض أدوات (functions) وموارد (بيانات) للوكلاء. خادم Apidog MCP الخاص بك سيعرض أدوات API testing.

┌─────────────────┐         ┌──────────────────┐         ┌─────────────┐
│  وكيل الذكاء      │         │  خادم MCP        │         │  Apidog     │
│  الاصطناعي      │◄───────►│  (كودك الخاص بك) │◄───────►│  API        │
│  (Claude Code)  │   JSON  └──────────────────┘  HTTP   └─────────────┘
└─────────────────┘
Enter fullscreen mode Exit fullscreen mode

الخطوة 1: إعداد المشروع

  1. أنشئ مشروع TypeScript جديد:
   mkdir apidog-mcp-server
   cd apidog-mcp-server
   npm init -y
   npm install @modelcontextprotocol/sdk zod
   npm install -D typescript @types/node
Enter fullscreen mode Exit fullscreen mode
  1. أضف ملف 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"]
   }
Enter fullscreen mode Exit fullscreen mode
  1. أضف سكريبت build/start في package.json:
   {
     "scripts": {
       "build": "tsc",
       "start": "node dist/index.js"
     }
   }
Enter fullscreen mode Exit fullscreen mode

الخطوة 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"
});

// الأدوات ستضاف هنا

const transport = new StdioServerTransport();
await server.connect(transport);
Enter fullscreen mode Exit fullscreen mode

وسيط النقل stdio يسمح بالاتصال بين وكيل الذكاء الاصطناعي وخادمك عبر stdin/stdout.

الخطوة 3: تعريف أداة run_test

أضف الأداة الأولى:

server.tool(
  "run_test",
  {
    projectId: z.string().describe("معرّف مشروع Apidog (من عنوان URL للمشروع)"),
    environmentId: z.string().optional().describe("معرّف البيئة (اختياري)"),
    testSuiteId: z.string().optional().describe("معرّف مجموعة الاختبار (اختياري)")
  },
  async ({ projectId, environmentId, testSuiteId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين متغير البيئة APIDOG_API_KEY"
        }]
      };
    }

    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: ${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: `فشل الطلب: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

شرح عملي للأداة:

  • الاسم: run_test
  • المدخلات: معرف المشروع، ومعرف البيئة (اختياري)، ومعرف مجموعة الاختبار (اختياري)
  • التنفيذ: استدعاء API لـ Apidog لتشغيل الاختبار وإرجاع النتائج

الخطوة 4: إضافة أداة validate_schema

للتحقق من صحة مخطط OpenAPI قبل النشر:

server.tool(
  "validate_schema",
  {
    schema: z.object({}).describe("كائن مخطط OpenAPI 3.x للتحقق من صحته"),
    strict: z.boolean().optional().default(false).describe("تمكين الوضع الصارم")
  },
  async ({ schema, strict }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين متغير البيئة APIDOG_API_KEY"
        }]
      };
    }

    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: `فشل التحقق من الصحة: ${JSON.stringify(result.errors, null, 2)}`
          }]
        };
      }

      return {
        content: [{
          type: "text",
          text: result.valid
            ? "المخطط صالح لـ OpenAPI 3.x"
            : `تحذيرات: ${JSON.stringify(result.warnings, null, 2)}`
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `فشل التحقق من الصحة: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

الخطوة 5: إضافة أداة list_environments

لجلب بيئات الاختبار المتاحة:

server.tool(
  "list_environments",
  {
    projectId: z.string().describe("معرّف مشروع Apidog")
  },
  async ({ projectId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين متغير البيئة APIDOG_API_KEY"
        }]
      };
    }

    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: ${response.status} ${error}`
          }]
        };
      }

      const environments = await response.json();
      return {
        content: [{
          type: "text",
          text: environments.length === 0
            ? "لم يتم العثور على بيئات لهذا المشروع"
            : environments.map((e: any) =>
                `- ${e.name} (المعرف: ${e.id})${e.isDefault ? " [افتراضي]" : ""}`
              ).join("\n")
        }]
      };
    } catch (error) {
      return {
        content: [{
          type: "text",
          text: `فشل الطلب: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);
Enter fullscreen mode Exit fullscreen mode

الخطوة 6: البناء والاختبار

قم ببناء الخادم:

npm run build
Enter fullscreen mode Exit fullscreen mode

لاختبار الخادم محليًا (مثال عميل بسيط):

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}`);
});

// إرسال رسالة اختبار
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");
Enter fullscreen mode Exit fullscreen mode

الخطوة 7: التكوين لـ Claude Code

أضف الخادم إلى إعدادات 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"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

أعد تشغيل Claude Code. يجب أن تظهر الأدوات تلقائيًا عند العمل مع اختبار API.

أمثلة للأوامر في Claude Code:

Use the run_test tool to run tests on my Apidog project.
Project ID: proj_12345
Environment: staging
Enter fullscreen mode Exit fullscreen mode
Validate this OpenAPI schema against Apidog rules:
[paste schema]
Enter fullscreen mode Exit fullscreen mode
List all environments for project proj_12345
Enter fullscreen mode Exit fullscreen mode

الخطوة 8: التكوين لـ Cursor

استخدم ملف .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"
      }
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

أمثلة الأوامر في Cursor:

@apidog run_test projectId="proj_12345" environmentId="staging"
Enter fullscreen mode Exit fullscreen mode

الكود المصدري الكامل

المحتوى الكامل لملف 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"),
    environmentId: z.string().optional().describe("معرّف البيئة"),
    testSuiteId: z.string().optional().describe("معرّف مجموعة الاختبار")
  },
  async ({ projectId, environmentId, testSuiteId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين APIDOG_API_KEY"
        }]
      };
    }

    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: `فشل الطلب: ${error instanceof Error ? error.message : String(error)}`
        }]
      };
    }
  }
);

// Tool: validate_schema
server.tool(
  "validate_schema",
  {
    schema: z.object({}).describe("مخطط OpenAPI"),
    strict: z.boolean().optional().default(false)
  },
  async ({ schema, strict }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين APIDOG_API_KEY"
        }]
      };
    }

    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
          ? "المخطط صالح"
          : `مشاكل: ${JSON.stringify(result.errors || result.warnings, null, 2)}`
      }]
    };
  }
);

// Tool: list_environments
server.tool(
  "list_environments",
  {
    projectId: z.string().describe("معرّف مشروع Apidog")
  },
  async ({ projectId }) => {
    const apiKey = process.env.APIDOG_API_KEY;
    if (!apiKey) {
      return {
        content: [{
          type: "text",
          text: "خطأ: لم يتم تعيين APIDOG_API_KEY"
        }]
      };
    }

    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 ? " [افتراضي]" : ""}`
        ).join("\n")
      }]
    };
  }
);

const transport = new StdioServerTransport();
await server.connect(transport);
Enter fullscreen mode Exit fullscreen mode

ما قمت ببنائه

المكون الغرض
خادم MCP يربط وكلاء الذكاء الاصطناعي بواجهة برمجة تطبيقات Apidog
run_test تنفيذ مجموعات الاختبار برمجيًا
validate_schema اكتشاف أخطاء OpenAPI قبل النشر
list_environments اكتشاف بيئات الاختبار المتاحة
التحقق من صحة Zod معالجة آمنة للنوع للمعاملات
وسيط نقل Stdio يعمل مع Claude Code و Cursor وأي عميل MCP

الخطوات التالية

لتوسيع الخادم:

  • أضف أداة compare_responses لمقارنة نتائج الاختبار عبر البيئات.
  • أضف get_test_history لجلب سجل التشغيلات.
  • أضف trigger_mock_server لتشغيل نقاط النهاية الوهمية.

تحسينات الإنتاج:

  • أضف منطق إعادة المحاولة لطلبات الشبكة غير المستقرة.
  • طبق تحديد المعدل لتجنب تقييد واجهة برمجة التطبيقات.
  • أضف السجلات لتصحيح أخطاء الأدوات الفاشلة.
  • خزّن مفاتيح API في خزنة آمنة وليس في متغيرات البيئة.

مشاركة مع الفريق:

  • انشر إلى npm كحزمة خاصة مثل @your-org/apidog-mcp-server
  • وثّق متغيرات البيئة المطلوبة
  • أضف أمثلة تكوين MCP لClaude Code وCursor

استكشاف الأخطاء الشائعة وإصلاحها

خادم MCP لا يظهر في Claude Code:

  • تحقق من أن المسار في ~/.claude/settings.json مطلق.
  • تحقق من وجود node في PATH: which node
  • تأكد من وجود ملف dist/index.js بعد البناء: ls -la dist/
  • راجع سجلات Claude Code لمزيد من التفاصيل.

الأدوات لا تظهر بعد التكوين:

  • أعد تشغيل Claude Code بالكامل.
  • تأكد من تشغيل npm run build.
  • تحقق من تعريف جميع الأدوات قبل server.connect().
  • تأكد أن الخادم يبدأ بدون أخطاء: node dist/index.js.

طلبات API تفشل بكود 401:

  • تأكد من تعيين APIDOG_API_KEY في التكوين.
  • تحقق من عدم وجود مسافات أو علامات اقتباس حول قيمة المفتاح.
  • تأكد من تمكين وصول API في حساب Apidog.
  • اختبر المفتاح يدويًا:
  curl -H "Authorization: Bearer $APIDOG_API_KEY" https://api.apidog.com/v1/user
Enter fullscreen mode Exit fullscreen mode

أخطاء التحقق من صحة Zod:

  • تأكد من تطابق أسماء المعاملات مع المخطط.
  • تحقق من توفير الحقول المطلوبة.
  • استخدم .optional() للحقول الاختيارية.
  • راجع رسالة الخطأ من Zod.

أخطاء تجميع TypeScript:

  • شغّل npm install لتثبيت جميع التبعيات.
  • تحقق من إصدار TypeScript: npx tsc --version (يفضل 5.x).
  • نظّف وأعد البناء: rm -rf dist && npm run build.
  • تحقق من توافق الأنواع في استجابات fetch.

اختبار خادم MCP الخاص بك محليًا

الاختبار اليدوي عبر stdio:

# تشغيل الخادم
node dist/index.js

# في نافذة طرفية أخرى، أرسل رسالة اختبار
echo '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | node dist/index.js
Enter fullscreen mode Exit fullscreen mode

الناتج المتوقع:

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

اختبار استدعاء أداة:

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

الآن وكلاءك لديهم وصول مباشر لاختبارات Apidog — دون نسخ/لصق أو خطوات يدوية. كل ما عليك هو كتابة أمر واحد والحصول على النتيجة.

هذه هي قوة MCP: وسّع إمكانيات عملك في الدردشة، واجعل الذكاء الاصطناعي يساعدك في التسليم السريع.

النقاط الرئيسية

  • خوادم MCP تربط وكلاء الذكاء الاصطناعي بواجهات برمجة التطبيقات الخارجية — أنشئ الأداة مرة، واستخدمها مع Claude Code أو Cursor أو أي عميل MCP.
  • ثلاث أدوات أساسيةrun_test للتنفيذ، validate_schema للتحقق من صحة OpenAPI، list_environments لاكتشاف البيئات.
  • Zod يتحقق من صحة المعاملات — تعريفات الأدوات الآمنة للنوع تلتقط الأخطاء مبكرًا.
  • التكوين خاص بالأداة — Claude Code يستخدم ~/.claude/settings.json، وCursor يستخدم .cursor/mcp.json.
  • تجهيز الإنتاج يتطلب معالجة الأخطاء — أضف إعادة المحاولة، وتحديد المعدل، وتخزين المفاتيح الآمن قبل النشر.

الأسئلة الشائعة

ما هو MCP في الذكاء الاصطناعي؟

MCP (بروتوكول سياق النموذج) هو معيار موحد يتيح لوكلاء الذكاء الاصطناعي استخدام أدوات وبيانات خارجية بطريقة إضافات.

كيف أبني خادم MCP لـ Apidog؟

ثبت @modelcontextprotocol/sdk، عرّف الأدوات مع Zod، نفّذ معالجات تتصل بـ apidog.com، ثم اربطه عبر StdioServerTransport.

هل يمكنني استخدامه مع Cursor؟

نعم. أضف إعداد MCP إلى .cursor/mcp.json في مشروعك. نفس الخادم يعمل مع Claude Code وCursor وأي عميل MCP آخر.

ما الأدوات التي يجب عرضها؟

ابدأ بـ run_test لتشغيل الاختبارات، وvalidate_schema للتحقق من صحة OpenAPI، وlist_environments لجلب البيئات.

هل خادم Apidog MCP جاهز للإنتاج؟

الكود تعليمي كبداية. أضف منطق إعادة المحاولة، وتحديد المعدل، ومعالجة الأخطاء، وتخزين المفاتيح بشكل آمن قبل اعتماده في بيئة إنتاجية.

هل أحتاج مفتاح Apidog API؟

نعم. عيّن متغير البيئة APIDOG_API_KEY. الخادم يعتمد عليه في المصادقة مع apidog.com.

هل يمكنني مشاركة الخادم مع فريقي؟

بالتأكيد. انشره كحزمة npm خاصة وشارك التوثيق وأمثلة التكوينات مع فريقك.


للمزيد من المعلومات أو تجربة الأدوات، تفضل بزيارة Apidog.

Top comments (0)