import type { AppState } from '@features/app-state/AppState';
import type { TextContent } from '@modelcontextprotocol/sdk/types.js';
import { getNextOrInitHexId } from '@shared/id-generator/getNextOrInitHexId';
import { McpToolError } from '@shared/mcp-tool/McpToolError';
import type { GenerateUniqueIdInput } from './GenerateUniqueIdInputSchema';
type GenerateUniqueIdMcpToolHandlerParams = {
params: GenerateUniqueIdInput;
appState: AppState;
};
/**
* Handler for the generateUniqueId MCP tool
* Returns text content with the generated unique IDs
*/
export async function generateUniqueIdMcpToolHandler({
params,
appState,
}: GenerateUniqueIdMcpToolHandlerParams): Promise<TextContent[] | McpToolError> {
try {
const { count = 1 } = params;
// Validate count range
const normalizedCount = Math.max(1, Math.min(32, Math.floor(count)));
// Generate the requested number of unique IDs
const uniqueIds: string[] = [];
for (let i = 0; i < normalizedCount; i += 1) {
uniqueIds.push(await getNextOrInitHexId(appState.idCounterFile));
}
// Return text response
return [
{
type: 'text',
text: `Generated ${String(normalizedCount)} unique ID(s):\n${uniqueIds.join('\n')}`,
},
];
} catch (error) {
// Handle any unexpected errors
console.error('Error in generateUniqueId tool:', error);
if (error instanceof Error) {
return new McpToolError(error.message);
}
return new McpToolError('An unexpected error occurred in the generateUniqueId tool');
}
}