Files
mcp-quantum/src/tools/hardware-tools.ts
2025-10-08 02:57:03 +02:00

446 líneas
13 KiB
TypeScript

/**
* Hardware Backend Tools for MCP Server
* Provides tools for managing quantum execution targets and hardware backends
*/
import { Tool } from '@modelcontextprotocol/sdk/types.js';
import { SetTargetSchema, QuantumBackends } from '../types/index.js';
import { getPythonBridge } from '../bridge/python-bridge.js';
import { Logger } from '../utils/logger.js';
const logger = new Logger('HardwareBackendTools');
/**
* Tool for setting quantum execution target
*/
export const setQuantumTargetTool: Tool = {
name: 'set_quantum_target',
description: 'Set the quantum execution target (simulator or hardware backend)',
inputSchema: {
type: 'object',
properties: {
target: {
type: 'string',
description: 'Quantum target name',
enum: Object.keys(QuantumBackends)
},
configuration: {
type: 'object',
description: 'Target-specific configuration options',
properties: {
shots: { type: 'integer', minimum: 1, maximum: 100000 },
optimization_level: { type: 'integer', minimum: 0, maximum: 3 },
api_key: { type: 'string', description: 'API key for hardware providers' },
url: { type: 'string', description: 'Custom endpoint URL' },
device: { type: 'string', description: 'Specific device name' },
noise_model: { type: 'string', description: 'Noise model for simulation' },
error_mitigation: { type: 'boolean', description: 'Enable error mitigation' }
}
}
},
required: ['target']
}
};
/**
* Tool for listing available quantum backends
*/
export const listQuantumBackendsTool: Tool = {
name: 'list_quantum_backends',
description: 'List all available quantum backends and their capabilities',
inputSchema: {
type: 'object',
properties: {
category: {
type: 'string',
enum: ['all', 'simulators', 'hardware'],
default: 'all',
description: 'Filter backends by category'
},
detailed: {
type: 'boolean',
default: false,
description: 'Include detailed information about each backend'
}
}
}
};
/**
* Tool for getting platform information
*/
export const getPlatformInfoTool: Tool = {
name: 'get_platform_info',
description: 'Get information about the current quantum platform and available resources',
inputSchema: {
type: 'object',
properties: {}
}
};
/**
* Tool for testing backend connectivity
*/
export const testBackendConnectivityTool: Tool = {
name: 'test_backend_connectivity',
description: 'Test connectivity to quantum hardware providers',
inputSchema: {
type: 'object',
properties: {
backend: {
type: 'string',
description: 'Backend to test',
enum: Object.keys(QuantumBackends)
},
credentials: {
type: 'object',
description: 'Credentials for the backend',
properties: {
api_key: { type: 'string' },
url: { type: 'string' },
username: { type: 'string' },
password: { type: 'string' }
}
}
},
required: ['backend']
}
};
/**
* Tool for GPU acceleration configuration
*/
export const configureGpuAccelerationTool: Tool = {
name: 'configure_gpu_acceleration',
description: 'Configure GPU acceleration for quantum simulations',
inputSchema: {
type: 'object',
properties: {
enable: {
type: 'boolean',
description: 'Enable or disable GPU acceleration'
},
device_id: {
type: 'integer',
minimum: 0,
description: 'GPU device ID to use'
},
memory_limit: {
type: 'number',
description: 'GPU memory limit in GB'
},
target: {
type: 'string',
enum: ['qpp-gpu', 'density-matrix-gpu'],
default: 'qpp-gpu',
description: 'GPU-accelerated target'
}
},
required: ['enable']
}
};
/**
* Implementation functions
*/
export async function handleSetQuantumTarget(input: any) {
try {
const bridge = getPythonBridge();
const response = await bridge.setTarget(input.target, input.configuration);
if (response.success) {
logger.info(`Set quantum target to: ${input.target}`);
let output = `Successfully set quantum target to: ${input.target}\n\n`;
output += `Description: ${QuantumBackends[input.target as keyof typeof QuantumBackends]}\n`;
if (input.configuration) {
output += `\nConfiguration:\n`;
for (const [key, value] of Object.entries(input.configuration)) {
if (key !== 'api_key') { // Don't log sensitive information
output += ` ${key}: ${value}\n`;
} else {
output += ` ${key}: [REDACTED]\n`;
}
}
}
return {
content: [
{
type: 'text' as const,
text: output
}
]
};
} else {
throw new Error(response.error || 'Failed to set quantum target');
}
} catch (error) {
logger.error('Error setting quantum target:', error);
return {
content: [
{
type: 'text' as const,
text: `Error setting quantum target: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
}
export async function handleListQuantumBackends(input: any) {
try {
let output = `Available Quantum Backends:\n\n`;
const simulators = ['qpp-cpu', 'qpp-gpu', 'density-matrix-cpu', 'tensor-network'];
const hardware = ['ionq', 'quantinuum', 'quantum_machines', 'infleqtion', 'iqm', 'oqc', 'pasqal'];
if (input.category === 'all' || input.category === 'simulators') {
output += `🖥️ Simulators:\n`;
for (const backend of simulators) {
if (backend in QuantumBackends) {
output += `${backend}: ${QuantumBackends[backend as keyof typeof QuantumBackends]}\n`;
if (input.detailed) {
output += ` - Local execution\n`;
output += ` - GPU support: ${backend.includes('gpu') ? 'Yes' : 'No'}\n`;
output += ` - Max qubits: ${backend.includes('tensor') ? '40+' : '32'}\n`;
output += `\n`;
}
}
}
output += `\n`;
}
if (input.category === 'all' || input.category === 'hardware') {
output += `🔬 Hardware Providers:\n`;
for (const backend of hardware) {
if (backend in QuantumBackends) {
output += `${backend}: ${QuantumBackends[backend as keyof typeof QuantumBackends]}\n`;
if (input.detailed) {
output += ` - Remote execution\n`;
output += ` - Authentication required\n`;
output += ` - Variable queue times\n`;
output += `\n`;
}
}
}
}
output += `\nTo set a target, use: set_quantum_target\n`;
output += `For GPU acceleration, ensure CUDA is installed and use GPU-enabled targets.\n`;
return {
content: [
{
type: 'text' as const,
text: output
}
]
};
} catch (error) {
logger.error('Error listing quantum backends:', error);
return {
content: [
{
type: 'text' as const,
text: `Error listing quantum backends: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
}
export async function handleGetPlatformInfo(input: any) {
try {
const bridge = getPythonBridge();
const response = await bridge.getPlatformInfo();
if (response.success) {
const result = response.result || {};
let output = `Quantum Platform Information:\n\n`;
output += `Platform Name: ${result.platform_name || 'Unknown'}\n`;
output += `Number of QPUs: ${result.num_qpus || 'Unknown'}\n`;
output += `Is Simulator: ${result.is_simulator !== undefined ? result.is_simulator : 'Unknown'}\n`;
output += `Is Remote: ${result.is_remote !== undefined ? result.is_remote : 'Unknown'}\n`;
// Add system information
output += `\nSystem Information:\n`;
output += `Node.js Version: ${process.version}\n`;
output += `Platform: ${process.platform}\n`;
output += `Architecture: ${process.arch}\n`;
// GPU information (if available)
const cudaDevice = process.env.CUDA_VISIBLE_DEVICES;
if (cudaDevice) {
output += `CUDA Visible Devices: ${cudaDevice}\n`;
}
return {
content: [
{
type: 'text' as const,
text: output
}
]
};
} else {
throw new Error(response.error || 'Failed to get platform information');
}
} catch (error) {
logger.error('Error getting platform information:', error);
return {
content: [
{
type: 'text' as const,
text: `Error getting platform information: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
}
export async function handleTestBackendConnectivity(input: any) {
try {
const backend = input.backend;
let output = `Testing connectivity to ${backend}...\n\n`;
// Check if it's a simulator (always available)
const simulators = ['qpp-cpu', 'qpp-gpu', 'density-matrix-cpu', 'tensor-network'];
if (simulators.includes(backend)) {
output += `${backend} is available (local simulator)\n`;
if (backend.includes('gpu')) {
const cudaDevice = process.env.CUDA_VISIBLE_DEVICES;
if (cudaDevice) {
output += `✅ CUDA device available: ${cudaDevice}\n`;
} else {
output += `⚠️ CUDA_VISIBLE_DEVICES not set, using default GPU\n`;
}
}
} else {
// Hardware backend - check credentials
output += `🔗 ${backend} is a hardware provider\n`;
if (input.credentials?.api_key) {
output += `✅ API key provided\n`;
} else {
output += `❌ API key required for ${backend}\n`;
}
if (input.credentials?.url) {
output += `✅ Custom URL provided: ${input.credentials.url}\n`;
}
output += `\nNote: Actual connectivity testing requires valid credentials and active connection.\n`;
}
return {
content: [
{
type: 'text' as const,
text: output
}
]
};
} catch (error) {
logger.error('Error testing backend connectivity:', error);
return {
content: [
{
type: 'text' as const,
text: `Error testing backend connectivity: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
}
export async function handleConfigureGpuAcceleration(input: any) {
try {
let output = `GPU Acceleration Configuration:\n\n`;
if (input.enable) {
output += `✅ Enabling GPU acceleration\n`;
output += `Target: ${input.target || 'qpp-gpu'}\n`;
if (input.device_id !== undefined) {
output += `GPU Device ID: ${input.device_id}\n`;
// Update environment variable
process.env.CUDA_VISIBLE_DEVICES = input.device_id.toString();
}
if (input.memory_limit) {
output += `Memory Limit: ${input.memory_limit} GB\n`;
}
// Attempt to set GPU target
try {
const bridge = getPythonBridge();
const response = await bridge.setTarget(input.target || 'qpp-gpu');
if (response.success) {
output += `✅ Successfully configured GPU target\n`;
} else {
output += `❌ Failed to set GPU target: ${response.error}\n`;
}
} catch (error) {
output += `❌ Error setting GPU target: ${error}\n`;
}
output += `\nNote: Ensure NVIDIA drivers and CUDA toolkit are installed for GPU acceleration.\n`;
} else {
output += `❌ Disabling GPU acceleration\n`;
output += `Falling back to CPU simulation\n`;
try {
const bridge = getPythonBridge();
await bridge.setTarget('qpp-cpu');
output += `✅ Set target to CPU simulator\n`;
} catch (error) {
output += `❌ Error setting CPU target: ${error}\n`;
}
}
return {
content: [
{
type: 'text' as const,
text: output
}
]
};
} catch (error) {
logger.error('Error configuring GPU acceleration:', error);
return {
content: [
{
type: 'text' as const,
text: `Error configuring GPU acceleration: ${error instanceof Error ? error.message : String(error)}`
}
],
isError: true
};
}
}
// Export all tools
export const hardwareBackendTools: Tool[] = [
setQuantumTargetTool,
listQuantumBackendsTool,
getPlatformInfoTool,
testBackendConnectivityTool,
configureGpuAccelerationTool
];