Skip to main content
Glama
Raistlin82

SAP OData to MCP Server

by Raistlin82

Natural Query Builder

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
NameRequiredDescriptionDefault
naturalQueryYes
entityTypeYes
serviceIdYes
userContextNoUser context

Implementation Reference

  • 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',
          ],
        };
      }
    }
  • 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)];
    }
  • 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(),
    ];
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure but offers minimal information. It states what the tool does ('convert') but doesn't describe how it behaves: no details about error handling, performance characteristics, authentication requirements, or what the output looks like (especially problematic since there's no output schema). This is inadequate for a tool with complex parameters.

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 perfectly concise at just 5 words, front-loading the core functionality without any wasted words. Every element earns its place, making it immediately scannable and understandable despite its brevity.

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 (4 parameters including a nested object, 25% schema coverage, no output schema, and no annotations), the description is insufficiently complete. It doesn't explain what the tool returns, how to interpret results, or provide enough context about parameters and behavior. This leaves too many unknowns for effective tool invocation.

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

Parameters2/5

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

Schema description coverage is only 25% (only 'userContext' has a description), and the description doesn't compensate by explaining any parameters. It doesn't clarify what 'naturalQuery', 'entityType', or 'serviceId' mean, nor does it provide examples or context for the 'userContext' object. For a tool with 4 parameters including a nested object, this leaves significant gaps in understanding.

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 function: converting natural language to OData queries. It uses specific verbs ('convert') and identifies the resource ('OData queries'), making the purpose immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'sap-smart-query' or 'smart-data-analysis' which might have overlapping functionality, preventing 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. There's no mention of prerequisites, typical use cases, or comparisons with sibling tools like 'sap-smart-query' or 'smart-data-analysis' that might handle similar query-related tasks. This leaves the agent guessing about appropriate contexts.

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