ui-form-generator
Generate dynamic forms for SAP entity operations with validation and SAP Fiori styling to create, edit, or view data through conversational interfaces.
Instructions
Creates dynamic forms for SAP entity operations with validation and SAP Fiori styling
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| entityType | Yes | SAP entity type for the form | |
| fields | No | Custom form fields configuration | |
| formType | Yes | Type of form to generate |
Implementation Reference
- Main handler function that processes the tool arguments, validates input, fetches entity metadata, generates form fields and configuration, creates UI components, enhances with SAP styling/JS, and returns the form response.private async handleFormGeneration(args: unknown): Promise<any> { try { // Validate input parameters const params = z.object(UIFormGeneratorSchema).parse(args); this.logger.info(`π¨ Generating UI form for entity: ${params.entityType}, operation: ${params.operation}`); // Check authentication and authorization const authCheck = await this.checkUIAccess('ui.forms'); if (!authCheck.hasAccess) { return { content: [{ type: "text", text: `β Authorization denied: ${authCheck.reason || 'Access denied for UI form generation'}\n\nRequired scope: ui.forms` }] }; } // Step 1: Get entity metadata from SAP const entityMetadata = await this.getEntityMetadata(params.entityType); // Step 2: Generate form fields from metadata const formFields = await this.generateFormFields(entityMetadata, params); // Step 3: Create form configuration const formConfig: FormConfig = { entityType: params.entityType, operation: params.operation, layout: params.layout || 'vertical', theme: params.theme || 'sap_horizon', customFields: formFields, validation: params.validation || this.generateDefaultValidation(formFields) }; // Step 4: Generate form UI const formResult = await this.componentLibrary.generateForm(formConfig); // Step 5: Add SAP-specific enhancements const enhancedResult = await this.enhanceFormResult(formResult, params); // Step 6: Prepare response const response = this.createFormResponse(enhancedResult, formConfig); this.logger.info(`β UI form generated successfully for ${params.entityType}`); return { content: [ { type: "text", text: `# SAP ${params.entityType} Form (${params.operation})\n\n` + `Form generated successfully with ${formFields.length} fields.\n\n` + `## Form Features:\n` + `- Layout: ${formConfig.layout}\n` + `- Theme: ${formConfig.theme}\n` + `- Validation: ${Object.keys(formConfig.validation || {}).length} rules\n` + `- Fields: ${formFields.map(f => f.name).join(', ')}\n\n` + `## Usage:\n` + `Embed this form in your SAP application or use via MCP client.\n\n` + `## Technical Details:\n` + `- Form ID: ${response.formId}\n` + `- Entity Type: ${params.entityType}\n` + `- Operation: ${params.operation}` }, { type: "resource", data: response, mimeType: "application/json" } ] }; } catch (error) { this.logger.error(`β Failed to generate UI form`, error as Error); return { content: [{ type: "text", text: `β Failed to generate UI form: ${(error as Error).message}` }] }; } }
- Zod schema defining the input parameters for the ui-form-generator tool, including entityType, operation, customFields, layout, theme, and validation rules.const UIFormGeneratorSchema = { entityType: z.string().describe("SAP entity type (e.g., 'Customer', 'Product', 'Order')"), operation: z.enum(['create', 'update', 'search']).describe("Form operation type"), customFields: z.array(z.object({ name: z.string(), label: z.string(), type: z.enum(['text', 'number', 'date', 'datetime', 'boolean', 'select', 'multiselect']), required: z.boolean().optional(), readonly: z.boolean().optional(), hidden: z.boolean().optional(), placeholder: z.string().optional(), defaultValue: z.any().optional(), options: z.array(z.object({ key: z.string(), text: z.string(), description: z.string().optional() })).optional(), validation: z.object({ required: z.boolean().optional(), pattern: z.string().optional(), minLength: z.number().optional(), maxLength: z.number().optional(), min: z.number().optional(), max: z.number().optional() }).optional() })).optional().describe("Custom field configurations"), layout: z.enum(['vertical', 'horizontal', 'grid']).optional().describe("Form layout type"), theme: z.enum(['sap_horizon', 'sap_fiori_3']).optional().describe("SAP UI theme"), validation: z.record(z.object({ required: z.boolean().optional(), pattern: z.string().optional(), minLength: z.number().optional(), maxLength: z.number().optional(), min: z.number().optional(), max: z.number().optional() })).optional().describe("Field validation rules") };
- src/tools/ui/ui-form-generator-tool.ts:80-110 (registration)Registration of the 'ui-form-generator' tool on the MCP server, including title, description, input schema, and handler function.public async register(): Promise<void> { this.mcpServer.registerTool( "ui-form-generator", { title: "UI Form Generator", description: `Generate interactive forms for SAP entities with validation and data binding. Features: - Dynamic form generation based on SAP entity metadata - Built-in validation with SAP-specific rules - SAP Fiori design language compliance - Support for all SAP field types (text, number, date, boolean, select) - Custom field configurations and layouts - Real-time validation feedback - Responsive design for mobile and desktop Required scope: ui.forms Examples: - Create customer form: {"entityType": "Customer", "operation": "create"} - Search products with custom fields: {"entityType": "Product", "operation": "search", "customFields": [...]} - Update order with validation: {"entityType": "Order", "operation": "update", "validation": {...}}`, inputSchema: UIFormGeneratorSchema }, async (args: Record<string, unknown>) => { return await this.handleFormGeneration(args); } ); this.logger.info("β UI Form Generator tool registered successfully"); }
- Helper function to generate form fields from SAP entity metadata or custom fields, mapping types, setting validation, labels, and placeholders.private async generateFormFields(metadata: any, params: any): Promise<FieldConfig[]> { const fields: FieldConfig[] = []; // Use custom fields if provided if (params.customFields && params.customFields.length > 0) { return params.customFields; } // Generate fields from metadata if (metadata.properties) { for (const [propertyName, property] of Object.entries(metadata.properties)) { const prop = property as any; const field: FieldConfig = { name: propertyName, label: this.formatFieldLabel(propertyName), type: this.mapSAPTypeToFieldType(prop.type), required: !prop.nullable, readonly: prop.key === true, // Primary keys are readonly in update forms hidden: this.shouldHideField(propertyName, params.operation), placeholder: this.generatePlaceholder(propertyName, prop.type), validation: this.generateFieldValidation(prop) }; // Add options for enum types if (prop.enum && prop.enum.length > 0) { field.options = prop.enum.map((value: string) => ({ key: value, text: value })); } fields.push(field); } } return fields; }
- Helper to retrieve (mocked) SAP entity metadata used for dynamic form field generation.private async getEntityMetadata(entityType: string): Promise<any> { try { // Mock metadata for now - in real implementation this would call SAP services const mockMetadata = { properties: { ID: { type: 'Edm.String', key: true, nullable: false }, Name: { type: 'Edm.String', nullable: false, maxLength: 100 }, Email: { type: 'Edm.String', nullable: true, maxLength: 255 }, Phone: { type: 'Edm.String', nullable: true, maxLength: 20 }, CreatedAt: { type: 'Edm.DateTime', nullable: false }, Active: { type: 'Edm.Boolean', nullable: false } } }; this.logger.debug(`Using mock metadata for entity: ${entityType}`); return mockMetadata; throw new Error(`Entity type '${entityType}' not found in available SAP services`); } catch (error) { this.logger.error(`Failed to get metadata for entity ${entityType}`, error as Error); throw error; } }