Add MCP Execute Endpoint with Secure Authentication and Tool Execution

- Implemented `/mcp/execute` endpoint for tool execution
- Added token-based authentication using HASS_TOKEN
- Supports dynamic tool selection and parameter passing
- Includes comprehensive error handling for unauthorized access and tool not found scenarios
- Provides flexible execution workflow with detailed response handling
This commit is contained in:
jango-blockchained
2025-02-01 12:29:42 +01:00
parent 431a68d690
commit 9037cffcfe

View File

@@ -49,6 +49,41 @@ app.get('/mcp', (_req, res) => {
res.json(MCP_SCHEMA); res.json(MCP_SCHEMA);
}); });
// MCP execute endpoint - requires authentication
app.post('/mcp/execute', async (req, res) => {
try {
// Get token from Authorization header
const token = req.headers.authorization?.replace('Bearer ', '');
if (!token || token !== HASS_TOKEN) {
return res.status(401).json({
success: false,
message: 'Unauthorized - Invalid token'
});
}
const { tool: toolName, parameters } = req.body;
// Find the requested tool
const tool = tools.find(t => t.name === toolName);
if (!tool) {
return res.status(404).json({
success: false,
message: `Tool '${toolName}' not found`
});
}
// Execute the tool with the provided parameters
const result = await tool.execute(parameters);
res.json(result);
} catch (error) {
res.status(500).json({
success: false,
message: error instanceof Error ? error.message : 'Unknown error occurred'
});
}
});
// Health check endpoint // Health check endpoint
app.get('/health', (req, res) => { app.get('/health', (req, res) => {
res.json({ res.json({