Skip to main content
Glama
Raistlin82

SAP OData to MCP Server

by Raistlin82

UI Form Generator

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;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'validation and SAP Fiori styling' which adds some context, but fails to cover critical aspects like whether this is a read-only or mutation operation, authentication requirements, error handling, or what the output looks like (forms as code, UI components, etc.).

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose ('Creates dynamic forms for SAP entity operations') and adds key features ('with validation and SAP Fiori styling'). Every word earns its place with zero redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of a form-generation tool with no annotations and no output schema, the description is incomplete. It lacks information about the tool's behavior (e.g., mutation vs. read-only), output format, error conditions, or integration with sibling tools, leaving significant gaps for an agent to use it effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema, such as explaining relationships between entityType and fields, or providing examples. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Creates dynamic forms for SAP entity operations' with specific features like 'validation and SAP Fiori styling'. It uses a specific verb ('creates') and identifies the resource ('forms'), but doesn't explicitly distinguish it from sibling UI tools like ui-dashboard-composer or ui-workflow-builder, which prevents a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, context for form generation, or compare it to sibling tools like ui-dashboard-composer or ui-report-builder, leaving the agent without usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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