mcp-client.jsā¢3.14 kB
#!/usr/bin/env node
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { spawn } from "child_process";
import path from "path";
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Create MCP client
const client = new Client(
{
name: "weather-client",
version: "1.0.0",
},
{
capabilities: {},
}
);
async function connectToWeatherServer() {
// Path to the weather server
const serverPath = path.join(__dirname, "build", "index.js");
console.log("š Connecting to Weather MCP Server...\n");
// Create transport using stdio
const transport = new StdioClientTransport({
command: "node",
args: [serverPath],
});
// Connect the client to the server
await client.connect(transport);
console.log("ā
Connected to Weather MCP Server\n");
return transport;
}
async function listAvailableTools() {
console.log("š Listing available tools...\n");
const response = await client.listTools();
response.tools.forEach((tool) => {
console.log(`Tool: ${tool.name}`);
console.log(` Description: ${tool.description}`);
console.log(` Input Schema:`, JSON.stringify(tool.inputSchema, null, 2));
console.log();
});
return response.tools;
}
async function callWeatherTool(latitude, longitude, locationName = "Unknown") {
console.log(
`š¤ļø Fetching weather for ${locationName} (${latitude}, ${longitude})...\n`
);
const result = await client.callTool({
name: "get_weather",
arguments: {
latitude,
longitude,
},
});
// Display the result
if (result.content && result.content.length > 0) {
result.content.forEach((item) => {
if (item.type === "text") {
console.log(item.text);
}
});
}
if (result.isError) {
console.error("\nā Error occurred while fetching weather");
}
console.log("\n" + "=".repeat(80) + "\n");
}
async function main() {
let transport;
try {
// Connect to the server
transport = await connectToWeatherServer();
// List available tools
await listAvailableTools();
// Example 1: Get weather for Sammamish, WA
await callWeatherTool(47.6162, -122.0356, "Sammamish, WA");
// Example 2: Get weather for Berlin, Germany
await callWeatherTool(52.52, 13.41, "Berlin, Germany");
// Example 3: Get weather for Tokyo, Japan
await callWeatherTool(35.68, 139.65, "Tokyo, Japan");
console.log("⨠All weather queries completed successfully!");
} catch (error) {
console.error("ā Error:", error.message);
console.error(error);
} finally {
// Close the connection
if (transport) {
await client.close();
console.log("\nš Disconnected from Weather MCP Server");
}
}
}
// Run the client
main().catch((error) => {
console.error("Fatal error:", error);
process.exit(1);
});