mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-28 04:59:52 +01:00
Merge 154 upstream commits with the 12-commit westernization stack, preserving upstream features (theme refactor, knowledge base, device calling, web search) while keeping downstream provider policy, English defaults, and westernized surfaces.
525 lines
19 KiB
JavaScript
525 lines
19 KiB
JavaScript
import { log } from '../../utils/logger.js?v=0205';
|
|
|
|
// ==========================================
|
|
// MCP tool management
|
|
// ==========================================
|
|
|
|
// Global state
|
|
let mcpTools = [];
|
|
let mcpEditingIndex = null;
|
|
let mcpProperties = [];
|
|
let websocket = null; // Set externally.
|
|
|
|
/**
|
|
* Set the WebSocket instance.
|
|
* @param {WebSocket} ws - WebSocket connection instance.
|
|
*/
|
|
export function setWebSocket(ws) {
|
|
websocket = ws;
|
|
}
|
|
|
|
/**
|
|
* Initialize MCP tools.
|
|
*/
|
|
export async function initMcpTools() {
|
|
// Load the default tool definitions.
|
|
const defaultMcpTools = await fetch("js/config/default-mcp-tools.json").then(res => res.json());
|
|
const savedTools = localStorage.getItem('mcpTools');
|
|
if (savedTools) {
|
|
try {
|
|
const parsedTools = JSON.parse(savedTools);
|
|
// Merge defaults with user-saved tools while keeping custom tools.
|
|
const defaultToolNames = new Set(defaultMcpTools.map(t => t.name));
|
|
// Add custom tools that do not exist in the default set.
|
|
parsedTools.forEach(tool => {
|
|
if (!defaultToolNames.has(tool.name)) {
|
|
defaultMcpTools.push(tool);
|
|
}
|
|
});
|
|
mcpTools = defaultMcpTools;
|
|
} catch (e) {
|
|
log('Failed to load saved MCP tools. Falling back to defaults.', 'warning');
|
|
mcpTools = [...defaultMcpTools];
|
|
}
|
|
} else {
|
|
mcpTools = [...defaultMcpTools];
|
|
}
|
|
renderMcpTools();
|
|
setupMcpEventListeners();
|
|
}
|
|
|
|
/**
|
|
* Render the tool list.
|
|
*/
|
|
function renderMcpTools() {
|
|
const container = document.getElementById('mcpToolsContainer');
|
|
const countSpan = document.getElementById('mcpToolsCount');
|
|
if (!container) {
|
|
return; // Container not found, skip rendering
|
|
}
|
|
if (countSpan) {
|
|
countSpan.textContent = `${mcpTools.length} tool${mcpTools.length === 1 ? '' : 's'}`;
|
|
}
|
|
if (mcpTools.length === 0) {
|
|
container.innerHTML = '<div style="text-align: center; padding: 30px; color: #999;">No tools yet. Click the button below to add one.</div>';
|
|
return;
|
|
}
|
|
container.innerHTML = mcpTools.map((tool, index) => {
|
|
const paramCount = tool.inputSchema.properties ? Object.keys(tool.inputSchema.properties).length : 0;
|
|
const requiredCount = tool.inputSchema.required ? tool.inputSchema.required.length : 0;
|
|
const hasMockResponse = tool.mockResponse && Object.keys(tool.mockResponse).length > 0;
|
|
return `
|
|
<div class="mcp-tool-card">
|
|
<div class="mcp-tool-header">
|
|
<div class="mcp-tool-name">${tool.name}</div>
|
|
<div class="mcp-tool-actions">
|
|
<button class="mcp-edit-btn" onclick="window.mcpModule.editMcpTool(${index})">
|
|
✏️ Edit
|
|
</button>
|
|
<button class="mcp-delete-btn" onclick="window.mcpModule.deleteMcpTool(${index})">
|
|
🗑️ Delete
|
|
</button>
|
|
</div>
|
|
</div>
|
|
<div class="mcp-tool-description">${tool.description}</div>
|
|
<div class="mcp-tool-info">
|
|
<div class="mcp-tool-info-row">
|
|
<span class="mcp-tool-info-label">Parameters:</span>
|
|
<span class="mcp-tool-info-value">${paramCount}${requiredCount > 0 ? ` (${requiredCount} required)` : ''}</span>
|
|
</div>
|
|
<div class="mcp-tool-info-row">
|
|
<span class="mcp-tool-info-label">Mock response:</span>
|
|
<span class="mcp-tool-info-value">${hasMockResponse ? '✅ Configured: ' + JSON.stringify(tool.mockResponse) : '⚪ Default response'}</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}).join('');
|
|
}
|
|
|
|
/**
|
|
* Render the parameter list.
|
|
*/
|
|
function renderMcpProperties() {
|
|
const container = document.getElementById('mcpPropertiesContainer');
|
|
const emptyState = document.getElementById('mcpEmptyState');
|
|
if (!container) {
|
|
return; // Container not found, skip rendering
|
|
}
|
|
if (mcpProperties.length === 0) {
|
|
if (emptyState) {
|
|
emptyState.style.display = 'block';
|
|
}
|
|
container.innerHTML = '';
|
|
return;
|
|
}
|
|
if (emptyState) {
|
|
emptyState.style.display = 'none';
|
|
}
|
|
container.innerHTML = mcpProperties.map((prop, index) => `
|
|
<div class="mcp-property-card" onclick="window.mcpModule.editMcpProperty(${index})">
|
|
<div class="mcp-property-row-label">
|
|
<span class="mcp-property-label">Name</span>
|
|
<span class="mcp-property-value">${prop.name}${prop.required ? ' <span class="mcp-property-required-badge">[Required]</span>' : ''}</span>
|
|
</div>
|
|
<div class="mcp-property-row-label">
|
|
<span class="mcp-property-label">Type</span>
|
|
<span class="mcp-property-value">${getTypeLabel(prop.type)}</span>
|
|
</div>
|
|
<div class="mcp-property-row-label">
|
|
<span class="mcp-property-label">Description</span>
|
|
<span class="mcp-property-value">${prop.description || '-'}</span>
|
|
</div>
|
|
<div class="mcp-property-row-action">
|
|
<button class="mcp-property-delete-btn" onclick="event.stopPropagation(); window.mcpModule.deleteMcpProperty(${index})">Delete</button>
|
|
</div>
|
|
</div>
|
|
`).join('');
|
|
}
|
|
|
|
/**
|
|
* Get the display label for a type.
|
|
*/
|
|
function getTypeLabel(type) {
|
|
const typeMap = {
|
|
'string': 'String',
|
|
'integer': 'Integer',
|
|
'number': 'Number',
|
|
'boolean': 'Boolean',
|
|
'array': 'Array',
|
|
'object': 'Object'
|
|
};
|
|
return typeMap[type] || type;
|
|
}
|
|
|
|
/**
|
|
* Add a parameter by opening the parameter editor.
|
|
*/
|
|
function addMcpProperty() {
|
|
openPropertyModal();
|
|
}
|
|
|
|
/**
|
|
* Edit a parameter by opening the parameter editor.
|
|
*/
|
|
function editMcpProperty(index) {
|
|
openPropertyModal(index);
|
|
}
|
|
|
|
/**
|
|
* Open the parameter editor.
|
|
*/
|
|
function openPropertyModal(index = null) {
|
|
const form = document.getElementById('mcpPropertyForm');
|
|
const title = document.getElementById('mcpPropertyModalTitle');
|
|
document.getElementById('mcpPropertyIndex').value = index !== null ? index : -1;
|
|
|
|
if (index !== null) {
|
|
const prop = mcpProperties[index];
|
|
title.textContent = 'Edit Parameter';
|
|
document.getElementById('mcpPropertyName').value = prop.name;
|
|
document.getElementById('mcpPropertyType').value = prop.type || 'string';
|
|
document.getElementById('mcpPropertyMinimum').value = prop.minimum !== undefined ? prop.minimum : '';
|
|
document.getElementById('mcpPropertyMaximum').value = prop.maximum !== undefined ? prop.maximum : '';
|
|
document.getElementById('mcpPropertyDescription').value = prop.description || '';
|
|
document.getElementById('mcpPropertyRequired').checked = prop.required || false;
|
|
} else {
|
|
title.textContent = 'Add Parameter';
|
|
form.reset();
|
|
document.getElementById('mcpPropertyName').value = `param_${mcpProperties.length + 1}`;
|
|
document.getElementById('mcpPropertyType').value = 'string';
|
|
document.getElementById('mcpPropertyMinimum').value = '';
|
|
document.getElementById('mcpPropertyMaximum').value = '';
|
|
document.getElementById('mcpPropertyDescription').value = '';
|
|
document.getElementById('mcpPropertyRequired').checked = false;
|
|
}
|
|
|
|
updatePropertyRangeVisibility();
|
|
document.getElementById('mcpPropertyModal').style.display = 'flex';
|
|
}
|
|
|
|
/**
|
|
* Close the parameter editor.
|
|
*/
|
|
function closePropertyModal() {
|
|
document.getElementById('mcpPropertyModal').style.display = 'none';
|
|
}
|
|
|
|
/**
|
|
* Update the visibility of the numeric range inputs.
|
|
*/
|
|
function updatePropertyRangeVisibility() {
|
|
const type = document.getElementById('mcpPropertyType').value;
|
|
const rangeGroup = document.getElementById('mcpPropertyRangeGroup');
|
|
if (type === 'integer' || type === 'number') {
|
|
rangeGroup.style.display = 'block';
|
|
} else {
|
|
rangeGroup.style.display = 'none';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle parameter form submission.
|
|
*/
|
|
function handlePropertySubmit(e) {
|
|
e.preventDefault();
|
|
const index = parseInt(document.getElementById('mcpPropertyIndex').value);
|
|
const name = document.getElementById('mcpPropertyName').value.trim();
|
|
const type = document.getElementById('mcpPropertyType').value;
|
|
const minimum = document.getElementById('mcpPropertyMinimum').value;
|
|
const maximum = document.getElementById('mcpPropertyMaximum').value;
|
|
const description = document.getElementById('mcpPropertyDescription').value.trim();
|
|
const required = document.getElementById('mcpPropertyRequired').checked;
|
|
|
|
// Reject duplicate parameter names.
|
|
const isDuplicate = mcpProperties.some((p, i) => i !== index && p.name === name);
|
|
if (isDuplicate) {
|
|
alert('A parameter with this name already exists. Please choose a different name.');
|
|
return;
|
|
}
|
|
|
|
const propData = {
|
|
name,
|
|
type,
|
|
description,
|
|
required
|
|
};
|
|
|
|
// Preserve min/max constraints for numeric types.
|
|
if (type === 'integer' || type === 'number') {
|
|
if (minimum !== '') {
|
|
propData.minimum = parseFloat(minimum);
|
|
}
|
|
if (maximum !== '') {
|
|
propData.maximum = parseFloat(maximum);
|
|
}
|
|
}
|
|
|
|
if (index >= 0) {
|
|
mcpProperties[index] = propData;
|
|
} else {
|
|
mcpProperties.push(propData);
|
|
}
|
|
|
|
renderMcpProperties();
|
|
closePropertyModal();
|
|
}
|
|
|
|
/**
|
|
* Delete a parameter.
|
|
*/
|
|
function deleteMcpProperty(index) {
|
|
mcpProperties.splice(index, 1);
|
|
renderMcpProperties();
|
|
}
|
|
|
|
/**
|
|
* Register event listeners.
|
|
*/
|
|
function setupMcpEventListeners() {
|
|
const panel = document.getElementById('mcpToolsPanel');
|
|
const addBtn = document.getElementById('addMcpToolBtn');
|
|
const modal = document.getElementById('mcpToolModal');
|
|
const closeBtn = document.getElementById('closeMcpModalBtn');
|
|
const cancelBtn = document.getElementById('cancelMcpBtn');
|
|
const form = document.getElementById('mcpToolForm');
|
|
const addPropertyBtn = document.getElementById('addMcpPropertyBtn');
|
|
|
|
// Parameter editor elements.
|
|
const propertyModal = document.getElementById('mcpPropertyModal');
|
|
const closePropertyBtn = document.getElementById('closeMcpPropertyModalBtn');
|
|
const cancelPropertyBtn = document.getElementById('cancelMcpPropertyBtn');
|
|
const propertyForm = document.getElementById('mcpPropertyForm');
|
|
const propertyTypeSelect = document.getElementById('mcpPropertyType');
|
|
|
|
// Return early if required elements don't exist (e.g., in test environment)
|
|
if (!panel || !addBtn || !modal || !closeBtn || !cancelBtn || !form || !addPropertyBtn) {
|
|
return;
|
|
}
|
|
addBtn.addEventListener('click', () => openMcpModal());
|
|
closeBtn.addEventListener('click', closeMcpModal);
|
|
cancelBtn.addEventListener('click', closeMcpModal);
|
|
addPropertyBtn.addEventListener('click', addMcpProperty);
|
|
form.addEventListener('submit', handleMcpSubmit);
|
|
|
|
// Parameter editor events.
|
|
if (propertyModal && closePropertyBtn && cancelPropertyBtn && propertyForm && propertyTypeSelect) {
|
|
closePropertyBtn.addEventListener('click', closePropertyModal);
|
|
cancelPropertyBtn.addEventListener('click', closePropertyModal);
|
|
propertyForm.addEventListener('submit', handlePropertySubmit);
|
|
propertyTypeSelect.addEventListener('change', updatePropertyRangeVisibility);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Open the MCP tool modal.
|
|
*/
|
|
function openMcpModal(index = null) {
|
|
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
|
|
if (isConnected) {
|
|
alert('You cannot edit tools while the WebSocket connection is active.');
|
|
return;
|
|
}
|
|
mcpEditingIndex = index;
|
|
const errorContainer = document.getElementById('mcpErrorContainer');
|
|
errorContainer.innerHTML = '';
|
|
if (index !== null) {
|
|
document.getElementById('mcpModalTitle').textContent = 'Edit Tool';
|
|
const tool = mcpTools[index];
|
|
document.getElementById('mcpToolName').value = tool.name;
|
|
document.getElementById('mcpToolDescription').value = tool.description;
|
|
document.getElementById('mcpMockResponse').value = tool.mockResponse ? JSON.stringify(tool.mockResponse, null, 2) : '';
|
|
mcpProperties = [];
|
|
const schema = tool.inputSchema;
|
|
if (schema.properties) {
|
|
Object.keys(schema.properties).forEach(key => {
|
|
const prop = schema.properties[key];
|
|
mcpProperties.push({
|
|
name: key,
|
|
type: prop.type || 'string',
|
|
minimum: prop.minimum,
|
|
maximum: prop.maximum,
|
|
description: prop.description || '',
|
|
required: schema.required && schema.required.includes(key)
|
|
});
|
|
});
|
|
}
|
|
} else {
|
|
document.getElementById('mcpModalTitle').textContent = 'Add Tool';
|
|
document.getElementById('mcpToolForm').reset();
|
|
mcpProperties = [];
|
|
}
|
|
renderMcpProperties();
|
|
document.getElementById('mcpToolModal').style.display = 'flex';
|
|
}
|
|
|
|
/**
|
|
* Close the MCP tool modal.
|
|
*/
|
|
function closeMcpModal() {
|
|
document.getElementById('mcpToolModal').style.display = 'none';
|
|
mcpEditingIndex = null;
|
|
document.getElementById('mcpToolForm').reset();
|
|
mcpProperties = [];
|
|
document.getElementById('mcpErrorContainer').innerHTML = '';
|
|
}
|
|
|
|
/**
|
|
* Handle tool form submission.
|
|
*/
|
|
function handleMcpSubmit(e) {
|
|
e.preventDefault();
|
|
const errorContainer = document.getElementById('mcpErrorContainer');
|
|
errorContainer.innerHTML = '';
|
|
const name = document.getElementById('mcpToolName').value.trim();
|
|
const description = document.getElementById('mcpToolDescription').value.trim();
|
|
const mockResponseText = document.getElementById('mcpMockResponse').value.trim();
|
|
// Reject duplicate tool names.
|
|
const isDuplicate = mcpTools.some((tool, index) => tool.name === name && index !== mcpEditingIndex);
|
|
if (isDuplicate) {
|
|
showMcpError('A tool with this name already exists. Please choose a different name.');
|
|
return;
|
|
}
|
|
// Parse the mock response payload.
|
|
let mockResponse = null;
|
|
if (mockResponseText) {
|
|
try {
|
|
mockResponse = JSON.parse(mockResponseText);
|
|
} catch (e) {
|
|
showMcpError('The mock response is not valid JSON: ' + e.message);
|
|
return;
|
|
}
|
|
}
|
|
// Build the input schema.
|
|
const inputSchema = { type: "object", properties: {}, required: [] };
|
|
mcpProperties.forEach(prop => {
|
|
const propSchema = { type: prop.type };
|
|
if (prop.description) {
|
|
propSchema.description = prop.description;
|
|
}
|
|
if ((prop.type === 'integer' || prop.type === 'number')) {
|
|
if (prop.minimum !== undefined && prop.minimum !== '') {
|
|
propSchema.minimum = prop.minimum;
|
|
}
|
|
if (prop.maximum !== undefined && prop.maximum !== '') {
|
|
propSchema.maximum = prop.maximum;
|
|
}
|
|
}
|
|
inputSchema.properties[prop.name] = propSchema;
|
|
if (prop.required) {
|
|
inputSchema.required.push(prop.name);
|
|
}
|
|
});
|
|
if (inputSchema.required.length === 0) {
|
|
delete inputSchema.required;
|
|
}
|
|
const tool = { name, description, inputSchema, mockResponse };
|
|
if (mcpEditingIndex !== null) {
|
|
mcpTools[mcpEditingIndex] = tool;
|
|
log(`Updated tool: ${name}`, 'success');
|
|
} else {
|
|
mcpTools.push(tool);
|
|
log(`Added tool: ${name}`, 'success');
|
|
}
|
|
saveMcpTools();
|
|
renderMcpTools();
|
|
closeMcpModal();
|
|
}
|
|
|
|
/**
|
|
* Show a modal error.
|
|
*/
|
|
function showMcpError(message) {
|
|
const errorContainer = document.getElementById('mcpErrorContainer');
|
|
errorContainer.innerHTML = `<div class="mcp-error">${message}</div>`;
|
|
}
|
|
|
|
/**
|
|
* Edit a tool.
|
|
*/
|
|
function editMcpTool(index) {
|
|
openMcpModal(index);
|
|
}
|
|
|
|
/**
|
|
* Delete a tool.
|
|
*/
|
|
function deleteMcpTool(index) {
|
|
const isConnected = websocket && websocket.readyState === WebSocket.OPEN;
|
|
if (isConnected) {
|
|
alert('You cannot edit tools while the WebSocket connection is active.');
|
|
return;
|
|
}
|
|
if (confirm(`Delete tool "${mcpTools[index].name}"?`)) {
|
|
const toolName = mcpTools[index].name;
|
|
mcpTools.splice(index, 1);
|
|
saveMcpTools();
|
|
renderMcpTools();
|
|
log(`Deleted tool: ${toolName}`, 'info');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Persist tools to local storage.
|
|
*/
|
|
function saveMcpTools() {
|
|
localStorage.setItem('mcpTools', JSON.stringify(mcpTools));
|
|
}
|
|
|
|
/**
|
|
* Get the tool list.
|
|
*/
|
|
export function getMcpTools() {
|
|
return mcpTools.map(tool => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema }));
|
|
}
|
|
|
|
/**
|
|
* Execute a tool invocation.
|
|
*/
|
|
export async function executeMcpTool(toolName, toolArgs) {
|
|
const tool = mcpTools.find(t => t.name === toolName);
|
|
if (!tool) {
|
|
log(`Tool not found: ${toolName}`, 'error');
|
|
return { success: false, error: `Unknown tool: ${toolName}` };
|
|
}
|
|
|
|
// Handle the photo capture tool.
|
|
if (toolName === 'self_camera_take_photo') {
|
|
if (typeof window.takePhoto === 'function') {
|
|
const question = toolArgs && toolArgs.question ? toolArgs.question : 'Describe what you see in the photo.';
|
|
log(`Capturing photo: ${question}`, 'info');
|
|
const result = await window.takePhoto(question);
|
|
return result;
|
|
} else {
|
|
log('Photo capture is not available.', 'warning');
|
|
return { success: false, error: 'The camera is not running or does not support photo capture.' };
|
|
}
|
|
}
|
|
|
|
// Use the mock response when one is configured.
|
|
if (tool.mockResponse) {
|
|
// Replace template variables.
|
|
let responseStr = JSON.stringify(tool.mockResponse);
|
|
// Replace ${paramName} variables.
|
|
if (toolArgs) {
|
|
Object.keys(toolArgs).forEach(key => {
|
|
const regex = new RegExp(`\\$\\{${key}\\}`, 'g');
|
|
responseStr = responseStr.replace(regex, toolArgs[key]);
|
|
});
|
|
}
|
|
try {
|
|
const response = JSON.parse(responseStr);
|
|
log(`Tool ${toolName} completed successfully with mock response: ${responseStr}`, 'success');
|
|
return response;
|
|
} catch (e) {
|
|
log(`Failed to parse the mock response: ${e.message}`, 'error');
|
|
return tool.mockResponse;
|
|
}
|
|
}
|
|
// Fall back to the default success payload.
|
|
log(`Tool ${toolName} completed successfully with the default response.`, 'success');
|
|
return { success: true, message: `Tool ${toolName} completed successfully`, tool: toolName, arguments: toolArgs };
|
|
}
|
|
|
|
// Expose global handlers used by inline HTML events.
|
|
window.mcpModule = { addMcpProperty, editMcpProperty, deleteMcpProperty, editMcpTool, deleteMcpTool };
|