natural-query-builder
Convert natural language questions into structured OData queries for SAP S/4HANA or ECC systems, enabling conversational access to ERP data.
Instructions
Convert natural language to OData queries
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| naturalQuery | Yes | ||
| entityType | Yes | ||
| serviceId | Yes | ||
| userContext | No | User context |
Implementation Reference
- src/tools/ai-enhanced-tools.ts:55-103 (handler)Main handler function of the natural-query-builder tool. Takes natural language query, entityType, serviceId; creates mock entity metadata, calls aiQueryBuilder service to generate optimized OData query, returns execution URL and suggestions.async execute(params: any): Promise<any> { try { logger.debug('Processing natural language query', { query: params.naturalQuery, entityType: params.entityType, }); const mockEntityType = this.createMockEntityType(params.entityType); const result = await aiQueryBuilder.buildQueryFromNaturalLanguage( params.naturalQuery, mockEntityType, params.userContext ); const executionUrl = `${params.serviceId}/${result.optimizedQuery.url}`; const suggestions = [ `Try: "${this.generateSuggestion(params.naturalQuery, mockEntityType)}"`, 'Add time filters for better performance', 'Specify fields you need to optimize data transfer', ]; logger.info('Successfully generated natural query', { originalQuery: params.naturalQuery, optimizedUrl: result.optimizedQuery.url, confidence: result.optimizedQuery.confidence, }); return { success: true, result, executionUrl, suggestions, }; } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; logger.error('Natural query builder failed', { error: errorMessage }); return { success: false, error: errorMessage, suggestions: [ 'Try using simpler language', 'Specify the entity type more clearly', 'Check if the service is available', ], }; } }
- src/tools/ai-enhanced-tools.ts:24-53 (schema)Input schema definition for the natural-query-builder tool, specifying required naturalQuery, entityType, serviceId and optional userContext.inputSchema = { type: 'object' as const, properties: { naturalQuery: { type: 'string' as const, description: 'Natural language query (e.g., "Show me all pending invoices from this month with amounts over 1000 euros")', }, entityType: { type: 'string' as const, description: 'Target SAP entity type (e.g., "Invoice", "PurchaseOrder", "Customer")', }, serviceId: { type: 'string' as const, description: 'SAP service identifier', }, userContext: { type: 'object' as const, properties: { role: { type: 'string' as const }, businessContext: { type: 'string' as const }, preferredFields: { type: 'array' as const, items: { type: 'string' as const }, }, }, }, }, required: ['naturalQuery', 'entityType', 'serviceId'], };
- Supporting helper: createMockEntityType generates mock SAP EntityType metadata from entity name, adding specific properties for Invoice/Customer or generic.createMockEntityType(entityTypeName: string): EntityType { const baseProperties = [ { name: 'ID', type: 'Edm.String', nullable: false }, { name: 'CreatedDate', type: 'Edm.DateTime', nullable: true }, { name: 'Status', type: 'Edm.String', nullable: true }, ]; let specificProperties: any[] = []; if (entityTypeName.toLowerCase().includes('invoice')) { specificProperties = [ { name: 'InvoiceNumber', type: 'Edm.String', nullable: false }, { name: 'Amount', type: 'Edm.Double', nullable: false }, { name: 'DueDate', type: 'Edm.DateTime', nullable: true }, { name: 'CustomerName', type: 'Edm.String', nullable: true }, { name: 'Currency', type: 'Edm.String', nullable: true }, ]; } else if (entityTypeName.toLowerCase().includes('customer')) { specificProperties = [ { name: 'CustomerNumber', type: 'Edm.String', nullable: false }, { name: 'Name', type: 'Edm.String', nullable: false }, { name: 'Email', type: 'Edm.String', nullable: true }, { name: 'Address', type: 'Edm.String', nullable: true }, { name: 'Country', type: 'Edm.String', nullable: true }, ]; } else { specificProperties = [ { name: 'Name', type: 'Edm.String', nullable: true }, { name: 'Description', type: 'Edm.String', nullable: true }, { name: 'Value', type: 'Edm.Double', nullable: true }, ]; } return { name: entityTypeName, namespace: 'SAP', entitySet: `${entityTypeName}Set`, keys: specificProperties.length > 0 ? [specificProperties[0].name] : ['ID'], properties: [...baseProperties, ...specificProperties], navigationProperties: [], // Add missing properties for EntityType compatibility creatable: true, updatable: true, deletable: true, addressable: true, }; }
- Supporting helper: generateSuggestion provides example query suggestions based on entity type for user guidance.private generateSuggestion(originalQuery: string, entityType: EntityType): string { const suggestions = [ `Show me recent ${entityType.name.toLowerCase()}s from this week`, `Find ${entityType.name.toLowerCase()}s with high values`, `List all pending ${entityType.name.toLowerCase()}s sorted by date`, `Get ${entityType.name.toLowerCase()}s created today`, ]; return suggestions[Math.floor(Math.random() * suggestions.length)]; }
- src/tools/ai-enhanced-tools.ts:462-467 (registration)Registration: Exports array of tool instances including natural-query-builder for use in MCP server tool registry.export const aiEnhancedTools = [ new NaturalQueryBuilderTool(), new SmartDataAnalysisTool(), new QueryPerformanceOptimizerTool(), new BusinessProcessInsightsTool(), ];