UNPKG

@kpritam/gremlin-mcp

Version:

A Gremlin MCP server that allows for fetching status, schema, and querying using Gremlin for any Gremlin-compatible graph database (TypeScript implementation).

91 lines 3.05 kB
/** * Utility functions for MCP tool registration and handling. * Eliminates code duplication and provides consistent error handling. */ import { logger } from '../logger.js'; import { z } from 'zod'; /** * Creates a standardized text response for tools. */ export function createTextResponse(data) { const text = typeof data === 'string' ? data : JSON.stringify(data, null, 2); return { content: [ { type: 'text', text, }, ], }; } /** * Wraps a tool handler with consistent error handling and logging. */ export function withErrorHandling(toolName, handler) { return async (args, client) => { try { logger.debug(`Executing tool: ${toolName}`, { args }); const result = await handler(args, client); logger.debug(`Tool ${toolName} completed successfully`); return createTextResponse(result); } catch (error) { logger.error(`Tool ${toolName} failed`, { error, args }); // Return error information in a structured format const errorResponse = { success: false, message: `Tool ${toolName} failed`, error: error instanceof Error ? error.message : String(error), details: error instanceof Error ? error.stack : undefined, }; return createTextResponse(errorResponse); } }; } /** * Creates and registers a tool with standardized configuration. */ export function createTool(server, getGraphClient, config, handler) { const wrappedHandler = withErrorHandling(config.name, handler); server.registerTool(config.name, { title: config.title, description: config.description, inputSchema: config.inputSchema || {}, }, async (args) => { const graphClient = await getGraphClient(); return wrappedHandler(args, graphClient); }); logger.info(`Registered tool: ${config.name}`); } /** * Validates input against a schema and returns parsed result. */ export function validateInput(schema, input, toolName) { try { return schema.parse(input); } catch (error) { logger.error(`Input validation failed for tool ${toolName}`, { error, input }); throw new Error(`Invalid input for tool ${toolName}: ${error instanceof Error ? error.message : String(error)}`); } } /** * Common error types for tools. */ export class ToolError extends Error { toolName; details; constructor(toolName, message, details) { super(message); this.toolName = toolName; this.details = details; this.name = 'ToolError'; } } /** * Helper for creating simple tools that don't require input validation. */ export function createSimpleTool(server, getGraphClient, name, title, description, handler) { createTool(server, getGraphClient, { name, title, description }, async (_, client) => handler(client)); } //# sourceMappingURL=tool-helpers.js.map