Model Context Protocol Server - ABAP SDK

June 4, 2026 · View on GitHub

This documentation provides a comprehensive guide to the Model Context Protocol (MCP) Server SDK for ABAP. It explains how to install, configure, and implement custom MCP servers.

Table of Contents

Overview

The Model Context Protocol (MCP) Server SDK for ABAP allows you to create custom AI integration servers that can be accessed by MCP clients. The SDK provides:

  • A standardized interface for MCP communication
  • Base classes for quick implementation
  • Session handling capabilities
  • Tools for schema definition
  • JSON-RPC handling

With the MCP Server SDK, you can implement servers that provide:

  • Prompts for AI models
  • Access to resources (like files, database records, etc.)
  • Custom tools that AI models can call
  • Long-running background tasks with polling support
  • Autocomplete suggestions for prompt and resource arguments

Architecture

The MCP Server SDK follows a layered architecture that handles the communication between MCP clients and your custom business logic.

Component Interaction Diagram

graph TD
    Client[MCP Client] <-->|HTTP/JSON-RPC| ICF[ICF Node]
    ICF <--> Handler[ZCL_MCP_HTTP_HANDLER]
    Handler <--> Auth[Authorization Check]
    Handler <--> CORS[CORS Handling]
    Handler <--> JSONRPC[ZCL_MCP_JSONRPC]
    JSONRPC <--> ServerFactory[ZCL_MCP_SERVER_FACTORY]
    ServerFactory --> ServerImpl[Custom Server Implementation]
    ServerImpl -->|Inherits| ServerBase[ZCL_MCP_SERVER_BASE]
    ServerBase -->|Implements| ServerInterface[ZIF_MCP_SERVER]
    ServerImpl <--> SessionMgmt[Session Management]
    SessionMgmt --> Stateless[Stateless Mode]
    SessionMgmt --> MCPSession[MCP Session Mode]
    SessionMgmt --> ICFSession[ICF Session Mode]
    ServerImpl <--> SchemaBuilder[ZCL_MCP_SCHEMA_BUILDER]
    ServerImpl <--> SchemaDDIC[ZCL_MCP_SCHEMA_BUILDER_DDIC]
    ServerImpl <--> SchemaValidator[ZCL_MCP_SCHEMA_VALIDATOR]
    ServerImpl <--> Tasks[ZCL_MCP_TASKS]
    Tasks <--> TaskDB[(ZMCP_TASKS)]
    Tasks <--> TaskExecutor[ZIF_MCP_TASK_EXECUTOR]
    TaskExecutor --> BgJob[Background Job / RFC]
    ServerImpl <--> Logger[ZCL_MCP_LOGGER]
    ServerImpl <--> Config[ZCL_MCP_CONFIGURATION]

Key Components

  1. HTTP Handler (ZCL_MCP_HTTP_HANDLER)

    • Entry point for all HTTP requests
    • Handles authentication, CORS, and request routing
    • Delegates to JSON-RPC processor
  2. JSON-RPC Processor (ZCL_MCP_JSONRPC)

    • Parses JSON-RPC requests
    • Validates request structure
    • Routes to appropriate server method
    • Formats responses
  3. Server Factory (ZCL_MCP_SERVER_FACTORY)

    • Creates server instances based on configuration
    • Manages server lifecycle
  4. Server Base Class (ZCL_MCP_SERVER_BASE)

    • Abstract base class for all server implementations
    • Handles common functionality
    • Provides session management
  5. Session Management

    • Supports three modes: Stateless, MCP Session, and ICF Session
    • Persists data between requests when needed
  6. Schema Builder & Validator

    • Tools for defining and validating JSON schemas
    • ZCL_MCP_SCHEMA_BUILDER: fluent API for building schemas
    • ZCL_MCP_SCHEMA_BUILDER_DDIC: derives schemas automatically from DDIC structures
    • ZCL_MCP_SCHEMA_VALIDATOR: validates JSON input against a schema
  7. Task Manager (ZCL_MCP_TASKS)

    • Persists and manages the lifecycle of long-running background tasks
    • Used via ZIF_MCP_TASK_EXECUTOR to launch and cancel background jobs/RFCs
    • Supports status transitions: working → completed / failed / cancelled
    • For details see Tasks
  8. Configuration (ZCL_MCP_CONFIGURATION)

    • Manages server settings from database tables
    • Controls CORS, logging, and other behaviors

Request Flow

  1. Client sends HTTP request to ICF node
  2. HTTP Handler processes request headers and authentication
  3. JSON-RPC processor parses the request
  4. Server Factory creates or retrieves server instance
  5. Request is routed to appropriate handler method
  6. Server processes request and generates response
  7. Response is formatted and returned to client

This architecture provides a flexible foundation for implementing custom MCP servers while handling the complexities of the protocol, authentication, and session management.

Authorizations

The authorization object ZMCP_SRV is used to check if you area allowed to call a specific server. The fields ZMCP_AREA and ZMCP_SRV match the area and server in ZMCP_SERVERS table.

Installation

To install the MCP Server SDK, follow these steps:

  1. Import the SDK objects into your SAP system via abapGit
  2. Set up the ICF node for your server endpoint
    Create a new node e.g. zmcp with handler class zcl_mcp_http_handler
  3. Setup server configuration, e.g. create an entry for the stateless demo server zcl_mcp_demo_server_stateless

Maintenance

You can use the report zmcp_clear_mcp_sessions to get rid of outdated MCP sessions. Ideally run it regularly as a background job if you use MCP sessions.

Use the report zmcp_clear_mcp_tasks to remove outdated task records from ZMCP_TASKS. It deletes completed, failed, and cancelled tasks whose TTL has elapsed, terminal tasks without a TTL after the default retention period, and working tasks older than the maximum lifetime. Schedule it as a regular background job if you use the tasks feature.

Prerequisites

  • SAP NetWeaver 7.52 or higher for the main branch
  • SAP Netweaver 7.02 or higher for the downport branch (702) - not tested as I have no system below 7.50 available, open issues if required
  • Authorization to create and modify ABAP classes
  • Authorization to create ICF service nodes

Configuration

Server Configuration Table

Configure your MCP servers in the ZMCP_SERVERS table:

FieldDescription
AREALogical grouping for servers
SERVERServer identifier
CLASSImplementation class (must implement ZIF_MCP_SERVER or extend ZCL_MCP_SERVER_BASE)

Use the area to group your servers based on a well known structure in your company. This can e.g. be modules or end to end processes.

CORS Configuration

Configure CORS settings in the ZMCP_CONFIG table:

FieldDescription
CORS_MODECORS handling mode (Ignore, Check, or Enforce)

Ignore = no validation, Check = if Origin header is present it is validated against maintained origins, Enforce ensures that the Origin header is present and checks against maintained origins. For whitelisted origins, maintain entries in the ZMCP_ORIGINS table. Use * in area and/or server for generic whitelists.

Logging Configuration

Configure logging in the ZMCP_CONFIG table:

FieldDescription
LOG_LEVELLogging detail level
OBJECTApplication log object
SUBOBJECTApplication log subobject

Make sure to create the Object/Subobject in SLG0. By default no logging happens. Note in case of incorrect object and subobject loggin will fail silently and not dump the server.

Implementing Custom MCP Servers

To implement a custom MCP server, we strongly recommend extending ZCL_MCP_SERVER_BASE rather than directly implementing the ZIF_MCP_SERVER interface. This approach provides you with pre-implemented session handling and error management.

Basic Implementation Pattern

CLASS zcl_my_custom_server DEFINITION
  PUBLIC
  INHERITING FROM zcl_mcp_server_base
  FINAL
  CREATE PUBLIC.

  PUBLIC SECTION.
  PROTECTED SECTION.
    METHODS handle_initialize REDEFINITION.
    " Implement only the handlers you need
    METHODS handle_list_tools REDEFINITION.
    METHODS handle_call_tool REDEFINITION.
    " Other handlers...
  
  PRIVATE SECTION.
    " Your helper methods
ENDCLASS.

Minimal Implementation

At minimum, you must implement the HANDLE_INITIALIZE method to define your server's capabilities and GET_SESSION_MODE:

METHOD handle_initialize.
  response-result->set_capabilities( VALUE #(
    tools = VALUE #( enabled = abap_true )
  ) ).
  response-result->set_implementation( VALUE #(
    name        = `My Custom MCP Server`
    version     = `1.0.0`
    " Optional MCP 2025-11-25 fields:
    " title       = `Human-readable server title`
    " description = `Short server description`
    " website_url = `https://example.com`
    " icons       = ...
  ) ).
  response-result->set_instructions(
    `Instructions for the AI model on when to use this server...`
  ).
ENDMETHOD.

METHOD get_session_mode.
  result = zcl_mcp_session=>session_mode_stateless.
ENDMETHOD.

Session Management

The MCP Server SDK offers three session management modes:

ModeDescription
StatelessNo session management (stateless)
MCP SessionUses the custom MCP session handling mechanism via database
ICF SessionUses the standard ICF session management

Note that ICF session management leads to potentially high number of sessions if the clients do not properly close them. Also your MCP client must support handling the session cookies. MCP Sessions are an alternative lightweight mode allowing you to store certain values in the DB between calls. In general use Stateless where feasible.

MCP Session User Isolation

MCP sessions (mode M) are now bound to the user who created them. When a session is loaded, the framework verifies that ZMCP_SESSIONS-CREATED_BY matches sy-uname. If it does not match, a session_unknown error is returned (the same error as a missing session, to prevent user enumeration).

Breaking change on upgrade: The ZMCP_SESSIONS table has a new CREATED_BY column (NOT NULL). Existing session records will have an empty value in that field after the table conversion. Any active session created before this upgrade will therefore fail the user check and be rejected on the next request. Clients will receive a session error and must start a new session. To avoid unexpected client errors during a production deployment, run ZMCP_CLEAR_MCP_SESSIONS to delete all existing sessions immediately before activating the new code.

Core Components

ZCL_MCP_SERVER_BASE

Abstract base class for implementing MCP servers. It handles:

  • Session management
  • Error handling
  • Protocol conformance

ZIF_MCP_SERVER

Interface defining all required MCP server methods. The main methods include:

  • initialize - Server initialization and capability declaration
  • prompts_list - List available prompts
  • prompts_get - Get prompt details
  • resources_list - List available resources
  • resources_read - Read resource content
  • resources_templates_list - List resource templates
  • tools_list - List available tools
  • tools_call - Execute tool function
  • tasks_list - List background tasks
  • tasks_get - Get task status
  • tasks_result - Get task payload/result
  • tasks_cancel - Cancel a running task
  • completions_complete - Provide autocomplete suggestions for prompt/resource arguments
  • get_session_mode - Define session logic

ZIF_MCP_TYPES

Shared type definitions used across the SDK:

  • message_role / role_user / role_assistant constants
  • annotations — audience, priority, and last-modified metadata attachable to content, resources, and tools
  • icon — icon metadata (src, MIME type, sizes, theme) for tools, prompts, and resources
  • page_cursor — opaque pagination cursor used in all paginated requests/responses
  • task / task_list / task_list_result — task lifecycle types (MCP 2025-11-25)

Schema Builder

ZCL_MCP_SCHEMA_BUILDER creates JSON Schema definitions for tool input validation and output schemas with a fluent, chainable API:

DATA(schema) = NEW zcl_mcp_schema_builder( ).
schema->add_string( name = 'parameter' required = abap_true )
      ->add_integer( name = 'count' minimum = 1 )
      ->begin_object( name = 'options' )
          ->add_boolean( name = 'flag' )
      ->end_object( ).

Key features:

  • Define basic property types (string, number, integer, boolean)
  • Apply validation constraints (min/max length, value ranges, enums)
  • Create nested objects and arrays
  • Mark required properties

For details see Schema Builder.

DDIC Schema Builder

ZCL_MCP_SCHEMA_BUILDER_DDIC auto-generates a JSON Schema from an existing DDIC structure or table. This eliminates manual schema maintenance when ABAP data types are already defined in the Data Dictionary:

TRY.
    DATA(schema) = NEW zcl_mcp_schema_builder_ddic(
        structure_name  = 'SFLIGHT'
        field_overrides = VALUE #(
            ( field_path = 'carrid'  description = 'Airline code'   required = abap_true )
            ( field_path = 'connid'  description = 'Connection ID'  required = abap_true ) ) ).
    DATA(json) = schema->to_json( ).
  CATCH zcx_mcp_schema_ddic_error zcx_mcp_ajson_error INTO DATA(error).
    " Handle error
ENDTRY.

Field names and descriptions are derived from DDIC metadata automatically; use field_overrides to customize individual fields. Override paths are lowercase DDIC field paths.

For details see Schema Builder.

Schema Validator

ZCL_MCP_SCHEMA_VALIDATOR validates JSON data against schemas created with the Schema Builder:

" Create validator with a schema
DATA(validator) = NEW zcl_mcp_schema_validator( schema ).

" Validate JSON input
IF validator->validate( json_input ) = abap_false.
    " Get validation errors
    DATA(errors) = validator->get_errors( ).
    " Handle invalid input...
ENDIF.

Key features:

  • Verifies data types match schema definitions
  • Checks presence of required properties
  • Validates string lengths and pattern constraints
  • Ensures numeric values are within defined ranges
  • Validates array sizes and nested structures
  • Provides detailed error messages for validation failures

Completions

The completion/complete endpoint lets clients request autocomplete suggestions for prompt arguments and resource-template variables. Override handle_completions_complete in your server, parse the request with ZCL_MCP_REQ_COMPLETE, and return candidates via ZCL_MCP_RESP_COMPLETE. Declare the completions capability during initialization.

For details see Completions.

Demo Implementations

The SDK includes four demo implementations:

ZCL_MCP_DEMO_SERVER_STATELESS

A stateless MCP server demonstrating:

  • Simple prompt handling
  • Resource access
  • Tool implementation (server time, flight connection details, and async flight report task)

ZCL_MCP_DEMO_SERVER_MCPSESSION

Demonstrates MCP session handling with:

  • Session information tool
  • Incremental counter tool that persists state between calls
  • Asynchronous background task (start_slow_computation) launched via ZMCP_DEMO_BG_TASK report, demonstrating the full task lifecycle

ZCL_MCP_DEMO_SERVER_ICFSESSION

Demonstrates ICF session handling with:

  • Session information tool
  • Instance variables that persist state between calls

ZCL_MCP_DEMO_SERVER_DDIC

Demonstrates DDIC-based schema generation with:

  • Prompts (greet, joke)
  • Resources and resource templates backed by DDIC table data
  • Flight connection tool using ZCL_MCP_SCHEMA_BUILDER_DDIC to derive its input schema from the SPFLI DDIC structure

Demo Configuration

This is included in the repo. Delete if you don't want it.

AreaServiceClassSessionMode
demodemo_session_icfZCL_MCP_DEMO_SERVER_ICFSESSIONICF Stateful
demodemo_session_mcpZCL_MCP_DEMO_SERVER_MCPSESSIONMCP Session
demodemo_standardZCL_MCP_DEMO_SERVER_STATELESSNo Session
demodemo_ddicZCL_MCP_DEMO_SERVER_DDICNo Session

Usage/Clients

At the time of writing this clients supporting HTTP Streamable protocol are still extremely rare and most official MCP SDKs do not yet fully support it. The MCP Inspector is currently a recommended testing tool.

API Reference

Handler Methods

MethodDescription
handle_initializeRequired: Set up server capabilities
handle_list_promptsList available prompts
handle_get_promptRetrieve specific prompt details
handle_list_resourcesList available resources
handle_resources_readRead resource content
handle_list_res_tmplsList resource templates
handle_list_toolsList available tools
handle_call_toolExecute a tool
handle_cancel_taskOptional hook before the framework marks a task cancelled
handle_completions_completeReturn autocomplete suggestions for prompt/resource args

tasks_list, tasks_get, and tasks_result are implemented by ZCL_MCP_SERVER_BASE and delegate to ZCL_MCP_TASKS; custom servers normally only override handle_cancel_task when a background process needs an explicit stop signal.

Key Data Types

TypeDescription
initialize_responseServer capabilities and information
list_prompts_responseCollection of available prompts
get_prompt_responseDetails of a specific prompt
list_resources_responseCollection of available resources
resources_read_responseContent of a specific resource
list_tools_responseCollection of available tools
call_tool_responseResult of tool execution
list_tasks_responsePaginated list of background tasks
get_task_responseStatus of a single task
get_task_payload_responseResult payload of a completed task
cancel_task_responseConfirmation of task cancellation
complete_responseAutocomplete suggestions for a prompt/resource arg

Request/Response Classes

See the relevant subpages:

Server Properties

PropertyDescription
serverServer context information
configServer configuration
sessionSession handling (when enabled)

For more detailed information, examples, and advanced usage, refer to the individual component documentation pages.