#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { exec } from "child_process";
import { promisify } from "util";
const execAsync = promisify(exec);
class PingServer {
private server: McpServer;
constructor() {
this.server = new McpServer(
{
name: "mcp-ping",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
this.setupHandlers();
}
private setupHandlers() {
// Register the ping tool
this.server.registerTool(
"ping",
{
description: "Ping a host/website to check connectivity and measure latency",
inputSchema: z.object({
host: z.string().describe("The hostname or IP address to ping (e.g., 'google.com', '8.8.8.8')"),
}),
},
async (args) => {
const { host } = args;
try {
// Execute ping command
// Using -c 4 for 4 packets on Unix/macOS, or -n 4 on Windows
const isWindows = process.platform === "win32";
const pingCommand = isWindows
? `ping -n 4 ${host}`
: `ping -c 4 ${host}`;
const { stdout, stderr } = await execAsync(pingCommand, {
timeout: 10000, // 10 second timeout
});
if (stderr) {
return {
content: [
{
type: "text",
text: `Error: ${stderr}\n\nOutput: ${stdout}`,
},
],
isError: true,
};
}
return {
content: [
{
type: "text",
text: stdout || "Ping completed successfully",
},
],
};
} catch (error: any) {
return {
content: [
{
type: "text",
text: `Failed to ping ${host}: ${error.message}`,
},
],
isError: true,
};
}
}
);
}
async run() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
console.error("MCP Ping Server running on stdio");
}
}
const server = new PingServer();
server.run().catch(console.error);