MCP Base
by jsmiff
- client
- examples
// Example usage of the MCP Client
import MCPClient from "../client.js";
async function main() {
try {
// Create a new client instance
// You can use the default settings to connect to http://localhost:3000
// or specify custom settings
const client = new MCPClient({
// Optional: Override the default server URL
serverUrl: "http://localhost:3000",
// Optional: Choose the transport type ("sse" or "stdio")
transportType: "sse",
// Only needed for stdio transport:
// serverCommand: "node",
// serverArgs: ["server/server.js"],
});
// Check if the server is alive
console.log("Checking server availability...");
const serverAvailable = await client.ping();
if (!serverAvailable) {
console.error("Server is not available. Please make sure the server is running.");
process.exit(1);
}
console.log("Server is available, proceeding with requests\n");
// Example 1: Call a tool
console.log("Example 1: Calling a tool");
try {
const toolResult = await client.callTool("sample-tool", {
query: "search query",
maxResults: 5,
options: {
filterBy: "category",
sortBy: "relevance"
}
});
console.log("Tool result:", toolResult);
console.log("\n");
} catch (error) {
console.error("Tool call failed:", error.message);
}
// Example 2: Read a resource
console.log("Example 2: Reading a resource");
try {
// Read all items
const allItems = await client.readResource("items://all");
console.log("All items:", allItems);
// Read a specific item by ID
const item = await client.readResource("items://1");
console.log("Item with ID 1:", item);
// Read items by category
const categoryItems = await client.readResource("items://category/electronics");
console.log("Electronics items:", categoryItems);
console.log("\n");
} catch (error) {
console.error("Resource read failed:", error.message);
}
// Example 3: Get a prompt
console.log("Example 3: Getting a prompt");
try {
// Get a simple prompt
const simplePrompt = await client.getPrompt("simple-prompt", {
task: "Explain quantum computing in simple terms",
context: "For a 10-year-old audience"
});
console.log("Simple prompt:", simplePrompt);
// Get an item-specific prompt
const itemPrompt = await client.getPrompt("item-usage-prompt", {
itemId: "42",
userQuery: "How do I use this item with my existing setup?"
});
console.log("Item prompt:", itemPrompt);
console.log("\n");
} catch (error) {
console.error("Prompt retrieval failed:", error.message);
}
// Example 4: List all available prompts
console.log("Example 4: Listing all prompts");
try {
const prompts = await client.listPrompts();
console.log("Available prompts:", prompts);
} catch (error) {
console.error("Prompt listing failed:", error.message);
}
// Don't forget to disconnect when done
await client.disconnect();
console.log("Disconnected from server");
} catch (error) {
console.error("An error occurred:", error);
}
}
// Run the main function
main().catch(console.error);