Skip to main content

Basic LLM-MCP Usage Examples

This document provides practical code examples for common LLM-MCP operations. These examples will help you quickly start using the LLM Platform Model Context Protocol in your applications.

Table of Contentsโ€‹

Server Connectionโ€‹

Basic Connectionโ€‹

Connect to a LLM-MCP server using the JavaScript client:

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

// Create a client instance
const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

// Check server health
async function checkServerHealth() {
try {
const health = await client.health();
console.log('Server health:', health);
// Output: { status: 'ok', version: '1.0.0', uptime: 3600 }

return health.status === 'ok';
} catch (error) {
console.error('Health check failed:', error.message);
return false;
}
}

checkServerHealth();

Connection with Configuration Optionsโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

// Create a client with advanced options
const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key',

// Connection options
timeout: 30000, // 30 seconds timeout
retryAttempts: 3, // Retry failed requests 3 times
retryDelay: 1000, // Wait 1 second between retries

// Logging options
logLevel: 'info', // Log level (debug, info, warn, error)

// Cache options
cache: {
enabled: true, // Enable response caching
ttl: 300, // Cache TTL in seconds
maxEntries: 1000, // Maximum cache entries
},

// Headers
headers: { // Additional headers for all requests
'X-Client-Version': '1.0.0',
},
});

// Test the connection with retry logic
async function testConnectionWithRetry() {
let connected = false;
let attempts = 0;
const maxAttempts = 5;

while (!connected && attempts < maxAttempts) {
try {
const health = await client.health();
console.log(`Connected to LLM-MCP server v[health.version]`);
connected = true;
} catch (error) {
attempts++;
console.warn(`Connection attempt [attempts] failed: [error.message]`);

if (attempts < maxAttempts) {
const delay = Math.pow(2, attempts) * 1000; // Exponential backoff
console.log(`Retrying in [delay/1000] seconds...`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
console.error('Failed to connect after multiple attempts');
}
}
}

return connected;
}

testConnectionWithRetry();

TypeScript Connectionโ€‹

import { BfmcpClient, ServerHealth, ClientOptions } from '@bluefly/llm-mcp/client';

// Define client options with TypeScript types
const options: ClientOptions = {
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key',
timeout: 30000,
};

// Create client
const client = new BfmcpClient(options);

// Check health with proper typing
async function checkHealth(): Promise<boolean> {
try {
const health: ServerHealth = await client.health();
console.log('Server status:', health.status);
console.log('Server version:', health.version);

return health.status === 'ok';
} catch (error) {
console.error('Health check failed:', error instanceof Error ? error.message : String(error));
return false;
}
}

// Execute and handle result
checkHealth()
.then(isHealthy => {
console.log('Server is healthy:', isHealthy);
})
.catch(error => {
console.error('Unexpected error:', error);
});

Tool Managementโ€‹

Registering a Simple Toolโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

// Define a simple calculator tool
const calculatorTool = {
id: 'calculator',
name: 'Calculator',
description: 'Performs basic arithmetic operations',
version: '1.0.0',
category: 'utilities',
tags: ['math', 'calculation'],

// Define input schema
input_schema: {
type: 'object',
properties: {
operation: {
type: 'string',
enum: ['add', 'subtract', 'multiply', 'divide'],
description: 'The arithmetic operation to perform'
},
a: {
type: 'number',
description: 'First operand'
},
b: {
type: 'number',
description: 'Second operand'
}
},
required: ['operation', 'a', 'b']
},

// Define output schema
output_schema: {
type: 'object',
properties: {
result: {
type: 'number',
description: 'The result of the operation'
}
}
},

// Define the function that will be executed
function: async (input) => {
const { operation, a, b } = input;

switch (operation) {
case 'add':
return { result: a + b };
case 'subtract':
return { result: a - b };
case 'multiply':
return { result: a * b };
case 'divide':
if (b === 0) {
throw new Error('Division by zero');
}
return { result: a / b };
default:
throw new Error(`Unknown operation: [operation]`);
}
}
};

// Register the tool
async function registerCalculatorTool() {
try {
await client.registerTool(calculatorTool);
console.log(`Tool '[calculatorTool.id]' registered successfully`);
} catch (error) {
console.error(`Failed to register tool: [error.message]`);
}
}

registerCalculatorTool();

Registering a Remote Toolโ€‹

// Define a remote tool that calls an external API
const weatherTool = {
id: 'weather_api',
name: 'Weather API',
description: 'Get current weather for a location',
version: '1.0.0',
category: 'external_services',
tags: ['weather', 'api'],

// Define input schema
input_schema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name and country code (e.g., "London,UK")'
},
units: {
type: 'string',
enum: ['metric', 'imperial'],
default: 'metric',
description: 'Units of measurement'
}
},
required: ['location']
},

// Define output schema
output_schema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'Location name'
},
temperature: {
type: 'number',
description: 'Current temperature'
},
conditions: {
type: 'string',
description: 'Weather conditions'
},
humidity: {
type: 'number',
description: 'Humidity percentage'
}
}
},

// Instead of a function, provide an endpoint for remote execution
endpoint: 'https://api.weatherservice.com/v1/current',

// Authentication configuration for the remote API
auth_config: {
type: 'api_key',
header_name: 'X-API-Key',
key: process.env.WEATHER_API_KEY
},

// Rate limiting configuration
rate_limit: {
max_requests: 60,
period: 'minute'
},

// Cache configuration
cache_config: {
enabled: true,
ttl: 600 // Cache results for 10 minutes
}
};

// Register the remote tool
client.registerTool(weatherTool)
.then(() => console.log(`Tool '[weatherTool.id]' registered successfully`))
.catch(error => console.error(`Failed to register tool: [error.message]`));

Listing Available Toolsโ€‹

// List all registered tools
async function listAllTools() {
try {
const tools = await client.listTools();
console.log(`Found [tools.length] registered tools:`);

tools.forEach(tool => {
console.log(`- [tool.id] ([tool.name]): [tool.description]`);
});
} catch (error) {
console.error(`Failed to list tools: [error.message]`);
}
}

// List tools with filtering
async function findSpecificTools() {
try {
// Find tools by category
const mathTools = await client.listTools({ category: 'utilities', tags: ['math'] });
console.log(`Found [mathTools.length] math tools`);

// Find tools by search term
const weatherTools = await client.listTools({ query: 'weather' });
console.log(`Found [weatherTools.length] weather-related tools`);
} catch (error) {
console.error(`Search failed: [error.message]`);
}
}

// Execute both functions
(async () => {
await listAllTools();
await findSpecificTools();
})();

Updating a Toolโ€‹

// Update an existing tool
async function updateTool() {
try {
// First, get the current tool definition
const tool = await client.getTool('calculator');

// Create an updated version
const updatedTool = {
...tool,
version: '1.1.0',
description: 'Performs basic and advanced arithmetic operations',
tags: [...tool.tags, 'advanced'],

// Add new input options
input_schema: {
...tool.input_schema,
properties: {
...tool.input_schema.properties,
operation: {
type: 'string',
enum: ['add', 'subtract', 'multiply', 'divide', 'power', 'sqrt'],
description: 'The arithmetic operation to perform'
}
}
}
};

// Update the tool
await client.updateTool(updatedTool);
console.log(`Tool '[tool.id]' updated to version [updatedTool.version]`);
} catch (error) {
console.error(`Failed to update tool: [error.message]`);
}
}

updateTool();

Deleting a Toolโ€‹

// Delete a tool
async function deleteTool(toolId) {
try {
await client.deleteTool(toolId);
console.log(`Tool '[toolId]' deleted successfully`);
} catch (error) {
console.error(`Failed to delete tool: [error.message]`);
}
}

deleteTool('deprecated_tool');

Tool Executionโ€‹

Basic Tool Executionโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

// Execute the calculator tool
async function runCalculation() {
try {
const result = await client.executeTool('calculator', {
operation: 'add',
a: 5,
b: 3
});

console.log(`5 + 3 = [result.result]`);
// Output: 5 + 3 = 8
} catch (error) {
console.error(`Calculation failed: [error.message]`);
}
}

// Execute the weather tool
async function getWeather(location) {
try {
const result = await client.executeTool('weather_api', {
location: location,
units: 'metric'
});

console.log(`Weather in [result.location]:`);
console.log(`- Temperature: [result.temperature]ยฐC`);
console.log(`- Conditions: [result.conditions]`);
console.log(`- Humidity: [result.humidity]%`);
} catch (error) {
console.error(`Weather lookup failed: [error.message]`);
}
}

// Execute both tools
(async () => {
await runCalculation();
await getWeather('London,UK');
})();

Tool Execution with Optionsโ€‹

// Execute tool with execution options
async function executeWithOptions() {
try {
// Execute with timeout and context
const result = await client.executeTool(
'weather_api', // Tool ID
{ location: 'New York,US' }, // Tool parameters
{
timeout: 5000, // 5 second timeout
retry: true, // Retry on failure
maxRetries: 3, // Maximum retries
bypassCache: false, // Use cache if available
context: { // Execution context
user_id: 'user-123',
session_id: 'session-456',
source: 'example-app'
}
}
);

console.log('Weather result:', result);
} catch (error) {
console.error(`Execution failed: [error.message]`);
}
}

executeWithOptions();

Batch Tool Executionโ€‹

// Execute multiple tools in a batch
async function executeBatch() {
try {
const batchResults = await client.executeBatch([
{
tool_id: 'calculator',
params: { operation: 'add', a: 10, b: 20 }
},
{
tool_id: 'calculator',
params: { operation: 'multiply', a: 5, b: 7 }
},
{
tool_id: 'weather_api',
params: { location: 'Tokyo,JP' }
}
]);

// Process batch results
batchResults.forEach((result, index) => {
if (result.success) {
console.log(`Batch result [index + 1]:`, result.data);
} else {
console.error(`Batch error [index + 1]:`, result.error);
}
});
} catch (error) {
console.error(`Batch execution failed: [error.message]`);
}
}

executeBatch();

Asynchronous Tool Executionโ€‹

// Execute a long-running tool asynchronously
async function executeAsync() {
try {
// Start asynchronous execution
const executionId = await client.executeToolAsync(
'data_processing',
{ dataset_id: 'large-dataset', operation: 'analyze' }
);

console.log(`Execution started with ID: [executionId]`);

// Poll for completion
let completed = false;
while (!completed) {
const status = await client.getToolExecutionStatus(executionId);
console.log(`Execution status: [status.state], progress: [status.progress || 0]%`);

if (status.state === 'completed' || status.state === 'failed') {
completed = true;
} else {
// Wait 2 seconds before polling again
await new Promise(resolve => setTimeout(resolve, 2000));
}
}

// Get the result
const result = await client.getToolExecutionResult(executionId);
console.log('Execution result:', result);
} catch (error) {
console.error(`Async execution failed: [error.message]`);
}
}

executeAsync();

Vector Operationsโ€‹

Storing Vectorsโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

// Store a single vector
async function storeDocumentVector() {
try {
// Store a vector with metadata
await client.storeVector({
id: 'doc-123', // Unique identifier
vector: [0.1, 0.2, 0.3, 0.4, /* ... */], // Embedding vector
metadata: { // Associated metadata
title: 'Important Document',
content: 'This is a summary of the document...',
url: 'https://example.com/docs/123',
tags: ['important', 'documentation'],
created_at: new Date().toISOString()
},
collection: 'documents' // Collection name
});

console.log('Vector stored successfully');
} catch (error) {
console.error(`Failed to store vector: [error.message]`);
}
}

// Store multiple vectors in a batch
async function storeMultipleVectors() {
try {
await client.storeVectors({
vectors: [
{
id: 'doc-123',
vector: [0.1, 0.2, 0.3, /* ... */],
metadata: { title: 'Document 1' }
},
{
id: 'doc-456',
vector: [0.4, 0.5, 0.6, /* ... */],
metadata: { title: 'Document 2' }
},
{
id: 'doc-789',
vector: [0.7, 0.8, 0.9, /* ... */],
metadata: { title: 'Document 3' }
}
],
collection: 'documents'
});

console.log('Batch vector storage completed');
} catch (error) {
console.error(`Batch storage failed: [error.message]`);
}
}

// Execute functions
(async () => {
await storeDocumentVector();
await storeMultipleVectors();
})();

Finding Similar Vectorsโ€‹

// Search for similar vectors
async function findSimilarDocuments() {
try {
// Find vectors similar to a query vector
const results = await client.findSimilarVectors({
vector: [0.15, 0.25, 0.35, /* ... */], // Query vector
collection: 'documents', // Collection to search
limit: 5, // Maximum results
scoreThreshold: 0.75, // Minimum similarity score

// Filter based on metadata
filter: {
tags: { $in: ['important'] },
created_at: { $gt: '2023-01-01T00:00:00Z' }
},

// Include vectors in results
includeVectors: false,

// Include metadata in results
includeMetadata: true
});

// Process results
console.log(`Found [results.length] similar documents:`);
results.forEach(result => {
console.log(`- ID: [result.id]`);
console.log(` Score: [result.score.toFixed(4)]`);
console.log(` Title: [result.metadata.title]`);
console.log(` Tags: [result.metadata.tags.join(', ')]`);
});
} catch (error) {
console.error(`Vector search failed: [error.message]`);
}
}

findSimilarDocuments();

Vector Collection Managementโ€‹

// Create a new vector collection
async function createCollection() {
try {
await client.createVectorCollection({
name: 'product_embeddings', // Collection name
dimensions: 1536, // Vector dimensions
similarity: 'cosine', // Similarity metric (cosine, euclidean, dot)
indexType: 'hnsw', // Index type

// Optional advanced index parameters
indexParams: {
m: 16, // Connections per layer
efConstruction: 100, // Construction time accuracy
}
});

console.log('Collection created successfully');
} catch (error) {
console.error(`Failed to create collection: [error.message]`);
}
}

// List all collections
async function listCollections() {
try {
const collections = await client.listVectorCollections();

console.log(`Found [collections.length] collections:`);
collections.forEach(collection => {
console.log(`- [collection.name]`);
console.log(` Dimensions: [collection.dimensions]`);
console.log(` Vectors: [collection.count]`);
console.log(` Similarity: [collection.similarity]`);
});
} catch (error) {
console.error(`Failed to list collections: [error.message]`);
}
}

// Delete a collection
async function deleteCollection(name) [try {
await client.deleteVectorCollection({ name]);
console.log(`Collection 'Name' deleted successfully`);
} catch (error) {
console.error(`Failed to delete collection: [error.message]`);
}
}

// Execute collection management functions
(async () => {
await createCollection();
await listCollections();
// Uncomment to delete a collection
// await deleteCollection('temporary_collection');
})();

Model Managementโ€‹

Listing Available Modelsโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

// List all available models
async function listModels() {
try {
const models = await client.listModels();

console.log(`Found [models.length] available models:`);
models.forEach(model => {
console.log(`- [model.id] ([model.provider])`);
console.log(` Type: [model.type]`);
console.log(` Max tokens: [model.max_tokens]`);
console.log(` Description: [model.description]`);
});
} catch (error) {
console.error(`Failed to list models: [error.message]`);
}
}

// Get details for a specific model
async function getModelDetails(modelId) {
try {
const model = await client.getModel(modelId);

console.log(`Model: [model.id]`);
console.log(`Provider: [model.provider]`);
console.log(`Version: [model.version]`);
console.log(`Description: [model.description]`);
console.log('Capabilities:');

// Show model capabilities
for (const [capability, supported] of Object.entries(model.capabilities)) {
console.log(`- [capability]: [supported ? 'Yes' : 'No']`);
}

// Show pricing information if available
if (model.pricing) {
console.log('Pricing:');
console.log(`- Input: $[model.pricing.input_per_token] per token`);
console.log(`- Output: $[model.pricing.output_per_token] per token`);
}
} catch (error) {
console.error(`Failed to get model details: [error.message]`);
}
}

// Execute model management functions
(async () => {
await listModels();
await getModelDetails('gpt-4');
})();

Generating Text with a Modelโ€‹

// Generate text with a model
async function generateText() {
try {
const result = await client.executeTool('text_generation', {
model: 'gpt-4',
prompt: 'Write a short poem about artificial intelligence.',
max_tokens: 200,
temperature: 0.7
});

console.log('Generated Text:');
console.log(result.text);
} catch (error) {
console.error(`Text generation failed: [error.message]`);
}
}

// Generate embeddings
async function generateEmbedding(text) {
try {
const result = await client.executeTool('embedding_generation', {
model: 'text-embedding-ada-002',
text: text
});

console.log(`Generated embedding with [result.embedding.length] dimensions`);
console.log('First few dimensions:', result.embedding.slice(0, 5));

return result.embedding;
} catch (error) {
console.error(`Embedding generation failed: [error.message]`);
return null;
}
}

// Execute text generation functions
(async () => {
await generateText();
const embedding = await generateEmbedding('This is a sample text for embedding generation.');

// Store the embedding if generated successfully
if (embedding) {
await client.storeVector({
id: `doc-[Date.now()]`,
vector: embedding,
metadata: {
text: 'This is a sample text for embedding generation.',
created_at: new Date().toISOString()
},
collection: 'embeddings'
});

console.log('Embedding stored successfully');
}
})();

Complete Applicationsโ€‹

Semantic Search Applicationโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

/**
* Semantic Search Application
*
* This example demonstrates a complete semantic search application
* that generates embeddings, stores them, and performs similarity searches.
*/
class SemanticSearch {
constructor(client) {
this.client = client;
this.collection = 'semantic_search';
}

/**
* Initialize the search application
*/
async initialize() {
try {
// Check if collection exists, create if it doesn't
const collections = await this.client.listVectorCollections();
const exists = collections.some(c => c.name === this.collection);

if (!exists) {
console.log(`Creating vector collection '[this.collection]'`);
await this.client.createVectorCollection({
name: this.collection,
dimensions: 1536, // For text-embedding-ada-002
similarity: 'cosine'
});
}

console.log('Semantic search initialized successfully');
return true;
} catch (error) {
console.error(`Initialization failed: [error.message]`);
return false;
}
}

/**
* Add a document to the search index
*/
async addDocument(id, text, metadata = {}) {
try {
// Generate embedding for the text
const embedding = await this.client.executeTool('embedding_generation', {
model: 'text-embedding-ada-002',
text: text
});

// Store the embedding with metadata
await this.client.storeVector({
id: id,
vector: embedding.embedding,
metadata: {
...metadata,
text: text,
indexed_at: new Date().toISOString()
},
collection: this.collection
});

console.log(`Document 'item' added to search index`);
return true;
} catch (error) {
console.error(`Failed to add document: [error.message]`);
return false;
}
}

/**
* Search for documents similar to a query
*/
async search(query, limit = 5, filters = {}) {
try {
// Generate embedding for the query
const embedding = await this.client.executeTool('embedding_generation', {
model: 'text-embedding-ada-002',
text: query
});

// Search for similar vectors
const results = await this.client.findSimilarVectors({
vector: embedding.embedding,
collection: this.collection,
limit: limit,
scoreThreshold: 0.7,
filter: filters,
includeMetadata: true
});

// Format results
return results.map(result => ({
id: result.id,
score: result.score,
text: result.metadata.text,
...Object.fromEntries(
Object.entries(result.metadata).filter(([key]) => key !== 'text')
)
}));
} catch (error) {
console.error(`Search failed: [error.message]`);
return [];
}
}

/**
* Delete a document from the index
*/
async deleteDocument(id) {
try {
await this.client.deleteVector({
id: id,
collection: this.collection
});

console.log(`Document 'item' deleted from search index`);
return true;
} catch (error) {
console.error(`Failed to delete document: [error.message]`);
return false;
}
}

/**
* Get statistics about the search index
*/
async getStats() {
try {
const collections = await this.client.listVectorCollections();
const collection = collections.find(c => c.name === this.collection);

if (!collection) {
throw new Error(`Collection '[this.collection]' not found`);
}

return {
collection: this.collection,
document_count: collection.count,
dimensions: collection.dimensions,
similarity: collection.similarity
};
} catch (error) {
console.error(`Failed to get stats: [error.message]`);
return null;
}
}
}

// Usage example
async function runSemanticSearchDemo() {
// Create and initialize the search application
const search = new SemanticSearch(client);
const initialized = await search.initialize();

if (!initialized) {
console.error('Failed to initialize semantic search');
return;
}

// Add sample documents
await search.addDocument('doc1', 'Artificial intelligence is transforming the world of technology', {
title: 'AI Transformation',
category: 'technology'
});

await search.addDocument('doc2', 'Machine learning algorithms can identify patterns in data', {
title: 'ML Patterns',
category: 'data science'
});

await search.addDocument('doc3', 'Natural language processing enables computers to understand human language', {
title: 'NLP Understanding',
category: 'linguistics'
});

// Get statistics
const stats = await search.getStats();
console.log('Search index statistics:', stats);

// Perform searches
console.log('\nSearching for "AI technology"');
const results1 = await search.search('AI technology');
results1.forEach(result => {
console.log(`- [[result.score.toFixed(2)]] [result.title]: [result.text]`);
});

console.log('\nSearching for "data patterns"');
const results2 = await search.search('data patterns');
results2.forEach(result => {
console.log(`- [[result.score.toFixed(2)]] [result.title]: [result.text]`);
});

console.log('\nSearching for "language understanding" in linguistics category');
const results3 = await search.search('language understanding', 5, { category: 'linguistics' });
results3.forEach(result => {
console.log(`- [[result.score.toFixed(2)]] [result.title]: [result.text]`);
});

// Clean up (uncomment to delete)
// await search.deleteDocument('doc1');
// await search.deleteDocument('doc2');
// await search.deleteDocument('doc3');
}

// Run the demo
runSemanticSearchDemo();

Multi-Tool Agent Systemโ€‹

const [BfmcpClient] = require('@bluefly/llm-mcp/client');

const client = new BfmcpClient({
serverUrl: 'http://localhost:3001',
apiKey: 'your-api-key'
});

/**
* Multi-Tool Agent System
*
* This example demonstrates a complete agent system that can use
* multiple tools to accomplish complex tasks.
*/
class MultiToolAgent {
constructor(client) {
this.client = client;
this.tools = [];
}

/**
* Initialize the agent
*/
async initialize() {
try {
// Fetch available tools
this.tools = await this.client.listTools();
console.log(`Agent initialized with [this.tools.length] tools available`);
return true;
} catch (error) {
console.error(`Agent initialization failed: [error.message]`);
return false;
}
}

/**
* Process a user query with the agent
*/
async process(query) {
try {
// Step 1: Generate embedding for the query
const embedding = await this.client.executeTool('embedding_generation', {
model: 'text-embedding-ada-002',
text: query
});

// Step 2: Determine which tools to use based on the query
const toolsToUse = await this.selectTools(query, embedding.embedding);

// Step 3: Execute the selected tools
const toolResults = await this.executeTools(toolsToUse, query);

// Step 4: Generate a response based on the tool results
const response = await this.generateResponse(query, toolResults);

return {
query,
tools_used: toolsToUse.map(t => t.id),
tool_results: toolResults,
response
};
} catch (error) {
console.error(`Agent processing failed: [error.message]`);
return {
query,
error: error.message
};
}
}

/**
* Select tools based on the query
*/
async selectTools(query, queryEmbedding) {
// For simplicity, we'll use a fixed set of tools based on keywords
// In a real system, you might use a more sophisticated approach
const selectedTools = [];

// Check for weather-related queries
if (query.toLowerCase().includes('weather')) {
const weatherTool = this.tools.find(t => t.id === 'weather_api');
if (weatherTool) selectedTools.push(weatherTool);
}

// Check for calculation queries
if (/\d+\s*[\+\-\*\/]\s*\d+/.test(query)) {
const calculatorTool = this.tools.find(t => t.id === 'calculator');
if (calculatorTool) selectedTools.push(calculatorTool);
}

// Always include search capability
const searchTool = this.tools.find(t => t.id === 'semantic_search');
if (searchTool) selectedTools.push(searchTool);

// If no specific tools were selected, use text generation
if (selectedTools.length === 0 || query.toLowerCase().includes('explain')) {
const textGenTool = this.tools.find(t => t.id === 'text_generation');
if (textGenTool) selectedTools.push(textGenTool);
}

return selectedTools;
}

/**
* Execute the selected tools
*/
async executeTools(tools, query) [const results = {];

for (const tool of tools) {
try {
let params;

// Configure parameters for each tool
switch (tool.id) {
case 'weather_api':
// Extract location from query
const locationMatch = query.match(/weather\s+in\s+([a-zA-Z\s,]+)/i);
params = {
location: locationMatch ? locationMatch[1].trim() : 'New York,US',
units: 'metric'
};
break;

case 'calculator':
// Extract calculation from query
const calcMatch = query.match(/(\d+)\s*([\+\-\*\/])\s*(\d+)/);
if (calcMatch) {
const [_, a, op, b] = calcMatch;
const operation = {
'+': 'add',
'-': 'subtract',
'*': 'multiply',
'/': 'divide'
}[op];

params = {
operation,
a: parseFloat(a),
b: parseFloat(b)
};
}
break;

case 'semantic_search':
params = {
query,
limit: 3
};
break;

case 'text_generation':
params = {
model: 'gpt-4',
prompt: `Answer the following question in a helpful way: [query]`,
max_tokens: 300,
temperature: 0.7
};
break;

default:
params = [query];
}

// Execute the tool
console.log(`Executing tool: [tool.id]`);
const result = await this.client.executeTool(tool.id, params);
results[tool.id] = result;
} catch (error) {
console.error(`Tool [tool.id] execution failed: [error.message]`);
results[tool.id] = { error: error.message };
}
}

return results;
}

/**
* Generate a final response based on tool results
*/
async generateResponse(query, toolResults) {
// For a real agent, you might use another LLM call to synthesize results
// For this example, we'll create a simple response based on available results

let response = '';

// Handle weather results
if (toolResults.weather_api && !toolResults.weather_api.error) {
const weather = toolResults.weather_api;
response += `Weather in [weather.location]: [weather.temperature]ยฐC, [weather.conditions]. `;
}

// Handle calculator results
if (toolResults.calculator && !toolResults.calculator.error) {
response += `Calculation result: [toolResults.calculator.result]. `;
}

// Handle search results
if (toolResults.semantic_search && !toolResults.semantic_search.error) {
const search = toolResults.semantic_search;
response += `Found [search.length] relevant documents. `;

if (search.length > 0) {
response += `Most relevant: "[search[0].text]". `;
}
}

// Handle text generation results
if (toolResults.text_generation && !toolResults.text_generation.error) {
response += toolResults.text_generation.text;
}

// Fallback if no tools provided useful results
if (!response) {
response = "I couldn't find a specific answer to your query. Could you provide more details?";
}

return response;
}
}

// Usage example
async function runAgentDemo() {
// Create and initialize the agent
const agent = new MultiToolAgent(client);
const initialized = await agent.initialize();

if (!initialized) {
console.error('Failed to initialize agent');
return;
}

// Process sample queries
const queries = [
"What's the weather in London?",
"Calculate 24 * 7",
"Explain how machine learning works",
"Find information about quantum computing"
];

for (const query of queries) {
console.log(`\n\nProcessing query: "[query]"`);
const result = await agent.process(query);

console.log('Tools used:', result.tools_used.join(', '));
console.log('Response:', result.response);
}
}

// Run the demo
runAgentDemo();

Conclusionโ€‹

These examples provide a comprehensive starting point for working with the LLM-MCP platform. You can combine and extend these patterns to build more complex applications that leverage the full power of LLM-MCP's tool orchestration, vector operations, and model management capabilities.

For more advanced usage:

If you encounter any issues, refer to our Troubleshooting Guide.