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:
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().