Skip to main content
Glama

CreateServiceDefinition

Create a new ABAP service definition in an SAP system. Provide a name and package; optionally add source code and activate after creation.

Instructions

Operation: Create. Subject: ServiceDefinition. Will be useful for creating service definition. Create a new ABAP service definition in SAP system. Creates the service definition object in initial state.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
service_definition_nameYesService definition name (e.g., ZSD_MY_SERVICE). Must follow SAP naming conventions (start with Z or Y).
descriptionNoService definition description. If not provided, service_definition_name will be used.
package_nameYesPackage name (e.g., ZOK_LOCAL, $TMP for local objects)
transport_requestNoTransport request number (e.g., E19K905635). Required for transportable packages.
source_codeNoService definition source code (optional). If not provided, a minimal template will be created.
activateNoActivate service definition after creation. Default: true.

Implementation Reference

  • Main handler function for CreateServiceDefinition MCP tool. Validates inputs (name, package, transport), creates an ABAP service definition via AdtClient, optionally activates it, and parses any activation warnings. Returns success/error response.
    export async function handleCreateServiceDefinition(
      context: HandlerContext,
      args: CreateServiceDefinitionArgs,
    ) {
      const { connection, logger } = context;
      try {
        // Validate required parameters
        if (!args?.service_definition_name) {
          return return_error(new Error('service_definition_name is required'));
        }
        if (!args?.package_name) {
          return return_error(new Error('package_name is required'));
        }
    
        // Validate transport_request: required for non-$TMP packages
        try {
          validateTransportRequest(args.package_name, args.transport_request);
        } catch (error) {
          return return_error(error as Error);
        }
    
        const typedArgs = args as CreateServiceDefinitionArgs;
    
        // Get connection from session context (set by ProtocolHandler)
        // Connection is managed and cached per session, with proper token refresh via AuthBroker
        const serviceDefinitionName =
          typedArgs.service_definition_name.toUpperCase();
    
        logger?.info(
          `Starting service definition creation: ${serviceDefinitionName}`,
        );
    
        try {
          // Create client
          const client = createAdtClient(connection, logger);
          const shouldActivate = typedArgs.activate !== false; // Default to true if not specified
          let activateResponse: any | undefined;
    
          // Validate
          await client.getServiceDefinition().validate({
            serviceDefinitionName,
            description: typedArgs.description || serviceDefinitionName,
          });
    
          // Create
          const createConfig: Partial<IServiceDefinitionConfig> &
            Pick<
              IServiceDefinitionConfig,
              'serviceDefinitionName' | 'packageName' | 'description'
            > = {
            serviceDefinitionName,
            description: typedArgs.description || serviceDefinitionName,
            packageName: typedArgs.package_name.toUpperCase(),
            transportRequest: typedArgs.transport_request,
            ...(typedArgs.source_code && { sourceCode: typedArgs.source_code }),
          };
    
          const createState = await client
            .getServiceDefinition()
            .create(createConfig);
          const createResult = createState.createResult;
    
          if (!createResult) {
            throw new Error(
              `Create did not return a response for service definition ${serviceDefinitionName}`,
            );
          }
    
          // Activate if requested
          if (shouldActivate) {
            const activateState = await client
              .getServiceDefinition()
              .activate({ serviceDefinitionName });
            activateResponse = activateState.activateResult;
          }
    
          // Parse activation warnings if activation was performed
          let activationWarnings: string[] = [];
          if (
            shouldActivate &&
            activateResponse &&
            typeof activateResponse.data === 'string' &&
            activateResponse.data.includes('<chkl:messages')
          ) {
            const parser = new XMLParser({
              ignoreAttributes: false,
              attributeNamePrefix: '@_',
            });
            const result = parser.parse(activateResponse.data);
            const messages = result?.['chkl:messages']?.msg;
            if (messages) {
              const msgArray = Array.isArray(messages) ? messages : [messages];
              activationWarnings = msgArray.map(
                (msg: any) =>
                  `${msg['@_type']}: ${msg.shortText?.txt || 'Unknown'}`,
              );
            }
          }
    
          logger?.info(
            `✅ CreateServiceDefinition completed successfully: ${serviceDefinitionName}`,
          );
    
          // Return success result
          const stepsCompleted = ['validate', 'create'];
          if (shouldActivate) {
            stepsCompleted.push('activate');
          }
    
          const result = {
            success: true,
            service_definition_name: serviceDefinitionName,
            package_name: typedArgs.package_name.toUpperCase(),
            transport_request: typedArgs.transport_request || null,
            type: 'SRVD/SRV',
            message: shouldActivate
              ? `Service Definition ${serviceDefinitionName} created and activated successfully`
              : `Service Definition ${serviceDefinitionName} created successfully (not activated)`,
            uri: `/sap/bc/adt/ddic/srvd/sources/${encodeSapObjectName(serviceDefinitionName)}`,
            steps_completed: stepsCompleted,
            activation_warnings:
              activationWarnings.length > 0 ? activationWarnings : undefined,
          };
    
          return return_response({
            data: JSON.stringify(result, null, 2),
            status: 200,
            statusText: 'OK',
            headers: {},
            config: {} as any,
          });
        } catch (error: any) {
          logger?.error(
            `Error creating service definition ${serviceDefinitionName}:`,
            error,
          );
    
          // Check if service definition already exists
          if (
            error.message?.includes('already exists') ||
            error.response?.status === 409
          ) {
            return return_error(
              new Error(
                `Service Definition ${serviceDefinitionName} already exists. Please delete it first or use a different name.`,
              ),
            );
          }
    
          const errorMessage = error.response?.data
            ? typeof error.response.data === 'string'
              ? error.response.data
              : JSON.stringify(error.response.data)
            : error.message || String(error);
    
          return return_error(
            new Error(`Failed to create service definition: ${errorMessage}`),
          );
        }
      } catch (error: any) {
        logger?.error('CreateServiceDefinition handler error:', error);
        return return_error(error);
      }
    }
  • TOOL_DEFINITION constant defining tool name ('CreateServiceDefinition'), availability, description, and inputSchema with properties: service_definition_name, description, package_name, transport_request, source_code, activate.
    export const TOOL_DEFINITION = {
      name: 'CreateServiceDefinition',
      available_in: ['onprem', 'cloud'] as const,
      description:
        'Operation: Create. Subject: ServiceDefinition. Will be useful for creating service definition. Create a new ABAP service definition in SAP system. Creates the service definition object in initial state.',
      inputSchema: {
        type: 'object',
        properties: {
          service_definition_name: {
            type: 'string',
            description:
              'Service definition name (e.g., ZSD_MY_SERVICE). Must follow SAP naming conventions (start with Z or Y).',
          },
          description: {
            type: 'string',
            description:
              'Service definition description. If not provided, service_definition_name will be used.',
          },
          package_name: {
            type: 'string',
            description: 'Package name (e.g., ZOK_LOCAL, $TMP for local objects)',
          },
          transport_request: {
            type: 'string',
            description:
              'Transport request number (e.g., E19K905635). Required for transportable packages.',
          },
          source_code: {
            type: 'string',
            description:
              'Service definition source code (optional). If not provided, a minimal template will be created.',
          },
          activate: {
            type: 'boolean',
            description:
              'Activate service definition after creation. Default: true.',
          },
        },
        required: ['service_definition_name', 'package_name'],
      },
    } as const;
  • TypeScript interface CreateServiceDefinitionArgs defining the typed arguments for the handler.
    interface CreateServiceDefinitionArgs {
      service_definition_name: string;
      description?: string;
      package_name: string;
      transport_request?: string;
      source_code?: string;
      activate?: boolean;
    }
  • Import of TOOL_DEFINITION and handleCreateServiceDefinition from the handler file into HighLevelHandlersGroup.
    import {
      TOOL_DEFINITION as CreateServiceDefinition_Tool,
      handleCreateServiceDefinition,
    } from '../../../handlers/service_definition/high/handleCreateServiceDefinition';
  • Registration of CreateServiceDefinition tool in the high-level handlers group with its tool definition and handler wrapped with context.
    {
      toolDefinition: CreateServiceDefinition_Tool,
      handler: withContext(handleCreateServiceDefinition),
    },
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 states that the object is created in 'initial state' but does not explain side effects, authentication needs, or what the default activation behavior is (though an 'activate' parameter exists). This is insufficient for a creation tool.

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

Conciseness3/5

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

The description is relatively short but includes redundant phrases like 'Operation: Create. Subject: ServiceDefinition.' The sentence 'Will be useful for creating service definition' is vague and unnecessary. It is not optimally structured, but not overly verbose.

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

Completeness3/5

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

Given no output schema and no annotations, the description provides a basic understanding of the tool's purpose. However, it does not elaborate on what 'initial state' means, the exact result of creation, or potential errors. It is adequate but not fully complete.

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?

The input schema already covers all 6 parameters with descriptions (100% coverage). The description adds no extra meaning beyond what is in the schema, so the baseline score of 3 is appropriate.

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

Purpose5/5

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

The description clearly states the action (Create) and the resource (ServiceDefinition). It uses specific verbs like 'Create a new ABAP service definition' and distinguishes from siblings such as GetServiceDefinition, UpdateServiceDefinition, and ActivateServiceDefinition.

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 does not provide any guidance on when to use this tool versus alternatives. There is no mention of prerequisites, context, or exclusions. The phrase 'Will be useful for creating service definition' is obvious and unhelpful.

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/fr0ster/mcp-abap-adt'

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