Model Context Protocol Model Context Protocol Model Context Protocol · Lab 3/7 Lab 3/7 Lab 3/7 · 30 phút · 30 min · 30 នាទី

03

Tích hợp API ngoài External API Integration ភ្ជាប់ API ខាងក្រៅ

Gọi API ngoài từ MCP tool. Nâng tool số ngẫu nhiên bằng beacon drand. Integrate external APIs into MCP tools. Enhance the random number tool with the drand randomness beacon for true randomness. ហៅ API ខាងក្រៅពី MCP tool។ លើក tool លេខចៃដន្យដោយ beacon drand។

Nội dung bước (lệnh, code) giữ nguyên tiếng Anh từ nguồn chính thức. Step body (commands, code) stays in English from the official source. ខ្លឹមសារជំហាន (ពាក្យបញ្ជា និង code) រក្សាភាសាអង់គ្លេសពីប្រភពផ្លូវការ។ labs.cloudflare.dev ↗

Cần trước Prerequisites តម្រូវការជាមុន

  • Đã xong bước 2 Completed Step 2 បានបញ្ចប់ជំហាន 2
  • Tool generate_random_number đang chạy generate_random_number tool working Tool generate_random_number កំពុងដំណើរការ
  • Hiểu HTTP request Understanding of HTTP requests យល់ HTTP request

Bạn sẽ làm được Learning objectives គោលបំណងសិក្សា

  • Gọi HTTP từ MCP tool Make HTTP requests from MCP tools ហៅ HTTP ពី MCP tool
  • Xử lý response và lỗi từ API ngoài Handle external API responses and errors ដោះស្រាយ response និង error ពី API ខាងក្រៅ
  • Làm cơ chế fallback cho độ tin cậy Implement fallback mechanisms for reliability ធ្វើយន្តការ fallback ដើម្បីភាពជឿជាក់
  • Xử lý data ngoài để AI dùng được Process external data for AI consumption ដំណើរការ data ខាងក្រៅឲ្យ AI ប្រើបាន

Bước 1: Gắn API ngẫu nhiên drand Step 1: Enhance with the drand Randomness API ជំហាន 1: ភ្ជាប់ API ចៃដន្យ drand

Chúng ta đang xây What we're building អ្វីដែលយើងកំពុងសង់
An enhanced random number tool that fetches cryptographically secure randomness from an external API, with a graceful fallback.
Vì sao quan trọng Why this matters ហេតុអ្វីសំខាន់
External API integration is what makes MCP tools truly powerful. Your tools can access any data or service on the internet.

Replace your existing generate_random_number tool in src/index.ts with this enhanced version:

Replace your existing generate_random_number tool in src/index.ts with this enhanced version:

Replace your existing generate_random_number tool in src/index.ts with this enhanced version:

typescript
this.server.tool(
  "generate_random_number",
  "Generate a truly random number between two numbers",
  { min: z.number(), max: z.number() },
  async ({ min, max }) => {
    try {
      // Fetch true randomness from the drand beacon endpoint
      const response = await fetch(
        "https://drand.cloudflare.com/public/latest",
      );
      const data = (await response.json()) as {
        round: number;
        signature: string;
        previous_signature: string;
        randomness: string;
      };

      // Process randomness
      const randomHex = data.randomness;
      const startIndex = Math.floor(Math.random() * (randomHex.length - 8));
      const randomValue = parseInt(
        randomHex.slice(startIndex, startIndex + 8),
        16,
      );

      // Scale to requested range
      const scaledRandom = (Math.abs(randomValue) % (max - min + 1)) + min;

      return {
        content: [
          {
            type: "text",
            text: String(scaledRandom),
          },
        ],
      };
    } catch (error) {
      // Fallback to Math.random if API fails
      return {
        content: [
          {
            type: "text",
            text: String(Math.floor(Math.random() * (max - min + 1)) + min),
          },
        ],
      };
    }
  },
);

Bước 2: Test tool đã nâng cấp Step 2: Test the Enhanced Tool ជំហាន 2: Test tool ដែលបានធ្វើឱ្យប្រសើរ

Save the file and head back to the MCP Inspector. Click the refresh button next to “Available Tools” to reload, then test generate_random_number a few times with {"min": 1, "max": 100}. The results now come from the drand randomness beacon instead of Math.random().

Save the file and head back to the MCP Inspector. Click the refresh button next to “Available Tools” to reload, then test generate_random_number a few times with {"min": 1, "max": 100}. The results now come from the drand randomness beacon instead of Math.random().

Save the file and head back to the MCP Inspector. Click the refresh button next to “Available Tools” to reload, then test generate_random_number a few times with {"min": 1, "max": 100}. The results now come from the drand randomness beacon instead of Math.random().