UNPKG

@gianpieropuleo/radix-mcp-server

Version:

A Model Context Protocol (MCP) server for Radix UI libraries (Themes, Primitives, Colors), providing AI assistants with access to component source code, installation guides, and design tokens.

64 lines (63 loc) 2.56 kB
import { CallToolRequestSchema, ListToolsRequestSchema, } from "@modelcontextprotocol/sdk/types.js"; import { logError, logInfo } from "../utils/logger.js"; import { validateAndSanitizeParams } from "../utils/validation.js"; import { generateMCPHandlers } from "./adapter.js"; // Generate tool handlers and definitions const toolHandlers = generateMCPHandlers(); /** * Wrapper function to handle requests with simple error handling */ async function handleRequest(method, params, handler) { try { // Validate and sanitize input parameters const validatedParams = validateAndSanitizeParams(method, params); // Execute the handler directly const result = await handler(validatedParams); return result; } catch (error) { logError(`Error in ${method}`, error); throw error; } } /** * Sets up all request handlers for the MCP server * Following MCP SDK 1.16.0 best practices for handler registration * @param server - The MCP server instance */ export const setupHandlers = (server, tools) => { logInfo("Setting up request handlers..."); // List available tools server.setRequestHandler(ListToolsRequestSchema, async (request) => { return await handleRequest("list_tools", request.params, async () => { // Return the Radix tools that are registered with the server const registeredTools = Object.values(tools).map((tool) => ({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, })); return { tools: registeredTools }; }); }); // Tool request Handler - executes the requested tool with provided parameters server.setRequestHandler(CallToolRequestSchema, async (request) => { return await handleRequest("call_tool", request.params, async (validatedParams) => { const { name, arguments: params } = validatedParams; if (!name || typeof name !== "string") { throw new Error("Tool name is required"); } const handler = toolHandlers[name]; if (!handler) { throw new Error(`Tool not found: ${name}`); } // Execute handler directly const result = await Promise.resolve(handler(params || {})); return result; }); }); // Add global error handler server.onerror = (error) => { logError("MCP server error", error); }; logInfo("Handlers setup complete"); };