Skip to main content
Glama
Raistlin82

SAP OData to MCP Server

by Raistlin82

ui-form-generator

Generate dynamic forms with SAP Fiori styling for creating, editing, or viewing SAP entity data. Configure custom fields and validation for SAP OData operations.

Instructions

Creates dynamic forms for SAP entity operations with validation and SAP Fiori styling

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
entityTypeYesSAP entity type for the form
formTypeYesType of form to generate
fieldsNoCustom form fields configuration

Implementation Reference

  • Core handler function that validates input, checks authorization, fetches SAP entity metadata, generates form fields and configuration, renders UI form using component library, enhances with SAP-specific CSS/JS, and returns the form as content and JSON resource.
    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 input schema defining parameters for form generation: 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")
    };
  • Registers the 'ui-form-generator' tool on the MCP server with title, description, input schema, and handler function that delegates to handleFormGeneration.
        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 field configurations from SAP entity metadata properties or use provided custom fields, mapping types, setting labels, validation, etc.
    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;
    }

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Raistlin82/btp-sap-odata-to-mcp-server-optimized'

If you have feedback or need assistance with the MCP directory API, please join our Discord server