
arc-1
SAP ABAP development for AI coding agents: the ARC-1 MCP server (read/write/search/activate/lint/diagnose ABAP via ADT) plus best-practice skills for RAP, CDS, ABAP Unit, clean-core, and UI5 modernization. Read-only by default.
- GitHub stars
- 264
Install
/plugin install arc-1@arc-1Run it inside Claude Code after adding the marketplace with /plugin marketplace add arc-mcp/arc-1.
Contents
Discovered from sourceSkills 22
Analyze Chat Session
Analyze the current conversation's tool calls, responses, errors, and overall approach to produce a structured feedback report. The goal is continuous improvement of MCP tool usage patterns, prompt strategies, and ARC-1 server capabilities.
This skill is introspective — the LLM analyzes its own chat session (the conversation you're currently in, or a referenced one) and generates actionable feedback.
PRIVACY NOTICE — READ FIRST
Before using this skill's output outside the current system (e.g., pasting into a GitHub issue, sharing in a chat), the user MUST review it for sensitive data.
The analysis MUST NOT contain:
- SAP system URLs, hostnames, IP addresses, or ports
- Usernames, passwords, API keys, tokens, or credentials
- Client numbers, system IDs (SID), or environment identifiers
- Real business data (customer names, order numbers, financial values, employee data)
- File paths that reveal internal infrastructure (home directories, mount paths)
- Transport request numbers or package names that reveal internal naming conventions
- Any content from SAP table previews or SQL query results containing business data
The LLM must actively redact these from the output, replacing them with generic placeholders like <SAP_HOST>, <USERNAME>, <OBJECT_NAME>, <TABLE_DATA_REDACTED>, etc.
After generating the report, remind the user: "Please review this report for any remaining sensitive information before sharing it outside your organization."
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Output format | issue (GitHub issue-ready) | Most actionable format |
| Severity filter | All levels | Don't miss anything |
| Focus area | Entire session | Comprehensive analysis |
| Sensitive data | Redact all (see Privacy Notice) | Safe by default |
Proceed immediately with Smart Defaults when triggered. No questions needed.
Input
The user triggers this skill at any point during (or after) a conversation. No additional input is required — the LLM analyzes the current chat context. Proceed immediately with Smart Defaults.
Optionally, the user may specify:
- Focus area — e.g., "focus on the write operations" or "focus on the search failures"
- Output format —
issue(GitHub issue-ready),internal(detailed, for internal review), orsummary(brief, 1 paragraph) - Severity filter — only report issues above a threshold (e.g., "only blockers")
Phase 1: Catalog the Session
Walk through the entire conversation and extract a structured catalog. For each turn, note:
1a. Identify the Goal
What was the user trying to accomplish? Categorize it:
| Goal Category | Examples |
|---|---|
| Read / Explore | Read source code, understand a class, explore dependencies |
| Search / Discover | Find objects by name, search source code, locate implementations |
| Write / Modify | Create objects, update source, edit methods, batch operations |
| Diagnose / Debug | Syntax check, unit tests, ATC, short dumps, traces |
| Navigate / Understand | Find definition, find references, code completion |
| Query / Data | Table preview, freestyle SQL, data inspection |
| Context / Architecture | Dependency graphs, usage analysis, API contracts |
| Activate / Deploy | Activate objects, manage transports |
| Lint / Quality | Run linter, fix lint issues, check rules |
1b. Catalog Tool Calls
For each MCP tool call in the session, record:
| Field | What to capture |
|---|---|
| Tool | Which of the 11 tools was called (SAPRead, SAPSearch, etc.) |
| Operation | The specific action/type/include (e.g., SAPRead type=CLAS format=structured) |
| Intent | What information was the LLM trying to get? |
| Result | success, error, partial, empty, redundant |
| Error type | If failed: not_found, auth, safety, network, validation, btp_unsupported, session, other |
| Tokens | Rough estimate: was the response small (< 1KB), medium (1-10KB), or large (> 10KB)? |
| Necessary? | Was this call necessary, or could the info have been obtained differently? |
1c. Identify Patterns
Look for these anti-patterns:
| Pattern | Description | Impact |
|---|---|---|
| Shotgun search | Multiple broad searches before narrowing | Wasted tokens and time |
| Missing SAPContext | Reading dependencies one-by-one instead of using SAPContext | 5-10x more calls than needed |
| Unstructured class read | Using plain SAPRead for a class instead of format=structured | Misses metadata, requires extra calls for includes |
| Retry without change | Repeating the same failing call without modifying parameters | Pure waste |
| Wrong type guess | Using wrong object type, then searching to find the right one | Could use SAPSearch first |
| Ignored error hints | Error response contains a hint (e.g., "use SAPSearch") but LLM didn't follow it | Missed recovery path |
| Redundant reads | Reading the same object multiple times in one session | Could cache/reuse from earlier response |
| Over-fetching | Reading entire objects when only a method or section was needed | Wasted tokens (use method param or edit_method) |
| Missing method listing | Modifying a class without first getting method="*" to understand the API | Blind modifications |
| Wrong action sequence | e.g., trying to activate before saving, or writing without reading first | Procedural error |
| Ignored BTP constraints | Attempting on-prem-only operations on BTP system | Known limitation, should check SAPManage features first |
Phase 2: Assess What Worked
2a. Successful Strategies
Identify and highlight things that worked well:
- Efficient tool selection — chose the right tool on the first try
- Good parameter usage — used
format=structured,include=elements,method="*", etc. - Effective error recovery — followed error hints, switched strategies after failures
- Context-first approach — used SAPContext/SAPSearch before diving into reads
- Batch operations — used batch_create or batch activate where appropriate
- Method surgery — used
edit_methodinstead of full class rewrite
2b. What Partially Worked
Identify approaches that eventually succeeded but were inefficient:
- How many extra calls were needed?
- What was the corrective action?
- Could the first attempt have succeeded with different parameters?
2c. What Failed
Identify approaches that never worked:
- Was the information actually available through a different path?
- Was it a system limitation (BTP, permissions, missing feature)?
- Was it a tool limitation that should be reported?
Phase 3: Generate Improvement Suggestions
3a. For the LLM (Prompt/Approach Improvements)
Suggestions the user can feed back into system prompts or skill instructions:
- Strategy improvements — "Start with SAPSearch before SAPRead when object type is uncertain"
- Parameter optimizations — "Use format=structured for class reads to reduce call count"
- Sequence improvements — "Read method listing before attempting method surgery"
- Recovery patterns — "When SAPContext fails for FUNC, pass the group= parameter explicitly"
3b. For ARC-1 (Server/Tool Improvements)
Suggestions that should become GitHub issues for the ARC-1 project:
| Category | Example |
|---|---|
| Missing operation | "No way to read message class text by message number" |
| Poor error message | "404 on FUNC doesn't suggest using SAPSearch to find the function group" |
| Missing parameter | "SAPRead for DDLS should support reading specific annotations" |
| Performance | "SAPContext depth=2 timed out for large dependency graphs" |
| BTP gap | "Cannot read service binding details on BTP" |
| Documentation | "Tool description doesn't mention that method='*' lists all methods" |
| Safety false positive | "Legitimate read operation blocked by safety check" |
| Caching opportunity | "Same object read 4 times — server should hint about SAPContext caching" |
3c. For the User (Workflow Improvements)
Suggestions for the user's workflow:
- "Provide the object type for live usage lookups to avoid an extra resolution call"
- "Use the explain-abap-code skill first to understand objects before modifying them"
- "Provide object type when possible to avoid search round-trips"
3d. Delivery Triage (Quick Wins vs Planned Work)
For every recommendation, classify delivery scope explicitly:
| Bucket | Definition |
|---|---|
| Quick Win (This Session) | Low-risk prompt/skill/doc tweak that can be implemented immediately without new backend primitives |
| Needs Plan + Implementation Phase | Requires code changes, new ADT integration, schema/tool contract updates, or live SAP regression testing |
Output two lists:
- Quick wins to execute now (ordered by leverage)
- Planned items (grouped into the minimum number of implementation plans)
This triage section is mandatory in issue and internal outputs.
Phase 4: Produce the Report
Format: issue (Default — GitHub Issue Ready)
Generate a report structured for creating a GitHub issue. Use this template:
## Session Analysis: <brief goal description>
### Goal
<1-2 sentences: what the user was trying to accomplish>
### Approach Summary
<3-5 bullet points: high-level steps taken>
### Tool Call Statistics
- Total calls: N
- Successful: N (N%)
- Failed: N (N%)
- Redundant/unnecessary: N (N%)
- Tools used: SAPRead (N), SAPSearch (N), SAPWrite (N), ...
### What Worked Well
- <bullet points of effective strategies>
### What Didn't Work
- <bullet points with error classification>
- **Error**: <redacted error summary>
- **Root cause**: <analysis>
- **Better approach**: <suggestion>
### Suggested ARC-1 Improvements
#### <Improvement 1 Title>
**Category**: Missing operation | Poor error message | Missing parameter | ...
**Severity**: blocker | major | minor | enhancement
**Description**: <what should change and why>
**Reproduction**: <generic steps, NO sensitive data>
#### <Improvement 2 Title>
...
### Delivery Triage
- **Quick Wins (this chat):**
- <item>
- **Needs Plan + Implementation Phase:**
- <item>
- <item>
### Prompt Strategy Recommendations
- <numbered list of approach improvements for future sessions>
---
*Generated by analyze-chat-session skill. **Review for sensitive data before sharing.***
Format: internal (Detailed Internal Review)
Same as issue but includes:
- Full tool call catalog table (with redacted parameters)
- Token usage estimates per call
- Sequence diagram of the call flow
- Detailed anti-pattern analysis with specific turn references
Format: summary (Brief)
A single paragraph summarizing: goal, outcome, top 2 things that worked, top 2 things that didn't, and the single most impactful improvement suggestion.
Phase 5: Offer Next Steps
After presenting the report, offer:
- "Create GitHub issues?" — For each suggested ARC-1 improvement, offer to draft a GitHub issue body (still requires user review before posting)
- "Refine a specific finding?" — Dive deeper into one particular issue
- "Retry the failed approach?" — If the analysis reveals a better strategy, offer to try it now
- "Save as skill feedback?" — If the analysis reveals patterns that should be encoded in a skill, offer to update the relevant
.claude/commands/*.mdfile
Reference: ARC-1 Tool Capabilities Quick Reference
Use this reference to assess whether the LLM used the right tools. This is a concise mapping of common goals to optimal tool usage.
Read Operations (SAPRead)
| Object Type | Key Parameters | Notes |
|---|---|---|
| CLAS | format=structured (metadata+all includes), method="*" (list methods), method="name" (single method source), include=testclasses|definitions|implementations|macros | Always prefer format=structured for initial read |
| DDLS | include=elements (field listing) | Field list is essential for understanding CDS views |
| FUNC | group=<FUGR> (required if not cached), expand_includes=true (full group source) | Group resolution is a common failure point |
| SRVB | Returns parsed binding info | Not raw DDL |
| TABLE_QUERY | columns, where, maxRows | Filtered data preview; sqlFilter here is refused |
| TABLE_CONTENTS | maxRows | Unfiltered data preview; its sqlFilter fails on 758/816 — subject to blockData safety |
Search (SAPSearch)
searchType=object— by name/wildcardsearchType=source_code— full-text (may be unavailable on some systems)
Write Sequence
- Read first (understand current state)
SAPWrite action=createoraction=updateoraction=edit_methodSAPActivate(single or batch withobjects[])SAPDiagnose action=syntaxoraction=unittestto verify
Context & Navigation
SAPContext action=deps— dependency graph (preferred over manual reads)SAPContext action=usages— live reverse dependencies from SAPSAPNavigate action=definition— go-to-definition (needs URI + line/col + source)SAPNavigate action=references— where-used
Common Error Recovery Paths
| Error | Recovery |
|---|---|
| 404 Not Found | → SAPSearch to verify name/type |
| FUNC without group | → SAPSearch for function name, extract group from result |
| BTP type not supported | → Check BTP_HINTS in error, use equivalent cloud type |
| Source search unavailable | → Use SAPQuery or object search instead |
| SAPContext usages fails | → Use SAPNavigate references as fallback |
| Activation fails | → Read activation error, fix source, retry |
| Lock conflict | → Object locked by another user, wait or use different object |
Error Handling
| Situation | How to Handle |
|---|---|
| Very short session (< 3 tool calls) | Produce a brief summary, note that limited data makes analysis less useful |
| No tool calls in session | Report that no MCP tool usage was detected; suggest this skill is meant for sessions with SAP operations |
| All calls succeeded | Focus the report on efficiency and optimization opportunities |
| All calls failed | Focus on root cause analysis and whether the goal was achievable with current capabilities |
| Mixed results | Full analysis with emphasis on the failure→recovery patterns |
| Session used non-ARC-1 tools | Catalog those separately; focus ARC-1 analysis on the SAP-related calls |
Notes
When to Use This Skill
- After a complex debugging or development session
- When a new tool pattern was discovered through trial and error
- When multiple approaches failed and you want to document what was learned
- When preparing feedback for ARC-1 improvement
- When onboarding and wanting to capture learning patterns
What This Skill Does NOT Do
- No automated issue creation — it drafts issue content, but the user must review and create
- No system access — this skill only reads the chat history, it makes no MCP tool calls
- No cross-session analysis — it analyzes one conversation at a time
- No real-time monitoring — it's a post-hoc analysis, not a live dashboard
Bootstrap System Context
Ground the assistant in the target SAP system before any coding work. Produces a local system-info.md file that captures SID, release, installed components, detected features, RAP-relevant constraints, and ARC-1's active lint preset — so later prompts stop guessing at constraints.
Run this once per session when working against an unfamiliar system, or again after a system upgrade.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Output path | ./system-info.md | Sidecar to the project root |
| Overwrite | Yes, if file exists | Fresh probe results are authoritative |
| Probe features | Yes | Feature flags (RAP, UI5, transports) drive downstream decisions |
| Include lint preset | Yes | Cloud vs on-prem lint rules matter for generated code |
| Include RAP constraints snapshot | Yes | Helps RAP skills avoid known 7.5x pitfalls immediately |
Input
No input required. Optionally:
- Output path (default:
./system-info.md) - Skip feature probe — if the user only wants identity info and the system is slow
Step 1: Read System Identity
SAPRead(type="SYSTEM")
Returns: SID, system type (onprem | btp), release, kernel version, current user, client, language.
Step 2: Read Installed Components
SAPRead(type="COMPONENTS")
Returns an array of { name, release, description }. Capture at minimum: SAP_BASIS, SAP_UI, SAP_ABA, SAP_GWFND. These set the safe ABAP syntax ceiling and available APIs.
Step 3: Probe Feature Availability
SAPManage(action="probe")
Returns feature flags for: hana, abapGit, rap, ui5, ui5repo, transport, flp. Each has available (bool), mode, and a message. These drive decisions like "can I generate a RAP stack?" or "is FLP catalog management wired in?"
If the user requested to skip this step, mark features as "not probed" in the output.
Step 3b: Derive RAP Constraints Snapshot
Derive a compact RAP constraints block from release + probe + lint context. This is heuristic guidance for skill prompts, not a hard API contract.
Include at minimum:
- Is RAP creation likely viable (
rap.available, plus whether DDLS/BDEF reads work) - On-prem 7.5x guardrails (TABL typing pitfalls, projection BDEF header limits, DDLX annotation scope caveats)
- Whether pre-write lint likely covers DDLS only vs broader RAP artifacts
- Whether ARC-1 RAP preflight/scaffolding helpers should be the default path (
preflightBeforeWrite,scaffold_rap_handlers) - Whether draft should default to deferred/two-pass for safety
Step 4: Read Lint Preset
SAPLint(action="list_rules")
Returns { preset, abapVersion, enabledRules, disabledRules, ... }. The preset (cloud or onprem) reflects the system type detection; abapVersion is the target ABAP dialect (e.g., v754, cloud, standard). Generated code should stay within this dialect.
Step 5: Write system-info.md
Create the file at the chosen path. Use exactly this layout:
# System Info: <SID>
_Generated: <ISO timestamp>_ · _Source: ARC-1_
## Identity
| Field | Value |
|---|---|
| SID | <SID> |
| System type | <onprem / btp> |
| Release | <release> |
| Kernel | <kernel> |
| Client | <client> |
| Language | <lang> |
| User | <username> |
## Core Components
| Component | Release | Description |
|---|---|---|
| SAP_BASIS | <release> | <description> |
| SAP_UI | <release> | <description> |
| SAP_ABA | <release> | <description> |
| SAP_GWFND | <release> | <description> |
<additional rows for any other captured components>
## Feature Availability
| Feature | Available | Mode | Note |
|---|---|---|---|
| RAP / CDS | <yes/no> | <auto/on/off> | <message> |
| abapGit | <yes/no> | <auto/on/off> | <message> |
| HANA | <yes/no> | <auto/on/off> | <message> |
| UI5 | <yes/no> | <auto/on/off> | <message> |
| UI5 Repository | <yes/no> | <auto/on/off> | <message> |
| Transports | <yes/no> | <auto/on/off> | <message> |
| FLP | <yes/no> | <auto/on/off> | <message> |
## Lint Configuration
- **Preset**: <cloud / onprem>
- **ABAP dialect**: <abapVersion>
- **Enabled rules**: <count>
- **Disabled rules**: <count>
## RAP Constraints Snapshot
- **RAP endpoint status**: <available / unavailable / not probed>
- **Recommended build mode**: <single-pass / two-pass>
- **TABL admin type guidance**: <syuname+timestampl on on-prem, abp_* on BTP>
- **Known projection BDEF caveat**: <e.g., use `projection;` header only on 7.5x>
- **Known DDLX scope caveat**: <e.g., headerInfo/search/objectmodel placement limits>
- **Lint coverage hint**: <ABAP+DDLS only / broader>
- **RAP helper path**: <`scaffold_rap_handlers` available / use quick-fix fallback>
## Coding Guidance
- Target ABAP dialect: **<abapVersion>** — do not use syntax beyond this level without verifying per object.
- System type is **<onprem / btp>**:
- If `btp`: prefer released APIs (check with `SAPRead(type="API_STATE", ...)`); avoid non-cloud object types (PROG, INCL, FUGR).
- If `onprem`: full type range available; still prefer released APIs for forward compatibility.
- Transports <enabled / disabled>: <if disabled, note that writes stay on `$TMP`>.
- RAP stack <available / not available>: <if not available, skip RAP generation skills>.
Step 6: Summarize To The User
After writing the file, report in 3-5 lines:
- Which system was probed (SID, type, release)
- The ABAP dialect ceiling
- Which headline features are available (RAP, UI5, transports)
- Key RAP constraints (for example: two-pass recommendation or strict/draft cautions)
- File path written
Do not dump the full file contents into chat — the user can open the file.
Error Handling
| Error | Cause | Fix |
|---|---|---|
SAPRead(type="SYSTEM") fails with auth error | User lacks S_ADT_RES for discovery | Continue without identity block; note in output that SID is unknown |
SAPRead(type="COMPONENTS") empty or 404 | Endpoint unavailable on this system | Note "components endpoint unavailable"; continue with probe + lint |
SAPManage(action="probe") blocked (read-only mode with no write scope) | Safety config | Fall back to SAPManage(action="features") for cached results |
SAPLint(action="list_rules") returns no preset | ARC-1 lint config not yet loaded | Report "lint preset: not configured"; still write the file |
Notes
When To Re-Run
- Starting work against a new or unfamiliar system
- After a support package upgrade (SAP_BASIS release changes)
- When features added (e.g., abapGit installed, RAP runtime enabled)
- When migrating from on-prem to BTP (or vice versa)
What This Skill Does NOT Do
- No source code is read — identity/components/features only
- No package enumeration — use
setup-abap-mirrororSAPRead(type="DEVC")for that - No SAP system-level configuration changes — every call is read-only
Pairing With Other Skills
- Run before
generate-rap-service-researched— the researcher uses system-info.md to pick the right RAP pattern - Run before
setup-abap-mirror— the mirror skill references system-info.md in its header - Run before
migrate-custom-code— migration checks depend on knowing the target release
Convert legacy UI5 JS app ➜ Fiori Elements V4 (annotation-first)
Generate a Fiori Elements V4 list-report + object-page app driven by @UI.* annotations on
the RAP CDS projection. Backend annotations are derived from the legacy UI5 app's actual
features (columns, search, sort, formatters, action buttons, tab structure) so the FE app
reproduces the user-visible contract. Custom behavior FE templates can't express is wired via
the extension API.
This skill is one of two parallel UI paths after the RAP backend lands. Pick this one if
the target architecture is Fiori Elements V4 (annotation-driven; minimal custom code). Pick
modernize-ui5-app.md instead if the target is freestyle TypeScript (custom controllers,
manual binding). Both start from the same legacy JS app + the same V4 RAP service.
migrate-segw-to-rap.md (backend: SEGW V2 → RAP V4)
│
┌─────────────┴─────────────┐
▼ ▼
modernize-ui5-app.md convert-ui5-to-fiori-elements.md
(freestyle TS) (Fiori Elements V4)
This skill depends on:
migrate-segw-to-rap.mdhaving produced an active V4 RAP service (CDS roots + projections, BDEF, SRVD, SRVB published, V4 routing group registered in/n/IWFND/MAINT_SERVICE).- The legacy app (
<source_app>/) still being readable — Phase 1 mines its features even though the legacy app itself is not modified.
Independent of
modernize-ui5-app.md. This skill does not require the modern TS app to exist. The legacy app is the single source of truth for user-visible features; the FE app reproduces them through annotations + extensions directly.
Domain example. Annotation templates use an illustrative
Project → Tasks → TimeEntriesdomain. Substitute the user's entities throughout — the LLM rewrites every projection / entity / field identifier to match the V4 service.
Canonical annotation reference. This skill points at the ABAP RAP Fiori Feature Showcase (
SAP-samples/abap-platform-fiori-feature-showcase) as the authoritative source for@UI.*/@ObjectModel.*/@Common.*annotation patterns. When uncertain about how to express a legacy UI feature as an annotation, search the showcase viamcp__sap-docs__searchwith the feature's Search Term (e.g.#OPHeaderAction,#LineItemHighlight,#HeaderInfo,#ActionInLineItem). The showcase is the ground-truth catalog every annotation in this skill maps back to.
Using mcp__sap-docs__search for annotation discovery (read this first)
This skill names a handful of canonical annotation patterns inline. Treat them as
starting points, not the whole catalog. Anything not explicitly covered — alternate
visual representations, dynamic feature control, charts, value helps, semantic keys,
multi-level OP routing, draft-specific UI behavior, or 7.58-specific syntax issues —
look up in mcp__sap-docs__search before guessing. The MCP indexes the
authoritative SAP-maintained references, has up-to-date showcase tags, and includes
release-specific documentation (758 news, cloud differences, etc.) that this skill text
can't keep current with on its own.
Canonical libraries to know
| Library ID | What's in it |
|---|---|
/abap-fiori-showcase | SAP-samples/abap-platform-fiori-feature-showcase — the on-prem RAP + FE V4 catalog. Every pattern is tagged with a Search Term like #HeaderInfo, #LineItemHighlight, #OPHeaderAction, #OPTable, #DataFieldForAction, #SemanticKey. The 7.58-accurate baseline for this skill. |
/cap-fiori-showcase | SAP-samples/fiori-elements-feature-showcase — CAP/CDS V4 counterpart. Same conceptual patterns from the CAP side; useful when the ABAP showcase tag doesn't include the variant you need, especially for FE manifest layout (layouts_ChildEntities*.cds, #Subpages, #InboundNav). |
/abap-docs-standard | Official ABAP keyword docs (on-prem). Definitive for syntax (FOR BEHAVIOR OF, virtual elements, projection BDEF rules), release-specific capabilities (ABENNEWS-758-RESTFUL for what's available on 7.58), and the deep theory behind any RAP construct. |
/abap-docs-cloud | Same as above for cloud/BTP. Useful when something looks cloud-only — verify before pulling into on-prem 7.58. |
/sap-help (online) | SAP Help full content. Best for SAPUI5 manifest configuration, FE template runtime details, Configuring Internal Navigation. Requires includeOnline=true. |
/abap-cheat-sheets | Practical RAP / ABAP snippets with current syntax variants. |
Search recipe — apply for every annotation question
- Identify what the user sees: "status as a colored chip", "click row → child detail page", "filter with fixed values".
- Search the showcase by hashtag — most patterns are tagged literally in markdown:
mcp__sap-docs__search(query="#TagName") // exact tag lookup mcp__sap-docs__search(query="<visual description>") // semantic fallback - Fetch the full pattern of the most relevant hit:
mcp__sap-docs__fetch(id="/abap-fiori-showcase/<section>#<tag>") - Adapt to the user's entities — the showcase uses
/DMO/FSA_R_RootTPetc.; substitute the user's projection names. - If the on-prem pattern is rejected on the target release, search again on a different axis:
/abap-docs-standard/ABENCDS_PROJ_VIEW_VIRTUAL_ELEMENT(+ exampleABENCDS_PROJ_VIEW_VIRTEL_ABEXA) for virtual elements with ABAP-class calculation/abap-docs-standard/ABENNEWS-<release>-RESTFULfor release-bound capabilities (e.g.ABENNEWS-758-RESTFUL)/cap-fiori-showcasefor an alternate CAP phrasing of the same concept- DDLX
annotate viewas a fallback when entity-level annotations are rejected on the DDLS projection (Run 7 evidence: 7.58 routes@UI.facet,@UI.selectionFields, and headerFOR_ACTIONthrough DDLX)
Starter tag pointers (non-exhaustive — search for more)
Search-Term references that resolve to a concrete annotation pattern in the showcase. Each is the entry point; fetch the full content to get the canonical syntax for your release.
| Need | Starting search terms / docs |
|---|---|
| Colored status / criticality on a list row | #LineItemHighlight, criticality: 'CriticalityCode', @UI.Criticality |
| Criticality with calculation logic (not a real column) | /abap-docs-standard/ABENCDS_PROJ_VIEW_VIRTUAL_ELEMENT; example ABENCDS_PROJ_VIEW_VIRTEL_ABEXA. Also @ObjectModel.virtualElementCalculatedBy: 'ABAP:<class>' |
| Header data point / status indicator | #HeaderFacet, #KeyValue, #DataPointProgress, @UI.dataPoint |
| Object Page table for a child entity | #OPTable, @UI.lineItem on the child projection, @UI.facet with type: #LINEITEM_REFERENCE, targetElement: '_AssocName' |
| Drill from one OP to another OP (e.g. Project → Task → TimeEntry) | #OPTable (entry); cap-fiori-showcase/app/listreport-objectpage/layouts_ChildEntities1.cds etc. (sub-page layout); SAPUI5 "Configuring Internal Navigation" (sap-help) for the manifest routing shape |
| In-page navigation between facets | #InboundNav, targetSections, navigation property on @UI.facet |
| Action button — OP header | #OPHeaderAction, type: #FOR_ACTION, DataFieldForAction |
| Action button — LR table toolbar | #ActionInLineItem, #WithAction |
| Sorting + filter bar | #SelectionFields, #PresentationVariant, @UI.selectionFields |
| Search across fields | #Search, @Search.searchable, @Search.defaultSearchElement |
| Semantic key (highlighted/bold in tables) | #SemanticKey, @ObjectModel.semanticKey |
| Value help / fixed value list | #ValueHelp, @Consumption.valueHelpDefault, @ObjectModel.text.element |
| Dynamic CRUD (hide/show edit/delete by row state) | #DynamicCRUD, @UI.updateHidden, @UI.deleteHidden, BDEF features: instance |
| Draft + UI specifics | #DraftHandling, @UI.lineItem editable qualifier, action keyword ( precheck ) |
| Side effects / re-read on action | #SideEffects, @Common.SideEffects |
| BDEF action signature variants (precheck, factory, copy) | /abap-docs-standard/ABENBDL_ACTION, #OPCopyAction, action ( precheck ) <name> |
| 7.58 capability boundaries | /abap-docs-standard/ABENNEWS-758-RESTFUL + ABENNEWS-758-CDS_BDL |
Anti-patterns
- Don't take this skill's example code as gospel. It's a teaching example written at a point in time. The showcase is the ground truth.
- Don't paste a showcase example from a different release without verifying. A
#DataFieldForActionexample branching off the BTP-Cloud branch may use cloud-only keywords; the on-premmainbranch is the safe baseline for 7.58. - Don't hand-code FE routing/manifest entries without consulting the SAPUI5 internal
navigation docs. The shape varies by template + release and is easier to derive from
sap-helpthan to reverse-engineer from a runtime failure. - Don't accept the first failed-activation symptom as the final answer. Run 7 hit four
different blockers in four different layers for one polish item; in every case a follow-up
search via
mcp__sap-docs__searchwould have surfaced an alternative before the rollback. The cost of one extra search is 5 seconds; the cost of an unnecessary rollback is 10+ minutes.
Why this is its own skill
Fiori Elements isn't a code transformation — it's a deletion + relocation. Most of the freestyle app is replaced by FE templates that interpret CDS annotations. The skill's three real jobs:
- Derive the right
@UI.*annotations from the legacy app's user-visible features so the FE renders an equivalent UX. - Apply those annotations to the RAP CDS projection (the service the SRVB exposes).
- Generate the FE list-report + object-page project via the SAP Fiori MCP server
(
@sap-ux/fiori-mcp-server), and wire extensions for anything FE templates can't express.
Smart defaults (apply silently — do NOT ask before research)
| Setting | Default | Rationale |
|---|---|---|
| Legacy app | <source_app>/ | The freestyle JS app — read-only; mined in Phase 1 for the feature inventory. Authoritative source of every user-visible behavior the FE app must reproduce. |
| Target FE app | <fe_app>/ — default name modern-fe-app/ if user gives no path (mirrors the workspace pattern legacy-ui5-app/ → modern-ui5-app/ → modern-fe-app/) | Fiori MCP generates here; folder must exist and be empty (or empty subfolders) |
| FE floorplan | List Report + Object Page (LROP V4) when the BO has a clear root + child facets | Maps cleanly to the typical RAP composition root + children. OVP only if the user explicitly asks. |
| Template | lropv4 | Default unless the user asks otherwise |
| Generator | SAP Fiori MCP server (@sap-ux/fiori-mcp-server) via the list_functionalities → get_functionality_details → execute_functionality sequence | First-party SAP tool; understands FE V4 patterns natively |
| App namespace | <source_namespace>.fe | Keeps the legacy and FE apps distinguishable (and the modern TS app too, if modernize-ui5-app was also run as the alternate path) |
| UI5 version | Latest 1.x release (e.g. 1.147.2) unless user specifies | LTS-track; latest FE V4 features available |
| Language | TypeScript | Modern default; extension files use type-safe APIs |
| OData V4 service URL | Prefer the SRVD-direct path on the system's HTTPS port: https://<host>:<https-port>/sap/opu/odata4/sap/<srvb>/srvd/sap/<srvb>/0001 (e.g. https://a4h.marianzeis.de:50001/sap/opu/odata4/sap/zui_dm_projects_o4/srvd/sap/zui_dm_projects_o4/0001). Falls back to the Gateway hub path http://<host>:<http-port>/sap/opu/odata4/sap/<srvb>/srvd_a2x/sap/<service>/0001 only when SRVD-direct isn't reachable. | Run 5 + Run 6 verified the SRVD-direct path works without /n/IWFND/MAINT_SERVICE registration on 7.5x systems. The hub path requires the routing-group manual step. |
| Main entity | Root entity alias exposed by the SRVB (e.g. the alias on define root view entity ... alias <X>) | The LR+OP floorplan is rooted at a single entity |
| Annotations location | In CDS via SAPWrite update DDLS — not in a local annotation file inside the FE app | The annotations belong to the service; FE app reads them through $metadata. Local annotation files are an antipattern for RAP-bound apps. |
| Extension language | TypeScript (controller extensions) | Match the rest of the chain |
| Validation | mcp__SAPUI5_MCP_Server__run_ui5_linter + run_manifest_validation + tsc --noEmit all green | The hard acceptance criteria |
| Acceptance | FE app runs end-to-end against the V4 service. Browser smoke covers every feature inventoried in Phase 1 — reproduced through annotations or extension hooks. | Concrete deliverable |
Input
The user provides:
- Path to the legacy app for feature mining (default:
<source_app>/). Read-only. - Path / name for the FE app (default:
<fe_app>/). - OData V4 service URL — derived from
migrate-segw-to-rap's SRVB output. Required. - Root entity alias (e.g.
Project). Default: infer from the SRVB's$metadata. - App namespace (default:
<source_namespace>.fe). - Transport for the CDS annotation writes (default: same transport used by
migrate-segw-to-rap, or auto-create viaSAPTransport(action="create")). - UI5 version (default: latest 1.x).
If only the legacy app path and V4 URL are provided, apply smart defaults and surface the plan
in Phase 3 for user ok before any writes.
Phase 0 — Preflight
0a. RAP V4 service is live and bindable
SAPManage(action="probe")
Assert rap.available == true.
SAPRead(type="SRVB", name="<V4_SRVB>")
Assert the SRVB exists and is active. If not, stop with "V4 service binding <V4_SRVB> is
missing or inactive — run migrate-segw-to-rap.md first."
Bash: curl -s -o /tmp/svc_metadata.xml -w "%{http_code}\n" "<V4_service_URL>/\$metadata?sap-client=<client>"
Assert 200 OK. Try the SRVD-direct path first (HTTPS port + /srvd/sap/<srvb>/0001/).
If 403 with IWBEP/CM_V4_COS/136, the URL is using the Gateway hub path and the routing
group isn't registered. Switch to the SRVD-direct URL pattern before stopping — the
direct path bypasses the hub registration. Only fall back to "register service group via
/n/IWFND/MAINT_SERVICE" if BOTH URL patterns fail.
If 503 with IWBEP/CM_V4_RUNTIME/000 ("service alias cache outdated"), retry once — this is
a transient Gateway cache issue. If it persists across retries, treat as 403 and switch URL
patterns.
0b. CDS projection is readable + writable
SAPRead(type="DDLS", name="<root_projection>")
Assert active version returns. If not, stop with "Root projection is missing — re-run
migrate-segw-to-rap.md Phase 6 Step 3."
0c. Legacy app exists and is readable
Bash: ls <source_app>/webapp/controller/ <source_app>/webapp/view/
Assert both folders are populated. Stop with explicit reason if either is missing — the legacy app is the single source of truth for both the annotation plan (Phase 1+2) and the extension list (Phase 2b).
0d. SAP Fiori MCP server reachable
mcp__fiori-mcp__list_functionalities
If this call fails, the Fiori MCP server isn't configured in this chat. Surface the configuration block and stop:
// .cursor/mcp.json (or equivalent)
{
"mcpServers": {
"fiori-mcp": {
"type": "stdio",
"timeout": 600,
"command": "npx",
"args": ["--yes", "@sap-ux/fiori-mcp-server@latest", "fiori-mcp"]
}
}
}
(Source: @sap-ux/fiori-mcp-server README on github.com/SAP/open-ux-tools.)
Optional companion: mcp__SAPUI5_MCP_Server__* for post-generation lint + manifest validation.
0e. Connection Manager (optional)
For scenarios that use a saved BTP / on-prem system connection rather than a direct service
URL, the Fiori MCP server depends on the Connection Manager for SAP Systems VS Code
extension. For the direct-URL flow this skill uses, the extension is not required — the
service URL is passed straight through to execute_functionality.
Phase 1 — Inventory the legacy app's user-visible features
This is the heart of the annotation plan. The FE app must reproduce every user-visible behavior of the legacy app. Read every relevant legacy file and produce a feature inventory.
1a. Read the legacy manifest
Read: <source_app>/webapp/manifest.json
Pull: sap.ui5.routing.routes (what URLs the user can reach), sap.ui5.rootView,
sap.app.dataSources, i18n. The routes tell you the navigation tree; the data sources tell
you what service shape the legacy app expects.
1b. Read every legacy view
Bash: ls <source_app>/webapp/view/
Read: <source_app>/webapp/view/<each>.view.xml
For each view, inventory:
- Page title (from
<Page title=...>). - Header content — buttons, with their conditions (e.g.
enabled="{= ${Status} === 'D'}"). - List/table columns — every
<Column>with its bound field, sort direction, alignment. - Search fields —
<SearchField>withliveChange+placeholder. - Sort defaults —
sorterclause on list bindings (path + ascending/descending). - Item structure —
ObjectListItem/ColumnListItem/ObjectHeaderwith their attributes, status fields, formatter calls. - Tab structure —
IconTabBar+IconTabFilterentries (which entities are tabbed, whether each tab has a counter). - Navigation handlers —
press/selectionChangecallbacks (rows clickable → navigation). - Counters, footers — informational widgets (item counts, totals).
1c. Read every legacy controller
Bash: ls <source_app>/webapp/controller/
Read: <source_app>/webapp/controller/<each>.controller.js
For each controller, inventory:
- Action handlers — what does each
on<Action>method do? (Call OData function import? Filter? Re-bind? Show MessageBox?) - Filtering / search logic — what fields, what
FilterOperator, what bind path? - Function-import calls —
oModel.callFunction(...)calls and their parameter shapes. - Custom validation — pre-call checks before function imports / submits.
- Custom navigation — anything that bypasses the manifest router.
- Custom client-side state — JSONModels created for UI-only state (e.g. tab counters fed from non-OData sources).
1d. Read every legacy formatter
Read: <source_app>/webapp/model/formatter.js
For each formatter function, inventory:
- What it formats — status code → text, status code → semantic state (Success/Warning/Error), date → short format, hours → decimal, etc.
- The code→text mapping — capture the exact values (e.g.
D → "Draft",A → "Active",C → "Closed").
These map directly to CDS annotation patterns — @Common.Text + @UI.TextArrangement,
@UI.Criticality, value-help collections, etc.
1e. Build the feature inventory
Print the structured inventory to the user:
Feature inventory — <source_app>:
ROOT ENTITY (Project):
Display name (header): Title
Description (sub): ProjectId
Status (criticality): Status field — values D=Draft (Warning) / A=Active (Success) / C=Closed (Neutral)
Sort default: StartDate descending
Search (master): ProjectId, Title (Contains, OR-joined)
Audit fields: Erdat (Created), Ernam (Created by), Aedat (Changed), Aenam (Changed by)
Header button: Approve — enabled when Status == 'D', calls /ApproveProject(ProjectId)
Count footer: "<n> projects" displayed below the list
CHILD ENTITY (Task):
Tab in detail: "Tasks"
Counter: from binding length
Columns: TaskId, Title+Description, Status, Priority, DueDate, AssignedTo, EstimatedHours
Status criticality: Status: D/IP/D/C (Draft/InProgress/Done/Cancelled) — see formatter
Priority criticality: L/M/H (Low/Medium/High) — see formatter
Click behavior: Selecting a task populates the TimeEntries tab
CHILD-OF-CHILD ENTITY (TimeEntry):
Tab in detail: "Time Entries"
Counter: from selected task's TimeEntries length
Columns: EntryId, TaskId, WorkDate, WorkHours, Description, Username
FORMATTERS:
statusText: D → "Draft", A → "Active", C → "Closed"
statusState: D → Warning, A → Success, C → Neutral
taskStatusText: D → "Draft", IP → "In Progress", DN → "Done", CN → "Cancelled"
taskStatusState: same scheme
priorityText: L → "Low", M → "Medium", H → "High"
priorityState: L → Neutral, M → Warning, H → Error
dateShort: custom YYYY-MM-DD
hoursDecimal: two decimal places
FUNCTION IMPORT (V2):
ApproveProject(ProjectId) → translates to RAP action approve_project (already in BDEF)
This inventory is the contract for Phase 2.
Phase 2 — Map features to annotations + extensions
Classify each inventory item as one of:
- STANDARD — FE templates render this natively (pagination, row click navigation, search-by-key, basic edit, basic create, basic delete, draft support).
- ANNOTATION — needs a specific
@UI.*/@Common.*/@ObjectModel.*annotation on the CDS projection. Most legacy features land here. - EXTENSION — genuinely custom behavior FE templates can't express; needs a controller extension on the FE app side.
2a. Annotation map — starting points (verify each pattern via sap-docs)
The table below is a quick reference, not a definitive catalog. Apply the search
recipe from the "Using mcp__sap-docs__search" section above to confirm the current
canonical syntax for your release, especially for anything tagged ⚠ below.
| Legacy feature | Starting annotation + showcase tag |
|---|---|
Header title = Title | @UI.HeaderInfo.title.value: 'Title' — #HeaderInfo |
Header description = ProjectId | @UI.HeaderInfo.description.value: 'ProjectId' — #HeaderInfo |
| Header type label | @UI.HeaderInfo.typeName: 'Project', typeNamePlural: 'Projects' — #HeaderInfo |
| List columns (master) | @UI.lineItem: [{ position: N, importance: #HIGH }] per field — #LineItemHighlight for the variant with criticality |
| ⚠ Status code → text + color | Multiple valid patterns; choose by release/draft constraints. Search #LineItemHighlight for the criticality-via-real-column path. For a calculated criticality without a persistent column, see /abap-docs-standard/ABENCDS_PROJ_VIEW_VIRTUAL_ELEMENT + @ObjectModel.virtualElementCalculatedBy: 'ABAP:<class>'. On 7.58 + draft, both have known constraints (Run 7 §1 details). Search before adopting. |
| Sort default | @UI.presentationVariant.sortOrder: [{ by: '<field>', direction: #DESC }] — #PresentationVariant |
| Search across fields | @Search.searchable: true at view level + @Search.defaultSearchElement: true per field — #Search |
| Filter bar | @UI.selectionFields: [...] — #SelectionFields |
| Audit fields display | @UI.fieldGroup + @UI.facet of #FIELDGROUP_REFERENCE — #HeaderFieldGroup |
| Approve button (header) | @UI.identification: [{ type: #FOR_ACTION, dataAction: 'approve_project', label: 'Approve', criticality: 3, criticalityRepresentation: #WITH_ICON }] — #OPHeaderAction. The action does NOT auto-render from the BDEF. Projection BDEF must already expose use action approve_project;. |
| LR toolbar action | Same shape on @UI.lineItem — #ActionInLineItem, #WithAction |
| OP table for child entity | @UI.facet: [{ type: #LINEITEM_REFERENCE, targetElement: '_AssocName', label: '...' }] on the parent + @UI.lineItem on the child projection — #OPTable |
| ⚠ Multi-level navigation (Project → Task → TimeEntry) | Two valid shapes — research before picking. (a) Nested LineItem facet referencing _Tasks._TimeEntries from the root projection (release-dependent FE support). (b) Separate Task OP route — annotate ZC_DM_TASK with @UI.headerInfo + its own _TimeEntries facet, then add a Task routing target to the FE app's manifest. Search #OPTable, #Subpages, #InboundNav (cap-fiori-showcase); plus SAPUI5 "Configuring Internal Navigation" (sap-help) for manifest routing shape. |
| Semantic key bolding | @ObjectModel.semanticKey: ['ProjectId'] — #SemanticKey |
| Dynamic CRUD (hide buttons by row state) | @UI.updateHidden + @UI.deleteHidden bound to a field — #DynamicCRUD |
DDLS-vs-DDLX scope on 7.58. Several entity-level annotations (
@UI.facet,@UI.selectionFields, headerFOR_ACTIONvia@UI.identification) were rejected on the projection DDLS in Run 7 but succeeded when moved to a DDLX metadata extension (annotate view <ZC_*> with @UI.facet: [...]etc.). If a DDLS entity-level annotation errors with "wrong scope" / "unknown", route it through DDLX. Confirm with the relevant#Tagin/abap-fiori-showcase— the showcase patterns are already split between DDLS and DDLX where the on-prem release requires it.
2b. Extension map (typical)
| Legacy feature | Extension hook |
|---|---|
| Status === 'D' guard on Approve | FE's BDEF action button is enabled per the BDEF's precheck. If the legacy app's enable rule differs from the BDEF, add the precheck on the BDEF (Step 2c) rather than overriding in JS. |
| Custom validation before Approve (e.g. require Description) | editFlow.onBeforeAction controller extension on the ObjectPage |
| Custom client-side count footer phrasing | Skipped — FE list-report shows native count |
| Custom navigation patterns | Almost never needed; FE's row → OP nav is default |
| MessageBox on approve failure | Native FE error toast already handles this |
2c. BDEF-side preparation (run AFTER 2b, BEFORE Phase 4)
If the inventory surfaced a guard like "Approve button only when Status === 'D'", that's a
precondition, not a UI concern. Encode it on the BDEF side via the action's precheck
clause, then re-activate. (This step belongs in migrate-segw-to-rap.md Step 5 but call it
out explicitly here when the legacy guard wasn't already lifted.) Example:
action approve_project precheck result [1] $self;
with a precheck method in the behavior pool that fills %cid / %key and asserts
Status == 'D'. Skill defers the actual precheck body to edit_method if needed.
Phase 3 — Plan + user approval
Print the plan in this exact format and STOP for ok / edit / question:
Plan — generate FE app at <fe_app>:
Floorplan: List Report + Object Page (LROP V4)
Namespace: <source_namespace>.fe
UI5 version: <user-provided, default latest 1.x>
V4 service: <V4_service_URL>
Main entity: <root_alias> (alias on the root projection)
Generator: SAP Fiori MCP server (@sap-ux/fiori-mcp-server)
Backend annotation writes (via SAPWrite update DDLS on the projection):
<root_projection>:
@UI.HeaderInfo, @UI.SelectionFields, @UI.LineItem (root columns),
@UI.Identification, @UI.PresentationVariant.SortOrder,
@UI.FieldGroup.Audit, @UI.Facet (Identification + Tasks)
@Common.Text + virtual <field>Criticality (Status)
<child_projection_task>:
@UI.LineItem (Task columns), @UI.HeaderInfo,
@UI.Facet (Task identification + TimeEntries),
@Common.Text + virtual fields for Status, Priority
<child_projection_timeentry>:
@UI.LineItem (TimeEntry columns), @UI.HeaderInfo
BDEF-side adjustments (via SAPWrite update BDEF / edit_method):
<list precheck additions, if any>
FE app generation (via Fiori MCP):
Step 1: list_functionalities → enumerate supported FE app creations
Step 2: get_functionality_details → "create FE V4 list-report+OP for external OData service"
Step 3: execute_functionality → pass service URL, root entity, namespace, target folder
Extension scaffold (post-generation):
- <controller-extension list per Phase 2b>
Validation:
- ui5-linter clean
- manifest validation clean
- tsc --noEmit clean
- browser smoke against every Phase 1 inventory item
Type `ok` to proceed, `edit` to revise, or ask any question.
Wait for ok before mutating anything in the SAP system or generating the FE app.
Phase 4 — Write @UI.* annotations to CDS projections (backend preparation)
This is the "prepare the annotations in the backend" step. Do all the CDS writes here
BEFORE invoking the Fiori MCP generator — the generator reads the annotated $metadata, so
the annotations must be active and the SRVB republished before the generator runs.
4a. Annotate the root projection
SAPRead(type="DDLS", name="<root_projection>")
Splice in the planned annotations. Concrete shape (substitute your entities):
@Metadata.allowExtensions: true
@UI.headerInfo: {
typeName: 'Project',
typeNamePlural: 'Projects',
title: { value: 'Title' },
description: { value: 'ProjectId' }
}
@UI.selectionFields: [ 'ProjectId', 'Title', 'Status' ]
@UI.presentationVariant: [{
qualifier: 'DefaultSort',
sortOrder: [{ by: 'StartDate', direction: #DESC }]
}]
@UI.facet: [
{ id: 'GeneralInfo', purpose: #STANDARD, type: #IDENTIFICATION_REFERENCE, label: 'General' },
{ id: 'AuditInfo', purpose: #STANDARD, type: #FIELDGROUP_REFERENCE, label: 'Audit',
targetQualifier: 'Audit' },
{ id: 'Tasks', purpose: #STANDARD, type: #LINEITEM_REFERENCE, label: 'Tasks',
targetElement: '_Tasks' }
]
// Header action — renders as an "Approve" button on the OP header (showcase #OPHeaderAction).
// criticality 3 = green (success), 0 = neutral, 1 = red.
@UI.identification: [
{ type: #FOR_ACTION,
dataAction: 'approve_project',
label: 'Approve',
criticality: 3,
criticalityRepresentation: #WITH_ICON }
]
@Search.searchable: true
define root view entity <root_projection>
provider contract transactional_query
as projection on <root_view>
{
key @UI.lineItem: [{ position: 10, importance: #HIGH }]
@UI.identification: [{ position: 10 }]
@UI.selectionField: [{ position: 10 }]
@Search.defaultSearchElement: true
ProjectId,
@UI.lineItem: [{ position: 20, importance: #HIGH }]
@UI.identification: [{ position: 20 }]
@UI.selectionField: [{ position: 20 }]
@Search.defaultSearchElement: true
Title,
@UI.lineItem: [{ position: 30, criticality: 'StatusCriticality' }]
@UI.identification: [{ position: 30 }]
@UI.selectionField: [{ position: 30 }]
Status,
@UI.lineItem: [{ position: 40 }]
@UI.identification: [{ position: 40 }]
StartDate,
@UI.lineItem: [{ position: 50 }]
@UI.identification: [{ position: 50 }]
EndDate,
@UI.identification: [{ position: 60 }]
Description,
@UI.fieldGroup: [{ qualifier: 'Audit', position: 10, label: 'Created at' }]
Erdat,
@UI.fieldGroup: [{ qualifier: 'Audit', position: 20, label: 'Created by' }]
Ernam,
@UI.fieldGroup: [{ qualifier: 'Audit', position: 30, label: 'Changed at' }]
Aedat,
@UI.fieldGroup: [{ qualifier: 'Audit', position: 40, label: 'Changed by' }]
Aenam,
// virtual criticality field (computed from Status code)
@ObjectModel.virtualElementCalculatedBy: 'ABAP:<root_class>' // OR via case-when below
virtual StatusCriticality : abap.int1,
/* associations */
_Tasks
}
For the virtual criticality, simplest cross-7.58-compatible option is a case-when directly
in the projection:
case Status
when 'D' then 2 // Critical (Warning)
when 'A' then 3 // Positive (Success)
when 'C' then 0 // Neutral
else 0
end as StatusCriticality,
Write the spliced source:
SAPWrite(action="update", type="DDLS", name="<root_projection>",
source="<spliced source>", transport="<transport>")
SAPActivate(type="DDLS", name="<root_projection>")
4b. Annotate every child projection
Repeat the pattern for each <child_projection_X>. Each child gets:
@UI.headerInfo(title/description)@UI.lineItemfor every column the legacy view showed@UI.facetif the child has further children (e.g._TimeEntriesunder Task)- Virtual criticality fields for any code-with-color field surfaced in the inventory
4c. Publish the SRVB
The SRVB needs republishing for the new annotations to surface in $metadata:
SAPWrite(action="publish_srvb", name="<V4_SRVB>")
4d. Verify annotations land in $metadata
Bash: curl -s "<base>/<V4_service_URL>/$metadata" | grep -oE 'UI\.(LineItem|HeaderInfo|Facets|SelectionFields|PresentationVariant|FieldGroup|Identification)' | sort -u
Expected output: every annotation kind you wrote shows up in the listing. If empty, the SRVB
didn't pick up the changes — re-run publish_srvb. If only some show, the projection wasn't
re-activated cleanly — SAPDiagnose(action="object_state", type="DDLS", name="<root_projection>")
to inspect.
Phase 5 — Generate the FE app via the SAP Fiori MCP server
This is the "use Fiori MCP to create the app" step. The Fiori MCP server exposes a
three-tool dance — list_functionalities → get_functionality_details → execute_functionality.
Each step narrows scope. Do not skip steps even if you think you know the params.
References:
- SAP/open-ux-tools — fiori-mcp-server README
- npm: @sap-ux/fiori-mcp-server
- SAP Community: First Release of the SAP Fiori MCP Server
The Fiori MCP server is experimental at the time of this skill's writing. Tool signatures may change. If
list_functionalitiesreturns a different shape than expected, follow the live response — the README above is the source of truth.
5a. Discover what the server can do
mcp__fiori-mcp__list_functionalities
Inspect the response for a functionality that matches "create a new Fiori elements application
for an external OData V4 service". The exact name in the response depends on the server version
— look for keywords like create, fiori-elements, list-report, lropv4, external-service.
If the server doesn't have a matching functionality:
- It might require a CAP project. In that case, generate via the legacy fallback
(
@sap/generator-fioriCLI — see 5d) and document the gap as a Run capture for next iteration. - Or the user's Fiori MCP version is older than expected. Re-check by running:
and instructing the user to update the MCP config to pin the latest.Bash: npx --yes @sap-ux/fiori-mcp-server@latest --version
5b. Get parameter requirements for the chosen functionality
mcp__fiori-mcp__get_functionality_details(name="<the-functionality-name-from-5a>")
The response lists required + optional parameters. For the LROP-for-external-service flow, typical required parameters include:
serviceUrl—<V4_service_URL>(the$metadata-backed endpoint from Phase 0a)mainEntityorentitySet— the root entity alias from the SRVB (e.g.Project)targetPath—<fe_app>/(the folder to generate into)namespace—<source_namespace>.feappId/appName— the application identifierui5Version— user-provided (default: latest 1.x)language—typescript
Map the user-supplied inputs onto the required parameters. If a required parameter has no mapping, stop and ask the user. Do not invent values.
5c. Execute the generator
mcp__fiori-mcp__execute_functionality(
name="<the-functionality-name-from-5a>",
parameters={
serviceUrl: "<V4_service_URL>",
mainEntity: "<root_alias>",
targetPath: "<fe_app>",
namespace: "<source_namespace>.fe",
appName: "<short-app-id>",
ui5Version: "<ui5-version>",
language: "typescript"
}
)
Wait for the generator to finish. Verify the structure:
Bash: ls <fe_app>/webapp/ && cat <fe_app>/webapp/manifest.json | head -40
Expected:
webapp/Component.tswebapp/manifest.jsonwithsap.ui.generic.app/sap.fe.templatesconfigwebapp/i18n/i18n.propertieswebapp/ext/(extension folder — may be empty)package.json/ui5.yaml/tsconfig.json
5d. Fallback if the MCP server can't do it
If list_functionalities doesn't expose an external-service path, fall back to the
@sap/generator-fiori CLI:
Bash: cd <workspace> && npx --yes @sap/generator-fiori --no-deploy
Walk through the prompts (or pass --skip-install with explicit args). This is the same
generator the MCP server wraps — slower because it's interactive, but always works.
5e. Known Fiori MCP rough edges (track upstream)
The Fiori MCP server is experimental. Two known issues to recognize and work around:
fetch-service-metadatareturns an MCP framework error instead of a structured response when the@sap-ux/storehas no entry for the target system. Workaround:curl $metadatayourself to a local file (e.g.<fe_app>/metadata.xml), then pointexecute_functionalityat the file. Tracked upstream: SAP/open-ux-tools#4652 — when this closes, the curl workaround can be dropped.fetch-service-metadatarequires Connection Manager configuration for stored system entries; direct URL passthrough toexecute_functionalitybypasses this. Skill's Phase 0e already documents the direct-URL path.
Capture any new rough edges in RUN-NOTES.md so the next iteration can either work
around them or file follow-up upstream issues.
Phase 6 — Configure extensions for the EXTENSION list from Phase 2b
For each row in the Phase 2b extension map, scaffold a TS controller extension. FE V4 extensions come in two flavors:
- Controller extensions — extend the LR or OP controller via the
editFlow/routing/appComponentAPI. - Extension points — slot custom XML/Fragment into a specific spot (header, footer, before/after a section).
For the talk demo's typical extension (a precheck on approve that the BDEF doesn't already encode):
Write: <fe_app>/webapp/ext/ObjectPageExt.ts
import ControllerExtension from "sap/ui/core/mvc/ControllerExtension";
import MessageBox from "sap/m/MessageBox";
/**
* @namespace <source_namespace>.fe.ext
*/
export default class ObjectPageExt extends ControllerExtension {
public static overrides = {
editFlow: {
onBeforeAction: async function (
this: ObjectPageExt,
mParameters: { actionName: string; context: any }
) {
if (!mParameters.actionName.endsWith(".approve_project")) return;
const description = mParameters.context.getProperty("Description");
if (!description) {
MessageBox.error("Cannot approve a project without a description.");
throw new Error("Approval blocked by extension");
}
}
}
};
}
Register the extension in <fe_app>/webapp/manifest.json:
"sap.ui5": {
"extends": {
"extensions": {
"sap.ui.controllerExtensions": {
"sap.fe.templates.ObjectPage.ObjectPageController": {
"controllerName": "<source_namespace>.fe.ext.ObjectPageExt"
}
}
}
}
}
Run the linter after each extension scaffold:
mcp__SAPUI5_MCP_Server__run_ui5_linter(files=["<fe_app>/webapp/ext/ObjectPageExt.ts"])
Repeat for every entry in the extension map. Keep extensions small — one concern per class.
If a feature classification is ambiguous (annotation? extension?), use the Fiori MCP's docs search to resolve:
mcp__fiori-mcp__search_docs(query="custom validation before action Fiori elements V4")
This pulls the authoritative SAP guidance and prevents speculation.
Phase 7 — Validation + smoke test
7a. Static checks
mcp__SAPUI5_MCP_Server__run_ui5_linter
mcp__SAPUI5_MCP_Server__run_manifest_validation
Bash: cd <fe_app> && npx tsc --noEmit
All three must return clean.
7b. Dev server
Restart the dev server on a free port (default 8082 — pick a different port if the legacy
app's dev server or another running tool already uses it):
Bash: cd <fe_app> && pkill -f "ui5 serve" ; (npm start -- --port 8082 &)
Wait ~5 seconds for the server to come up. Probe the entry point:
Bash: curl -s -o /dev/null -w "%{http_code}\n" http://localhost:8082/index.html
7c. Browser smoke against the Phase 1 inventory
Open http://localhost:8082 in a browser and validate every Phase 1 inventory item. The
acceptance criterion is: the FE app reproduces every user-visible feature of the legacy app,
either through annotations or extensions.
Reference checklist (adapt to the user's inventory):
- List-report renders with the columns from
@UI.LineItemin the right order. - Filter bar shows the fields from
@UI.SelectionFields. - Search works on the fields marked
@Search.defaultSearchElement. - Default sort matches
@UI.PresentationVariant.SortOrder. - Row click opens the OP.
- OP header shows the right title/description from
@UI.HeaderInfo. - Status field in the row has the right color (criticality).
- Tabs/facets render each
@UI.Facet-referenced association. - Nested facets drill into grandchild entities (e.g. TimeEntries under Tasks).
- Action button renders for the BDEF action (from
@UI.identificationDataFieldForAction); clicking executes via the framework's standard CSRF/etag flow — no extension required for the round-trip. - Extension hook fires for the cases inventoried in Phase 2b (validation, custom prompts).
- Audit fields show in the Audit facet on the OP.
- Native FE count in the list-report header matches the legacy footer phrasing (allowing for "X projects" vs "Showing X of Y" UX differences).
7c.1 — Draft V4 reality (verified in Run 6)
The V4 service exposes IsActiveEntity as part of every entity key under a draft scenario.
Two consequences for testing:
- Keyed reads must include
IsActiveEntity:Project(ProjectId='PRJ-0001',IsActiveEntity=true)returns 200; the legacy-styleProject('PRJ-0001')returns 400. - Action invocation requires the full CSRF dance: GET
<service-root>/?sap-client=<n>withX-CSRF-Token: Fetchfirst → POST the action URL with the returnedX-CSRF-Token, session cookie, andIf-Match: <etag>. SkippingIf-Matchreturns 428 (CX_OD_PRECOND_REQUIRED).
These are normal for any V4 + draft service; FE templates handle them automatically at runtime. The notes here are for manual curl smokes only.
If any step fails:
- For an annotation issue, return to Phase 4 and adjust the CDS, re-activate,
publish_srvb, rerun the smoke step. - For an extension issue, debug the controller extension in browser DevTools.
- For an FE rendering issue that looks like a tool bug, run
mcp__fiori-mcp__search_docs(query="<exact symptom>")to find the authoritative reference.
7d. Final report
Fiori Elements conversion complete — <fe_app>
Floorplan: LROP V4 (TS)
UI5: <version>
V4 service: <V4_service_URL>
Annotations: <n> @UI.* annotations written across <m> projections
Extensions: <n> controller extensions
Linter: clean
Manifest: clean
TypeCheck: clean
Browser smoke: <12+/12+> inventory items reproduced
What just happened (3 sentences):
- Mined the legacy app's user-visible feature set (columns, sort, search, actions,
tab structure, formatters).
- Wrote the equivalent @UI.* / @Common.* / @Search.* annotations onto the RAP CDS
projections via ARC-1.
- Generated the FE app on top of the now-annotated $metadata via the SAP Fiori MCP
server, with extension hooks for the few cases FE templates can't express natively.
ARC-1 calls used:
- SAPManage(action=probe)
- SAPRead(type=DDLS, name=<root_projection>)
- SAPRead(type=SRVB, name=<V4_SRVB>)
- SAPWrite(action=update, type=DDLS, ...) × <m> projections
- SAPActivate(type=DDLS, ...)
- SAPWrite(action=publish_srvb, name=<V4_SRVB>)
- (Optional) SAPWrite(action=update, type=BDEF, ...) + SAPActivate for BDEF precheck
Fiori MCP calls used:
- mcp__fiori-mcp__list_functionalities
- mcp__fiori-mcp__get_functionality_details(name=<chosen>)
- mcp__fiori-mcp__execute_functionality(...)
- mcp__fiori-mcp__search_docs(...) × <n> (during extension scaffolding)
UI5 MCP calls used:
- mcp__SAPUI5_MCP_Server__run_ui5_linter × <n>
- mcp__SAPUI5_MCP_Server__run_manifest_validation
Error handling — known modes
| Symptom | Cause | Fix |
|---|---|---|
$metadata reflects no annotations after SAPWrite update DDLS | DDLS reactivated but SRVB wasn't republished | SAPWrite(action="publish_srvb", name="<V4_SRVB>") |
mcp__fiori-mcp__list_functionalities returns empty / fails | Server not registered, or npx cache stale | Verify .cursor/mcp.json; in a fresh shell, npx --yes @sap-ux/fiori-mcp-server@latest fiori-mcp should print server-ready logs |
| Generator fails with "service unreachable" | The <V4_service_URL> is gated by 403 because of the V4 routing group | Surface the /n/IWFND/MAINT_SERVICE manual step from migrate-segw-to-rap.md Phase 6 |
| Generator succeeds but FE app shows a blank shell | mainEntity passed without annotated CDS | Re-check Phase 4 — every entity in the @UI.Facet chain needs at least @UI.LineItem and (for OP root) @UI.HeaderInfo |
| List-report shows no columns | @UI.LineItem annotation is on the root view, not the projection | Move annotations to the projection; FE reads them from the SRVB-exposed projection |
| Action button not visible | Action wasn't exposed on the projection BDEF, or projection BDEF missing use action approve_project | Check projection BDEF (define behavior for <root_projection> { ... use action approve_project; }) and re-publish |
| Filter bar empty | @UI.SelectionFields annotation missing or pointing at field that's not marked @Search.searchable at view level | Add @Search.searchable: true at the view level and @Search.defaultSearchElement: true on the right fields |
| Status field uncolored | No criticality binding | Add the criticality: '<field>Criticality' reference on the @UI.LineItem entry, AND a virtual <field>Criticality projection field that maps the code to FE criticality (0=Neutral, 1=Negative, 2=Critical, 3=Positive) |
| Nested facet (TimeEntries under Tasks) doesn't render | Some 7.5x releases don't honor _Tasks._TimeEntries LineItem facet paths | Render TimeEntries as a separate OP if you must — drill from the Task LineItem; verify on user's release |
| Controller extension throws "Override target not found" | Wrong controller path in manifest | LR: sap.fe.templates.ListReport.ListReportController; OP: sap.fe.templates.ObjectPage.ObjectPageController |
MCP server timed out | Long-running execute_functionality blocked by slow $metadata fetch | Increase the MCP timeout in .cursor/mcp.json (currently 600s); the default is usually enough for the talk-demo's service size |
| Generator hangs on a confirmation prompt | The MCP server tried to interactively confirm an overwrite | Pre-delete <fe_app>/ before re-running, or pass overwrite: true if the functionality details list it |
What this skill explicitly does NOT cover
- Multi-floorplan composition (Overview Page + LRO + ALP). Single LRO+OP is the talk demo's scope. Composition is a follow-up.
- Heavy custom rendering that genuinely can't fit into FE building blocks. If the user
needs that, they should pick the freestyle path (
modernize-ui5-app.md) instead. - Mock/local-service mode. The skill targets the live V4 RAP service. The Fiori MCP can generate apps for CAP projects, but that's a different flow.
- Authorization policy. FE renders what the service authorizes. PFCG / S_DEVELOP changes happen on the SAP side, not in this skill.
- Translation/localization beyond what the CDS
@EndUserText.labelprovides. FE picks labels from the service metadata; additional i18n lives in the FE app's i18n files. - CAP-side generation. This skill assumes a RAP backend; for CAP-only flows use the Fiori MCP server's CAP-targeted prompts directly.
Notes for the LLM running this skill
- The annotation-first discipline is the whole point. Never let the FE generator run
against an un-annotated
$metadata— the result is a useless shell. - The Fiori MCP server is experimental. Tool names and parameter shapes may have shifted
since this skill was written. Always start with
list_functionalitiesand adapt. - Annotations belong on the projection, not the root view. The SRVB exposes the projection; FE reads from there.
- Republish the SRVB after every CDS change that affects exposed annotations. ADT does not do this automatically.
- The "facets reference associations" pattern is the trickiest part: a facet of type
#LINEITEM_REFERENCEwithtargetElement: '_Tasks'only works if_Tasksis an exposed association on the projection. Check the projection'suse association _Tasks { ... }block. - Controller extensions are the escape hatch — when in doubt about whether something needs one, ask the user. The FE template can express more than people expect; only escalate when truly necessary.
- Reach for
mcp__fiori-mcp__search_docs(ormcp__sap-docs__searchwithtopic="fiori-elements") before guessing annotation syntax. SAP's annotation reference is the authoritative source. - If
mcp__fiori-mcp__list_functionalitiesreturns capabilities you didn't expect (e.g. "add page to existing app", "modify manifest"), surface them in the plan — they may simplify Phase 6 extension work. - Do not edit
manifest.jsonby hand to add pages or change routing if the Fiori MCP can do it viaexecute_functionality. The MCP's edits are schema-aware and survive re-generation; hand edits can be overwritten.
Sources
- SAP/open-ux-tools — fiori-mcp-server README
- npm: @sap-ux/fiori-mcp-server
- SAP Community: First Release of the SAP Fiori MCP Server
- SAP-samples/ui5con-2026-fiori-mcp-server (hands-on exercises)
- SAP-samples/fiori-mcp-server-hands-on
- sapdev.eu: Using Fiori MCP Server in VSCode with Cline or GitHub Copilot
Debug Slow SQL / OData
Find the root cause of a slow ABAP SQL or Fiori-Elements OData request and propose a fix — driving ARC-1's diagnostics first (GUI-free), then escalating to SAP GUI / Fiori apps only when the deeper signal needs them. The goal is not "it's slow" but why: which statement, what it scans, and what to change.
Use this when the user reports a slow report/transaction, a slow OData/Fiori list, a long-running CDS view, a timeout/dump under load, or "this query got slow after …".
Inputs (ask only for what's missing)
- What is slow — one of: an OData URL (copy from the browser Network tab), a CDS view / DDLS name, an ABAP program / class / report, a transaction code, or a table + access pattern.
- How slow / how often — a single slow call vs. slow-under-load vs. intermittent. (Routes you to per-request vs. aggregate analysis.)
- Reproducible? — can the user re-trigger it on demand (needed to arm a live trace)? On which system (DEV/QA/PROD) and as which SAP user?
- Recent change? — new code, new data volume, a transport, an index drop. Narrows the search fast.
If you only have a vague "X is slow", get the OData URL or the object name first — everything below keys off it.
The diagnostic ladder — stop at the rung that explains it
Work top-down. Each rung is cheaper than the next and usually tells you whether to descend.
Reachability — don't promise a plan you can't reach. Rungs 3–4 (profiler, ST05) need
SAP_ALLOW_WRITESto arm,S_ADT_RESwithURIcoverage for the trace resources, and the trace tools' backend authorizations (confirm with STAUTHTRACE) — and don't exist on NW 7.50. If arming returns writes disabled or a403, say so and stop at rung 2:odata_perf+cds_sql+SAPQueryalready pin a DB-bound root cause GUI-free. Tier-3–4 (the exact statement + execution plan) then depends on Basis/config, so hand the user the precise ST05/SAT steps below instead of pretending you reached the plan.
0. Orient (no execution)
SAPContext(action="deps", type="<type>", name=…)/SAPRead(type="DDLS", name=…)— read the CDS/ABAP source. Eyeball it for the usual suspects before measuring:LIKE '%term%'(leading wildcard = no index),SELECT … FROMwith noWHEREon a key,SELECT *, nestedSELECTin aLOOP(N+1), client-side filtering, missingFOR ALL ENTRIESpre-check, calculated fields forcing a full scan.SAPContext(action="impact", type="DDLS", name=…)— the CDS stack (projection → base views → tables). The slow view is often a thin projection over a heavy base.- Find the generator, not just the literal SQL. A slow
LIKE '%…%'/scan is often generated — by a search help, SADL/RAP, or a framework — not hand-written, so agrep/where-used for the literalSELECTcomes up empty. Trace the generator instead: for a value-help / type-ahead screen, the search help (DD30L.SELMETHOD+FUZZY_SEARCH,DD32Sfields) and its DSH/SADL classes (CL_DSH_*, the F4→WHERE conversion) viaSAPSearch/SAPNavigate/SAPRead. For an OData service, find its implementation: a V4/RAP binding →SAPRead(type="SRVB", name=…)→ the service definition → the CDS view (then usecds_sql, rung 2). The binding (SRVB) name often differs from the URL's service path — ifSRVB404s,SAPSearchthe service name to find the actual binding, or read the service definition (SRVD) directly for itsexpose … asentities. A classic SEGW / Gateway V2 service has no CDS → find the DPC class (SAPSearch "<SERVICE>_DPC*", read its*_get_entityset/*_get_entity/ expand /resolve_navigation_pathmethods) and skip rung 2. (Don't confuse SE91/WBMESSAGES, which loads one message class in memory and searches withCS, with a search-help path that issues a real DBLIKE.)
1. Where did the time go? (one cheap call)
For an OData / Fiori request:
SAPDiagnose(action="odata_perf", url="/sap/opu/odata4/sap/…/Entity?$filter=…")
Read the verdict:
db(gwappdbdominates) → the CDS/SQL query is the cost → go to rung 2.app(gwapp≫gwappdb, orgwappdbabsent) → ABAP/SADL logic, not the DB. Do not ST05-hunt for a slow query — find what implements the service (rung 0) and trace it (rung 3). Classic culprit is an$expandN+1 — isolate it by re-probing the URL with vs without$expand/$selectand watchgwappmove.framework(gwfw; on 7.50 often onlygwhub) → metadata / first-call / cold cache → re-probe warm. If onlygwhubis present, you do not have a DB/app split yet; descend to a trace if it is not just cold cache.auth(icfauth) → ICF/DCL authorization overhead.unknown→ no usable Gateway timing at all; confirm the URL is an OData/Gateway service on the SAP host.
(odata_perf needs SAP_ALLOW_DATA_PREVIEW; url must be a host-relative OData path under /sap/opu/odata
or /sap/opu/odata4 on the SAP host ARC-1 connects to — other paths are rejected. It does a GET, so use the
entity/list request from the Network tab, not a $batch POST.)
2. DB-bound → see and measure the actual SQL
SAPDiagnose(action="cds_sql", name="I_TheView")— the nativeCREATE VIEWthe CDS compiles to (read-only; verified on 7.50/758/816). Now you see the real joins,CASTs,COALESCEs, and whether a sub-view drags in extra tables.SAPQuery(sql="SELECT … FROM <cds-or-base> WHERE <the filter>")— returnscolumns/rowsplus datapreview metrics:queryExecutionTimeMs,sapReportedTotalRows,rowsReturned, andexecutedQueryString. Use the real filter values. SAP's count is diagnostic, not a result size or proof of a scan; aggregates, DISTINCT and UNION can report misleading counts. The timing may exclude SAP's separate count query.maxRowscaps returned rows, not SAP work; UNION can transfer more rows than requested. Confirm suspected scans with ST05/HANA plans and rows fetched. Record timeouts instead of repeatedly loweringmaxRows. (NeedsSAP_ALLOW_FREE_SQLfor freestyle SQL; multi-columnWHEREviaSAPRead(type="TABLE_QUERY")needsSAP_ALLOW_DATA_PREVIEW.)- Equality also slow? It's the view, not your filter. If
SAPQuerywith an exactWHERE key = '…'is as slow as aLIKE '%…%'(both tens of seconds), theLIKEis a red herring — the cost is the CDS itself: a wideSELECT DISTINCT, a deep join the filter can't start from (the filtered field isn't index-leading), or an aggregate /$count=true.cds_sqlshows the join order; the fix is to invert the join so the selective table leads, trim theDISTINCT/aggregate out of the list projection, or drop$count=trueon a large scan — not to touch theLIKE. - Compare signals: probe the OData URL, then run
SAPQueryon the underlying CDS/base — ifqueryExecutionTimeMsis close to the ODatagwappdb, the DB query is the cost; if OData is slow but the query is fast, it's the SADL/framework layer above. For the exact statement + execution plan, descend to ST05. - Recommending a HANA full-text /
CONTAINS/ fuzzy fix? You can't A/B-test it withSAPQuery— the ADT freestyle endpoint is Open-SQL-only and rejectsCONTAINS(...)/… CP '*x*'(400 "(" is not allowed). Prove it instead with an ST05 trace during a live reproduce of the real feature, or a one-off ABAP probe report. First confirm the table even has a full-text index:SAPQuery(sql="SELECT indexname, full_text FROM dd12l WHERE sqltab = '<TABLE>'")→full_text = 'X'.
3. App-bound → ABAP profiler trace (which code, which tables)
SAPDiagnose(action="traces") # list recent profiler traces
SAPDiagnose(action="traces", id="<id>", analysis="hitlist") # hottest call paths
SAPDiagnose(action="traces", id="<id>", analysis="dbAccesses") # which tables, counts, buffered?
The dbAccesses view tells you which tables a request hit and how often (N+1 shows up as a huge count on one
table). The hitlist tells you the ABAP hot path. ARC-1 can arm a profiler trace request itself —
SAPDiagnose(action="trace_start", …), then trace_requests to list and trace_cancel to clean up — or record
one in SAT/ST12; then list/analyze it with the traces action above.
Two caveats trace_start itself flags — heed them: (1) an HTTP trace captures the user's very next matching
HTTP call, so after arming make no other ARC-1/MCP calls until the user has reproduced — your own ADT calls
will consume the trap. (2) For HTTP/OData traces on HANA the profiler is weak: hitlist/statements are usually
empty (or 400 "Data is invalid…"), and business tables hide inside a <DB Access from Kernel> bucket — use
dbAccesses only for "did we touch table X, how often", and use ST05 (rung 4) for the actual OData SQL +
timings. The profiler is richest for dialog/report/RFC traces of ABAP-side code.
4. The exact SQL + plan → ST05 SQL trace
ARC-1 can arm/disarm the ST05 SQL trace and point you to the records (it can't read the records over ADT — SAP has no SQL-record API; record viewing is the TMC Fiori app / SAP GUI ST05):
SAPDiagnose(action="sql_trace_state") # is a trace already on?
SAPDiagnose(action="set_sql_trace_state", sqlOn=true, user="<SAPUSER>") # arm, filtered to the user (needs SAP_ALLOW_WRITES)
# → user reproduces the slow request now ←
SAPDiagnose(action="sql_trace_directory") # SAP's "SQL Trace Analysis" deep-link
SAPDiagnose(action="set_sql_trace_state", sqlOn=false) # always disarm when done
Then read the records (see "SAP GUI / Fiori escalation"). The record list gives you the exact SELECT, its
duration, rows fetched, the object, and (in ST05) the EXPLAIN / execution plan + buffer state.
Available on 758/816; not on NW 7.50 (the /st05/trace ADT API returns 404 there — use SAP GUI ST05).
Reading the records (there is no sql_trace_records/sql_trace_read ADT action — sql_trace_directory
only returns the viewer link): open the deep-link (TMC "SQL Trace Analysis") or SAP GUI ST05 → Display
Trace → pick the app server + your trace file → sort by Duration desc → per row read the SQL text,
Duration, Records (rows fetched), Object (table/view); double-click the slowest → Explain for the HANA
plan. Look for: extra hits on association/text tables (SADL expansion), repeated identical SELECTs (N+1), or
Records ≫ visible rows (selectivity).
If a perf endpoint 403s with "Service cannot be reached", ARC-1 surfaces an
icf-service-inactivehint — activate the named SICF node (/sap/bc/stmcfor the trace UI) in tcode SICF.
5. Static check (anytime)
SAPDiagnose(action="atc", type="<type>", name=…, variant="PERFORMANCE_DB") — flags perf anti-patterns
statically (it won't catch a runtime LIKE scan that depends on data, but it's free and catches the obvious
ones).
SAP GUI / Fiori escalation (when ARC-1's GUI-free signals aren't enough)
ARC-1 is GUI-free up to the point of reading SQL-trace records and execution plans — for those, escalate. Tell the user exactly what to open and what to look for; or, if you have a desktop/Chrome MCP and authorization, drive it yourself (never on PROD without explicit sign-off).
| Tool | Where | What it gives you that ARC-1 can't |
|---|---|---|
| ST05 (SQL/RFC/buffer/enqueue trace) | SAP GUI | The recorded SELECTs with duration + rows; "Explain" → the DB execution plan; identical-/similar-statement grouping; buffer hits. The ground truth for "which statement and why". |
| SQL Trace Analysis | Fiori app (the sql_trace_directory deep-link) | The same ST05 records in a browser (TMC) — use when SAP GUI isn't available. Needs /sap/bc/stmc SICF active. |
| ST12 / SAT | SAP GUI | Combined ABAP+SQL trace with aggregation — best for "where does the time really go" across app+DB in one capture. |
| DBACOCKPIT / HANA | SAP GUI / HANA Studio / DBeaver | EXPLAIN PLAN, PlanViz, M_SQL_PLAN_CACHE, table/index sizes, missing-index hints, optimizer stats freshness. The HANA-side root cause (column-store scan, no pruning, stale stats). |
| ST22 / SM50 / SM66 | SAP GUI | Dumps (e.g. TIME_OUT, TSV_* memory) and what work processes are stuck on under load. |
| SE11 / SE14 | SAP GUI | Indexes on the table, their fields, and whether the slow WHERE matches a usable index prefix. |
| ABAP Cross Trace | ADT (/sap/bc/adt/crosstrace/*, 758+) | RAP/OData-aware cross-layer trace incl. OData V4 request types — the strategic ADT-native record reader (ARC-1 follow-up; not yet a tool). |
Capturing an OData request for odata_perf: browser DevTools → Network → click the slow $batch/entity
request → copy the path after the host (e.g. /sap/opu/odata4/sap/zsrv/…/Entity?$filter=…&$top=…). That path is
the url argument.
Root-cause catalog (pattern → confirm → fix)
| Symptom in the trace/SQL | Likely cause | Confirm | Typical fix |
|---|---|---|---|
Huge rows fetched ≫ rows shown; long duration | Full scan / poor selectivity | ST05 high rows fetched and execution plan; SAPQuery's count alone cannot establish a scan | Add a WHERE on indexed fields; add a secondary index (SE11); push the filter into the CDS |
LIKE '%term%' | Leading-wildcard = index unusable | Read DDLS/ABAP source | Search help / fuzzy (HANA) / full-text index; anchor the pattern; pre-filter |
| Same table hit thousands of times | N+1 (SELECT in LOOP) | traces dbAccesses shows a giant count on one table | FOR ALL ENTRIES / a join / read-all-then-loop; RAP: prefetch |
SELECT * then use 2 fields | Over-fetch | cds_sql / source | Select only needed fields; trim the CDS projection |
| Fast in DEV, slow in PROD | Data volume / stale stats / different plan | Compare EXPLAIN + table sizes (DBACOCKPIT) | Refresh optimizer stats; add index; partition |
gwappdb small but OData slow | SADL / determinations / virtual elements / auth (DCL) | odata_perf verdict app/auth; profiler hitlist | Move logic to the DB/CDS; simplify DCL; cache; avoid per-row ABAP virtual elements |
| Slow only first call | Metadata / cold cache | odata_perf verdict framework; re-probe warm | Expected; warm-up; don't optimize the query |
TIME_OUT / memory dump under load | Unbounded result / missing paging | ST22 + ST05 | Server-side paging ($top/$skip); add filters; package the work |
Worked example (real, a4h S/4HANA 2023)
A "message-text search screen is slow" complaint. The query behind it:
SAPQuery(sql="SELECT sprsl, arbgb, msgnr, text FROM t100 WHERE text LIKE '%error%'")
→ { sapReportedTotalRows: 12549, queryExecutionTimeMs: 49.086, rowsReturned: 100, rowLimitReached: true,
executedQueryString: "SELECT … FROM T100 WHERE TEXT LIKE '%error%' … UP TO 100 ROWS" }
Read it: SAP reports 12 549 matches for this plain projection; the leading-wildcard LIKE '%…%'
suggests poor selectivity. Confirm the scan and index use in ST05/HANA. The result the user actually wanted
was a handful of rows. Possible fix: anchor the search / add a search help or full-text index /
pre-filter on an indexed field first. For the HANA plan + rows-fetched, arm an ST05 trace (rung 4), reproduce,
and open the directory deep-link.
This is the simple case — a single-table scan where the leading wildcard really is the bottleneck. On a
wide CDS view it often is not: if an exact-match WHERE key = '…' is just as slow as the LIKE, the cost is
the view's joins / DISTINCT / $count, not the wildcard (rung 2, "Equality also slow?"). Measure both before
you blame the LIKE.
Output
Deliver a tight diagnosis, not a tool log:
- Verdict — DB / app / framework / auth, with the number that proves it (e.g. "
gwappdb412 ms ofgwtotal480 ms"). Cite the SAP figure (gwtotal/gwappdb), neverwallClockMs: wall-clock also counts network/MCP/proxy (odata_perfreturns that gap asclientWaitMs), so whenclientWaitMsdwarfsgwtotalthe latency is the landscape, not the query. - The statement — the offending SQL (from
cds_sql/ ST05), ST05 rows fetched and the execution plan. TreatSAPQuery sapReportedTotalRowsonly as supporting diagnostic data. - Root cause — one sentence, mapped to the catalog above.
- Fix — concrete and minimal (the index to add, the filter to push down, the N+1 to collapse), with the cheapest option first and the trade-off named.
- Evidence — the exact ARC-1 calls run + any ST05/HANA-plan capture, so the user can re-verify.
Always disarm any trace you armed. On PROD, prefer read-only signals (odata_perf, cds_sql, SAPQuery,
read-only traces) and get explicit sign-off before arming an ST05 trace or touching state.
Explain ABAP Code
Explain ABAP objects with full dependency context and optional ATC code quality analysis.
This skill replicates SAP Joule's "Explain Code" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices). It goes beyond J4D by providing compressed dependency graphs via SAPContext.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Object type | Auto-detect via SAPSearch | Don't make user look up the type |
| Depth | Overview | Start high-level, user can ask for detail |
| ATC | No | Only run if user asks about code quality |
| Dependencies | Fetch via SAPContext | Always get the dependency graph |
| BDEF handler class | Discover from implementation in class clause | The behavior logic lives in the bound pool class |
Input
The user provides an ABAP object name (e.g., ZCL_TRAVEL_HANDLER, ZI_SALESORDER, Z_REPORT_POSTING).
Only the object name is required. If the user provides just an object name, auto-detect the type and proceed immediately with an overview explanation.
Optionally, the user may specify:
- Object type (default: auto-detect)
- Explain ATC findings? (default: no)
- Depth — "overview" or "detailed" (default: overview)
Step 1: Read the Object
1a. Resolve type (if not provided)
If the user didn't specify a type, search for the object:
SAPSearch(query="<object_name>")
Use the first result's type. If ambiguous (multiple matches), ask the user.
1b. Read the source code
SAPRead(type="<type>", name="<object_name>")
1c. For classes — also get the method listing
SAPRead(type="CLAS", name="<class_name>", method="*")
This returns all methods with their signatures, visibility (public/protected/private), and parameter types. Essential for understanding the class API.
1d. For CDS entities — also get the structured field list
SAPRead(type="DDLS", name="<entity_name>", include="elements")
Returns a formatted listing of all fields with key markers, aliases, associations, and expression types.
1e. (Optional) Read related artifacts
Depending on type, also read associated objects:
- CLAS:
SAPRead(type="CLAS", name="<class>", include="testclasses")— check if tests exist - DDLS:
SAPRead(type="BDEF", name="<entity>")— check if behavior definition exists;SAPRead(type="DCLS", name="<entity>_DCL")— check CDS access control;SAPRead(type="DDLX", name="<entity>")— check for metadata extensions - BDEF:
SAPRead(type="DDLS", name="<entity>")— read the associated CDS view
These may fail if the related artifact doesn't exist — that's fine, skip them.
1f. For behavior definitions (BDEF) — walk the RAP graph
A behavior definition is only meaningful together with its bound CDS root entity and its behavior pool (handler) class. When the object is a BDEF, do this instead of (or in addition to) the steps above:
Read the BDEF source:
SAPRead(type="BDEF", name="<bdef_name>")
Identify the implementation type + bound pool class by reading the BDEF source:
- First non-comment token:
managed/unmanaged/projection/abstract/interface— this is the implementation kind strict ( 2 )→ latest RAP syntax checks;with draft/with collaborative draft→ draft-enabled- The clause
... implementation in class <ZBP_NAME> unique;names the behavior pool class. Extract<ZBP_NAME>with a regex likeimplementation\s+in\s+class\s+(\S+). (Aprojection;BDEF may have no pool class — it reuses the base behavior viause ....)
Read the behavior pool class (the handler logic lives in its local includes — usually CCIMP):
SAPRead(type="CLAS", name="<ZBP_NAME>", include="implementations")
If that returns empty, also try include="definitions" (CCDEF) and the main include. The local handler classes are named lhc_<alias> and each FOR DETERMINE / FOR VALIDATE / FOR MODIFY method implements the corresponding BDEF declaration.
Read the bound CDS root entity to understand the data model the behavior governs:
SAPRead(type="DDLS", name="<root_cds>", include="elements")
The root CDS name appears in define behavior for <root_cds> alias <alias>.
For a projection BDEF, also read the underlying base BDEF (the one it projects) to see which operations are reused (use create; use update; use action ...).
These reads may fail if an artifact doesn't exist (e.g. a pure abstract BDEF) — skip gracefully.
1g. For function groups (FUGR) — read the full code tree
A function group's logic is spread across nested includes: the main program references the TOP (global data) and UXX (function-module dispatcher) includes, and the actual FUNCTION … ENDFUNCTION bodies live in further-nested LZ<grp>U01/U02… includes pulled in from UXX (PBO/PAI subroutines in …O…/…I… includes). Read the whole tree in one call with expand_includes:
SAPRead(type="FUGR", name="<group>", expand_includes=true)
This returns the main source plus every nested include (recursively, depth/count-capped), each prefixed with a === <name> === marker — so you get all the function module bodies and flow logic in one read. Without expand_includes, you only get the function-module list.
Screen flow is not available. Dynpros (screens) and GUI status (CUA) are not exposed by ADT over REST — they are SAPGUI-only (SE51/SE41), and the endpoints return 404. So for a FUGR you can explain the business purpose, function-module responsibilities, and flow logic from the code, but not the screen layout / PBO-PAI screen sequence beyond what the PBO/PAI module code reveals. State this limitation if the user asks about the screen flow specifically.
Step 2: Get Dependency Context
SAPContext(type="<type>", name="<object_name>")
This automatically extracts all dependencies and fetches compressed public API contracts for each. It provides:
- For classes: used interfaces, superclasses, injected dependencies, called methods on other classes
- For CDS views: data sources (FROM, JOIN), associations, compositions, projection bases
- For programs: called function modules, used classes, included programs
For complex objects with deep dependency chains, use depth=2:
SAPContext(type="<type>", name="<object_name>", depth=2)
If SAPContext fails (e.g., unsupported type), fall back to manual reads of key dependencies identified in the source code.
Supported types: SAPContext accepts CLAS, INTF, PROG, FUNC, DDLS (on-prem) / CLAS, INTF, DDLS (BTP). It does not accept BDEF. So when explaining a BDEF, run dependency/impact analysis on the bound CDS root entity instead:
SAPContext(action="impact", name="<root_cds>")
action="impact" (DDLS only) returns the downstream blast radius — projection views, consumption views, and services that build on the behavior. This is the "dependencies / who consumes this" answer for a behavior definition. For the handler class internals, run SAPContext(type="CLAS", name="<ZBP_NAME>").
Step 3: (Optional) Run ATC Check
If the user asked to explain code quality or ATC findings:
SAPDiagnose(action="atc", type="<type>", name="<object_name>")
If a specific ATC variant is needed (e.g., S/4HANA readiness):
SAPDiagnose(action="atc", type="<type>", name="<object_name>", variant="<variant>")
Group findings by priority:
- Priority 1 (Errors): Must-fix issues — deprecated APIs, syntax problems
- Priority 2 (Warnings): Should-fix — performance, maintainability
- Priority 3 (Info): Nice-to-fix — style, conventions
- Check each finding's
hasQuickfixflag. Iftrue, mention that SAP provides a machine-applicable quickfix proposal for that location.
Step 4: (Optional) Research with mcp-sap-docs
For unfamiliar SAP APIs found in the source code:
search("<class_or_function_name> ABAP documentation")
For ATC findings that need explanation:
search("<checkTitle> simplification item S/4HANA")
For SAP Notes if available:
sap_notes_search(q="<finding_or_api_name>")
Use documentation results to enrich the explanation with official SAP context.
Step 5: Explain
Present a structured explanation with the following sections. Adapt depth based on user preference (overview vs detailed).
Summary
- Purpose: What the object does in one sentence
- Type: Object type and classification (e.g., "RAP behavior pool", "interface CDS view", "ALV report")
- Scope: How many methods/fields/lines, complexity assessment
Public API
For classes:
- Key public methods with their signatures and purpose
- Implemented interfaces
- Constructor parameters (especially injected dependencies)
- Events raised
For CDS views:
- Exposed fields with business meaning
- Parameters (if any)
- Associations available for navigation
Business Logic
- Core processing flow (what happens when key methods are called)
- Important business rules and conditions
- Data transformations and calculations
- Error handling approach
Behavior Definition (if the object is a BDEF)
Structure the explanation around the RAP behavior graph you read in Step 1f:
- Implementation kind: managed / unmanaged / projection / abstract / interface — and what that implies (framework-provided CRUD vs custom handlers vs reuse/typing layer). Note
strict(2)andwith draftif present. - Business purpose: derived from the bound CDS root entity + the BDEF header comments.
- Per-entity model: for each
define behavior for <CDS> alias <alias>— persistent table,lock master/lock dependent,authorization master/authorization dependent,etag. - Operations (the CRUD graph):
create/update/delete, create-by-association (association _X { create; }), and whether draft actions (Edit,Activate,Discard,Resume,Prepare) are present. - Determinations:
determination <name> on save|on modify— what each derives, read from the matchingFOR DETERMINEmethod in the pool class. - Validations:
validation <name> on save— what each enforces, from theFOR VALIDATEmethod. - Actions / functions:
action <name>(+static/factory/parameter/result), from theFOR MODIFY/FOR READmethods. - Side effects:
side effects { ... }declarations (what UI refresh / recompute they trigger). - Field controls:
field ( readonly | mandatory | numbering : managed ),mapping for <table>. - For a projection BDEF: which base operations/actions are reused via
use ....
Dependencies
From SAPContext results:
- Direct dependencies with their roles (data source, helper, framework)
- Key interfaces/classes used and why
- External system calls (RFC, HTTP, etc.) if any
- Database tables accessed
Security / Authorization
- CDS access control (
DCLS) rules if present (row-level restrictions, role mapping) - Behavior-level authorization hints (
authorization master,authorization dependent by) when present in BDEF - Practical impact: what data/operations may be restricted at runtime
Code Quality (if ATC was run)
From ATC results:
- Summary: total findings by priority
- Top findings with explanation of impact
- Recommendations for improvement
Follow-up Options
Offer the user next steps:
- "Want me to explain a specific method in detail?"
- "Want me to get SAP quickfix proposals for the ATC findings?" (→
SAPDiagnose(action="quickfix")) - "Want me to apply SAP's quickfix for ?" (uses SAP-verified fix proposals +
apply_quickfix) - "Want me to analyze the ATC findings and suggest fixes?" (→ migrate-custom-code skill)
- "Want me to generate unit tests for this class?" (→ generate-abap-unit-test skill)
- "Want me to show the full dependency graph?" (→ SAPContext with depth=2)
- For a BDEF: "Want me to implement a missing determination/validation/action body?" (→ generate-rap-logic skill) or "Want me to scaffold the behavior pool handlers?" (→
SAPWrite(action="scaffold_rap_handlers"))
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
| Object not found | Name misspelled or object doesn't exist | Use SAPSearch to find similar names |
| SAPContext fails | Object type not supported for dependency analysis | Fall back to manual reads of key dependencies found in source |
| ATC check returns no findings | No ATC configuration or clean code | Inform user — no findings is good news |
| ATC variant not found | Specified variant doesn't exist on system | Run default ATC, list available variants |
| Method listing empty | Object is not a class or has no methods | Skip method listing, explain from source only |
| Source is empty | Object exists but has no source (e.g., generated proxy) | Inform user, try reading related objects instead |
SAPContext rejects BDEF type | BDEF isn't a supported SAPContext type | Run SAPContext(action="impact", name="<root_cds>") on the bound CDS root instead |
| BDEF pool class not found | projection; BDEF (no own pool) or class name parsed wrong | Skip the class read; explain from the projection's use clauses + base BDEF |
Notes
BTP vs On-Premise Differences
- BTP: Fewer object types available — no PROG, INCL, FUGR. Focus on released APIs and ABAP Cloud objects. DDLS, DCLS, CLAS, INTF, BDEF, DDLX, SRVD are the primary types. ATC variants are limited to cloud readiness checks.
- On-Premise: Full range of object types. All ATC variants available. Can explain legacy objects (FORM routines, function modules, classic reports).
What This Skill Does NOT Do
- No code modification: This skill only reads and explains — it never writes or changes code
- No refactoring suggestions: For improvement suggestions, use ATC analysis or migration skill
- No test generation: For generating tests, use generate-abap-unit-test or generate-cds-unit-test skills
- No cross-system comparison: Explains objects on one system at a time
When to Use This Skill
- When onboarding to an unfamiliar codebase
- When investigating a bug or understanding existing behavior
- When reviewing code quality before a migration
- When documenting an undocumented object
- When understanding the impact of changing a shared class or CDS view
Generate ABAP Unit Test
Generate ABAP Unit tests for classes with dependency analysis, test doubles, and method-level surgery.
This skill replicates SAP Joule's "Unit Test Generation" capability for ABAP classes by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices). Unlike the CDS unit test skill which targets CDS entities, this skill targets ABAP classes and uses interface-based test doubles instead of CDS Test Double Framework.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Test class name | ltc_<short_class_name> | ABAP Unit tests for a global class belong in its local testclasses (CCAU) include |
| Methods to test | All public methods | User can narrow after seeing the list |
| Package | $TMP | Fast prototyping |
| Risk level | HARMLESS | Test doubles don't modify real data |
| Duration | SHORT | Unit tests should be fast |
| Mock strategy | Interface-based test doubles | Cleanest pattern for dependency injection |
Input
The user provides an ABAP class to test (e.g., ZCL_TRAVEL_HANDLER).
Only the class name is required. If the user provides just a class name, apply Smart Defaults and proceed immediately.
Optionally, the user may specify:
- Test class name (default: local class
ltc_<short_class_name>inside the target class'stestclassesinclude) - Methods to test (default: all public methods)
- Package (default:
$TMP) - Transport request (only needed for non-
$TMPpackages)
Step 1: Gather Class Context
Read the class, its methods, dependencies, and any existing tests.
1a. Read the full class source
Prefer the structured format to get metadata and all includes (including existing tests) in one call:
SAPRead(type="CLAS", name="<class_name>", format="structured")
This returns JSON with metadata (description, category, package) and decomposed source (main, testclasses, definitions, implementations, macros). The testclasses field contains existing test code if any — useful for analyzing what's already covered without a separate fetch.
Alternatively, for just the main source:
SAPRead(type="CLAS", name="<class_name>")
1b. List all methods with signatures
SAPRead(type="CLAS", name="<class_name>", method="*")
Returns all methods with their signatures and visibility (public/protected/private). Use this to understand the class API and identify which methods to test.
1c. Get dependency context
SAPContext(type="CLAS", name="<class_name>")
Automatically extracts all dependencies and fetches compressed public API contracts for each. This gives you:
- Implemented interfaces and their methods
- Superclass hierarchy
- Injected dependencies (constructor parameters)
- Used classes and their public APIs
- Database tables accessed
For complex classes with deep dependency chains, use depth=2:
SAPContext(type="CLAS", name="<class_name>", depth=2)
1d. (Optional) Read existing test classes
If you used format="structured" in Step 1a, the testclasses field already contains existing test code (or null if none) — skip this step.
Otherwise, fetch test classes separately:
SAPRead(type="CLAS", name="<class_name>", include="testclasses")
This may fail if no test classes exist — that's fine. If tests exist, analyze them to avoid duplicating coverage and to follow existing test patterns.
Step 2: Analyze Methods and Propose Test Cases
For each public method, analyze the source code to identify testable scenarios.
Dependency Classification
Classify each dependency the class uses:
| Category | What to Look For | Test Strategy |
|---|---|---|
| Mockable | Constructor injection via interfaces (if_*, zif_*) | Create test double implementing the interface |
| Stubbable | Database access (SELECT, INSERT, UPDATE, DELETE) | Prepare fixture data in SETUP, or use test double for DB layer |
| Transparent | Internal private/protected helper methods | Don't mock — they execute normally |
| Framework | Static calls to SAP framework classes (e.g., cl_abap_context_info) | Wrap in injectable interface or accept limitation |
Analysis Per Method
For each public method, identify:
- Branches: IF/CASE/COND/SWITCH statements — each branch needs a test
- Error paths: RAISE EXCEPTION, TRY-CATCH blocks — test error scenarios
- Return values: What the method produces — verify outputs
- State changes: Side effects on instance attributes or database — verify mutations
- Dependencies used: Which mockable dependencies are called — set up expectations
Output to User
Present the identified test cases as a numbered list grouped by method:
Identified test cases for ZCL_TRAVEL_HANDLER:
Method: CREATE_TRAVEL (public)
1. [HAPPY] test_create_travel_success — Create travel with valid data, verify travel ID returned
2. [ERROR] test_create_no_customer — Missing customer, expect CX_TRAVEL_ERROR
3. [BRANCH] test_create_with_discount — Discount > 0 triggers calculation path
Method: VALIDATE_DATES (public)
4. [HAPPY] test_dates_valid — End date after begin date
5. [ERROR] test_dates_reversed — Begin date after end date, expect exception
6. [EDGE] test_dates_same_day — Same begin and end date, should be valid
Ask the user: "Which test cases should I generate? (all / specific numbers / skip any?)"
If the user says "all" or doesn't respond with preferences, generate all.
Step 3: Fetch Test Framework Reference
Use mcp-sap-docs to get the latest ABAP Unit and test double patterns.
search("ABAP Unit cl_abap_unit_assert")
search("test double interface mock ABAP")
Use the returned documentation to inform the generated code patterns. Key things to verify:
- Correct
cl_abap_unit_assertassertion method names (assert_equals,assert_initial,assert_not_initial,assert_bound,fail) - Test double creation patterns for interfaces
FOR TESTINGclass and method syntax- Risk level and duration annotations
Step 4: Generate Test Class
Generate a complete ABAP test class following this structure:
Template
"! @testing <CLASS_UNDER_TEST>
CLASS <test_class_name> DEFINITION
FINAL
FOR TESTING
DURATION SHORT
RISK LEVEL HARMLESS.
PUBLIC SECTION.
PROTECTED SECTION.
PRIVATE SECTION.
CLASS-DATA cut TYPE REF TO <class_under_test>.
" Test doubles for mockable dependencies
CLASS-DATA mock_<dep1> TYPE REF TO <interface_1>.
CLASS-DATA mock_<dep2> TYPE REF TO <interface_2>.
CLASS-METHODS class_setup RAISING cx_static_check.
CLASS-METHODS class_teardown.
METHODS setup.
"! <description of test case 1>
METHODS <test_method_1> FOR TESTING RAISING cx_static_check.
"! <description of test case 2>
METHODS <test_method_2> FOR TESTING RAISING cx_static_check.
" ... one method per selected test case
ENDCLASS.
CLASS <test_class_name> IMPLEMENTATION.
METHOD class_setup.
" One-time initialization — create test doubles
" If using a test double framework:
" mock_<dep1> = cl_abap_testdouble=>create( '<interface_1>' ).
" Or create a local test double class (see below)
ENDMETHOD.
METHOD class_teardown.
" Clean up
ENDMETHOD.
METHOD setup.
" Per-test CUT instantiation with fresh state
" Inject test doubles via constructor
cut = NEW <class_under_test>(
io_<dep1> = mock_<dep1>
io_<dep2> = mock_<dep2>
).
ENDMETHOD.
METHOD <test_method_1>.
" Arrange — configure mock behavior
" cl_abap_testdouble=>configure_call( mock_<dep1>
" )->returning( VALUE #( <expected_return> ) )->and_expect( )->is_called_once( ).
" mock_<dep1>-><method>( ).
" Act — call the method under test
DATA(lv_result) = cut-><method>( <params> ).
" Assert — verify expected behavior
cl_abap_unit_assert=>assert_equals(
act = lv_result
exp = <expected_value>
msg = '<assertion message>' ).
ENDMETHOD.
METHOD <test_method_error>.
" Arrange — set up conditions that trigger the error
" Act & Assert — expect exception
TRY.
cut-><method>( <invalid_params> ).
cl_abap_unit_assert=>fail( msg = 'Expected exception was not raised' ).
CATCH <exception_class> INTO DATA(lx_error).
" Optionally verify exception details
cl_abap_unit_assert=>assert_not_initial(
act = lx_error->get_text( )
msg = 'Exception message should not be empty' ).
ENDTRY.
ENDMETHOD.
" ... more test methods
ENDCLASS.
Local Test Double Pattern
When cl_abap_testdouble is not available or the interface is complex, create a local test double class:
" Local test double — defined in the test include
CLASS lcl_mock_<dep> DEFINITION FOR TESTING.
PUBLIC SECTION.
INTERFACES <interface>.
DATA last_<method>_input TYPE <param_type>.
DATA <method>_result TYPE <return_type>.
ENDCLASS.
CLASS lcl_mock_<dep> IMPLEMENTATION.
METHOD <interface>~<method>.
last_<method>_input = <param>.
<return_param> = <method>_result.
ENDMETHOD.
ENDCLASS.
Test Data Generation Rules
Follow these principles when generating test data:
- Minimal data: Use the fewest values needed to exercise the scenario. Typically 1-3 records per test.
- Obvious values: Choose values where the expected result is trivially verifiable:
- For calculations: use 100.00 - 10.00 = 90.00, not 37.83 - 4.27
- For status checks: use exactly the status values from the IF/CASE expression
- For string operations: use short, recognizable strings
- Type-correct: Match ABAP types exactly:
- Use
'001'for NUMC fields (string with leading zeros) - Use
'100.00'for DEC/CURR fields - Use
'20260101'for DATS fields - Use
abap_true/abap_falsefor ABAP_BOOL
- Use
- Deterministic: Never use
sy-datum,sy-uzeit,cl_abap_context_info=>get_system_date( ), or random values - Isolated: Each test method should be self-contained — setup method ensures fresh CUT state
Naming Conventions
- Test class: local class
ltc_<short_class_name>in the class'stestclassesinclude - Test methods:
test_<method>_<scenario>(e.g.,test_create_success,test_validate_no_date) - Use snake_case for method names (ABAP convention for test methods)
- Keep method names under 30 characters
- Mock variables:
mock_<short_dep_name>(e.g.,mock_persistence,mock_validator)
Step 5: Preview and Confirm
Show the user the complete generated testclasses include source code and ask:
"Here's the generated testclasses include. Should I write it to the SAP system? (yes / edit first / cancel)"
If the user wants edits, incorporate them before proceeding.
Step 6: Write, Activate, and Test
6-pre. Lint-check generated code (optional)
Before writing, validate the generated code against lint rules:
SAPLint(action="lint", source="<generated_testclasses_include>", name="<class_under_test>")
Fix any lint findings before proceeding. Pre-write lint validation also runs automatically when enabled (default: on).
6a. Write the local test class to the target class's testclasses include
SAPWrite(action="update", type="CLAS", name="<class_under_test>", include="testclasses", source="<generated_testclasses_include>", transport="<transport>")
This is a local include write, not a separate global class create. Do not pass a lock handle or add lock/unlock code to the ABAP source; ARC-1 performs the ADT lock -> initialize missing CCAU include -> write -> unlock sequence internally. On a fresh class, ARC-1 auto-creates the missing testclasses include before writing.
6b. Update existing tests
SAPWrite(action="update", type="CLAS", name="<class_under_test>", include="testclasses", source="<full_updated_testclasses_include>", transport="<transport>")
For a small fix to an existing local test method, use method surgery after the include exists:
SAPWrite(action="edit_method", type="CLAS", name="<class_under_test>", method="<ltc_class>~<failing_method>", source="<fixed_method_body>")
Note: For update actions, transport is recommended but not always required. ARC-1 auto-propagates the lock-provided corrNr when no explicit transport is supplied.
6c. Activate the class under test
SAPActivate(type="CLAS", name="<class_under_test>")
Activation returns structured responses with detailed error/warning messages including line numbers. Use these to pinpoint exact issues.
6d. Run the unit tests
SAPDiagnose(action="unittest", type="CLAS", name="<class_under_test>")
6e. Report results and fix failures
Show the user:
- Number of tests passed / failed / skipped
- For any failures: the assertion message and which test method failed
- Suggested fixes for any failures
If tests fail:
- Analyze the failure message
- Determine if it's a mock setup issue, assertion issue, or CUT logic issue
- Fix the specific test method using method surgery:
SAPWrite(action="edit_method", type="CLAS", name="<class_under_test>", method="<ltc_class>~<failing_method>", source="<fixed_source>") - Re-activate and re-run
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
class_setup fails | Wrong CUT instantiation — missing constructor parameter or wrong type | Check CUT constructor signature, ensure all required dependencies are injected |
| Mock injection fails | Constructor parameter type mismatch — mock doesn't implement expected interface | Verify interface name, check if CUT expects concrete class instead of interface |
| Assertion fails | Wrong expected value or test data | Re-check CUT method logic, adjust expected value or input data |
| Activation error | Syntax error in generated code — typo, wrong type, missing variable declaration | Read activation error, fix syntax, re-activate |
cl_abap_testdouble not found | Test double framework not available on system (older releases) | Use local test double class pattern instead |
| Method not found on CUT | Method is private or protected — not callable from test | Test only public methods; for protected, use FRIENDS clause |
testclasses/CCAU include missing | Fresh class has no ABAP Unit include yet | Use SAPWrite(action="update", type="CLAS", include="testclasses", source=...); ARC-1 auto-initializes it |
Method not found in edit_method | The local ltc_* method does not exist yet, or the wrong local class name was used | First write the full testclasses include with update include="testclasses", then use edit_method for existing methods |
Notes
BTP vs On-Premise Differences
- BTP: Write local
ltc_*test classes into custom Z*/Y* classes. Must use ABAP Cloud syntax — no classic ABAP statements. Only released APIs are available for mocking.cl_abap_testdoubleis available. Constructor injection is the standard pattern. - On-Premise: Full flexibility. Can use classic ABAP.
cl_abap_testdoubleavailable from 7.51+. On older systems, use local test double classes.
What This Skill Does NOT Do
- No CDS unit tests: For CDS entities, use generate-cds-unit-test skill (uses CDS Test Double Framework)
- No integration tests: This generates isolated unit tests with mocked dependencies, not end-to-end flows
- No performance tests: Use ABAP profiler (SAPDiagnose) for performance analysis
- No RAP behavior tests: For RAP BO test doubles, a separate pattern is needed
When to Use This Skill
- When a class has non-trivial business logic in public methods
- When the class uses dependency injection (constructor parameters with interfaces) — ideal for mocking
- When the user wants test coverage as a starting point for TDD
- When refactoring a class and wanting regression tests before making changes
- NOT for classes with no public methods or pure data containers (structures/constants) — if analysis in Step 2 finds no testable scenarios (no branches, no error paths, no meaningful return values), warn the user: "This class has no non-trivial public methods to test. Consider whether unit tests add value here."
Generate CDS Analytics Star Schema
Generate a CDS analytical model — a star schema consisting of a cube view (@Analytics.dataCategory: #CUBE), one or more dimension views (#DIMENSION), and text views (#TEXT) — on top of a RAP business object or a plain DDIC table.
This skill replicates SAP Joule's "CDS Analytical Model Generation" capability (basic + extended scope) by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices). Basic scope = cube + reuse existing dimensions. Extended scope = also generate new dimensions, and start from a DDIC table (not just a RAP BO).
Prerequisites — read this first
- Requires SAP_BASIS 7.5x with the analytics annotations. Verify with
SAPManage(action="probe")(rap.available). If RAP/CDS isn't available, stop. - The output is a set of interdependent CDS views (cube → dimensions → texts). They must be created as inactive drafts and activated together so SAP's activator resolves the cross-references in one pass. This skill uses
SAPWrite(action="batch_create", activateAtEnd: true)for exactly that.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Object type | DDLS | Cube/dimension/text are all CDS data definitions |
| Package | $TMP | Fast prototyping; ask before a transportable package |
| Activation | batch_create + activateAtEnd: true | Cross-references resolve in one terminal pass |
| Authorization | #NOT_REQUIRED (cube/dimension) | Standard for analytical interface views |
| Naming | ZI_<X>_Cube, ZI_<X>_Dim, ZI_<X>_Txt | Clear star-schema roles (match the casing the templates use) |
Input
The user provides either:
- A RAP business object root entity / behavior pool (e.g.
ZBP_R_TRAVELorZI_Travel), or - A DDIC table (e.g.
ZTRAVEL), or - An interface CDS view to use as the fact source.
Optionally: which numeric fields are measures, which fields are dimensions, target package, and whether to generate new dimension views or reuse existing ones.
Step 1: Resolve and read the source
1a. RAP BO input — find the bound CDS root entity
If the user names a behavior pool class (ZBP_*), read the class metadata to find the root entity it's bound to:
SAPRead(type="CLAS", name="<ZBP_class>", format="structured")
Look for the bound root entity reference. Then read that CDS root entity (next step). If the user already named the CDS root entity / interface view, skip to 1c.
1b. DDIC table input — read the table structure
SAPRead(type="TABL", name="<table>")
Capture the field list with types. Identify candidate keys, dimension fields (foreign keys, characteristics), and numeric measure fields (amounts, quantities, counts).
1c. CDS view input — read source + elements
SAPRead(type="DDLS", name="<view>")
SAPRead(type="DDLS", name="<view>", include="elements")
The element list classifies fields. Decide for each:
- Measure: numeric, additive (amount / quantity / count) → goes in the cube with
@Aggregation.default: #SUM - Dimension: a characteristic you slice by (region, customer, date) → either reuse an existing dimension view or generate a new one
- Currency/Unit: paired with each amount/quantity measure
Step 2: Discover reusable dimensions
For each dimension field, check whether a reusable dimension view already exists before generating a new one:
SAPSearch(query="*<dimension_keyword>*", searchType="object", objectType="DDLS")
If a released #DIMENSION view exists (e.g. I_Country, I_CalendarDate), reuse it via association. Otherwise generate a new ZI_<X>_DIM (extended scope).
Step 3: Look up current analytics annotations
Ground the generation in current docs:
search("CDS analytical model cube Analytics.dataCategory CUBE dimension representativeKey")
search("ObjectModel.foreignKey.association text association Semantics.text")
Cite the doc IDs in your summary. Key facts (7.58):
- Cube:
@Analytics: { dataCategory: #CUBE, internalName: #LOCAL }+@ObjectModel: { supportedCapabilities: [ #ANALYTICAL_PROVIDER ], modelingPattern: #ANALYTICAL_CUBE } - A cube needs ≥1 measure; measures carry
@Aggregation.default: #SUM(or#MIN/#MAX/#AVG); a numeric field WITHOUT@Aggregation.defaultis treated as a dimension - Cube→dimension associations must be
[1..1];@ObjectModel.foreignKey.association: '_Dim'goes on the dimension key field in the cube - Dimension:
@Analytics.dataCategory: #DIMENSION+@ObjectModel: { representativeKey: '<key>', supportedCapabilities: [ #ANALYTICAL_DIMENSION ], modelingPattern: #ANALYTICAL_DIMENSION } - Text view uses
@ObjectModel.dataCategory: #TEXT(theObjectModel.namespace — NOT@Analytics.dataCategory) +@Semantics.text: true+@Semantics.language: true
Step 4: Compose the model
Cube template
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Sales Cube'
@Analytics: {
dataCategory: #CUBE,
internalName: #LOCAL
}
@ObjectModel: {
supportedCapabilities: [ #ANALYTICAL_PROVIDER ],
modelingPattern: #ANALYTICAL_CUBE
}
define view entity ZI_Sales_Cube
as select from zsales_data
association [1..1] to ZI_Region_Dim as _Region
on _Region.RegionId = $projection.RegionId
{
@ObjectModel.foreignKey.association: '_Region'
key region_id as RegionId,
key calyear as CalendarYear,
@Semantics.amount.currencyCode: 'CurrencyCode'
@Aggregation.default: #SUM
amount as SalesAmount,
currency as CurrencyCode,
@Aggregation.default: #SUM
@EndUserText.label: 'Number of Records'
abap.int8'1' as RecordCount,
_Region
}
Dimension template
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Region Dimension'
@Analytics.dataCategory: #DIMENSION
@ObjectModel: {
representativeKey: 'RegionId',
supportedCapabilities: [ #ANALYTICAL_DIMENSION ],
modelingPattern: #ANALYTICAL_DIMENSION
}
define view entity ZI_Region_Dim
as select from zregion
association [0..1] to ZI_Region_Txt as _Text
on _Text.RegionId = $projection.RegionId
{
@ObjectModel.text.association: '_Text'
key region_id as RegionId,
_Text
}
Text view template
@AccessControl.authorizationCheck: #NOT_REQUIRED
@EndUserText.label: 'Region - Text'
@ObjectModel.dataCategory: #TEXT
@ObjectModel.representativeKey: 'RegionId'
define view entity ZI_Region_Txt
as select from zregion_t
{
key region_id as RegionId,
@Semantics.language: true
key spras as Language,
@Semantics.text: true
regiontext as RegionName
}
(The text view stands alone — it declares no association, so it carries no @ObjectModel.foreignKey.association. The link is one-directional: the dimension associates to this text view via _Text + @ObjectModel.text.association, not the other way round.)
Composition rules (enforce before writing):
- Cube has ≥1 measure (
@Aggregation.default). - Each amount measure has
@Semantics.amount.currencyCode+ the currency field is projected; each quantity measure has@Semantics.quantity.unitOfMeasure+ the unit field is projected. - Every cube→dimension association is
[1..1]and the dimension key field carries@ObjectModel.foreignKey.association. - Every dimension has a
representativeKey. - Text views use
@ObjectModel.dataCategory: #TEXT+@Semantics.text/language.
Step 5: Show the plan as a tree, then batch-create
Show the user the model tree before writing:
Cube: ZI_Sales_Cube (from zsales_data)
Measures: SalesAmount (SUM, currency CurrencyCode), RecordCount (SUM)
Dimensions:
ZI_Region_Dim (new) → ZI_Region_Txt (new)
On confirmation, create all views in one batch with deferred activation so cross-references resolve together:
SAPWrite(action="batch_create", activateAtEnd=true, objects=[
{ type: "DDLS", name: "ZI_Region_Txt", source: "<text_ddl>", package: "$TMP" },
{ type: "DDLS", name: "ZI_Region_Dim", source: "<dimension_ddl>", package: "$TMP" },
{ type: "DDLS", name: "ZI_Sales_Cube", source: "<cube_ddl>", package: "$TMP" }
])
Order the array dependencies-first (text → dimension → cube) so that even if activateAtEnd falls back to per-object activation on an older release, the chain still resolves. With activateAtEnd: true, ARC-1 writes all three as inactive drafts and fires one terminal activation over the whole graph.
If batch_create with activateAtEnd is not honored (older release), fall back to: create each object with SAPWrite(action="create", ...) then a single SAPActivate(objects=[...]) over all created objects.
Step 6: Verify
SAPRead(type="DDLS", name="ZI_Sales_Cube", include="elements")
Confirm the cube is live and its dimension association + measures resolved.
Step 7: Offer the query layer
The cube is the foundation; the query is what end users consume. Offer:
"Want me to generate an analytical query (the consumable KPI view) on top of this cube? →
generate-cds-analytical-query"
Error Handling
| Error | Cause | Fix |
|---|---|---|
| Cube has no measure | All numeric fields treated as dimensions | Add @Aggregation.default: #SUM to at least one numeric field |
| Association cardinality error | Cube→dimension not [1..1] | Change cardinality to [1..1] |
foreignKey.association placement | Annotation on the association instead of the key field | Move it to the dimension key field in the cube |
| Text view rejected | Used @Analytics.dataCategory instead of @ObjectModel.dataCategory for #TEXT | Text views use the ObjectModel namespace |
| Cross-reference unresolved | Created objects activated individually before siblings existed | Use batch_create with activateAtEnd: true |
| Representative key missing | Dimension has no representativeKey | Add @ObjectModel.representativeKey |
Notes
- Basic vs extended scope: Basic = reuse existing dimensions (Step 2 finds released
#DIMENSIONviews). Extended = also generate newZI_*_DIM+ZI_*_TXTand accept a DDIC table as the fact source (Step 1b). - This skill builds the model; the consumable query is a separate step (
generate-cds-analytical-query). - For a transactional RAP service (not analytics), use
generate-rap-service. - Reuse SAP standard dimensions where they exist (
I_CalendarDate,I_Country,I_Currency) instead of regenerating them —SAPSearchin Step 2.
Generate CDS Analytical Query
Generate an analytical CDS query — a transient projection view with provider contract analytical_query — on top of an existing analytical cube (@Analytics.dataCategory: #CUBE).
This skill replicates SAP Joule's "CDS Analytical Query Generation" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices). The query view is what end users consume in analytical clients (SAP Analytics Cloud, Analysis for Office, embedded analytics) — it selects measures and dimensions from a cube and arranges them on rows/columns/free axes.
Prerequisites — read this first
- Requires SAP_BASIS 7.57+ (S/4HANA 2022+). The
provider contract analytical_queryform is unavailable on 7.56 and earlier. Note thatSAPManage(action="probe")rap.availableis necessary but not sufficient — RAP shipped in 7.54, so atruedoes not confirm the 7.57 floor. To gate reliably, check the release directly, e.g.SAPQuery(sql="SELECT release FROM cvers WHERE component = 'SAP_BASIS'")and require>= 757; otherwise be ready for the provider-contract syntax error to surface at activation (Step 5) and stop there. - You need an existing cube. This skill projects ON a cube. If no cube exists yet, run the
generate-analytics-star-schemaskill first to build the cube + dimensions, then come back here.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Object type | DDLS | Analytical queries are CDS data definitions |
| Package | $TMP | Fast prototyping; ask before a transportable package |
| Authorization | #NOT_ALLOWED | Mandatory on analytical queries — any other value fails activation |
| Axis layout | Dimensions → #ROWS, measures → #COLUMNS | Sensible default grid; user can rearrange |
| ATC | No | Only run if user asks about code quality |
Input
The user provides a cube name (e.g., ZI_Sales_Cube) or a business description ("revenue by region and month"). Only the cube is strictly required; if the user gives a description, find the cube via Step 1.
Optionally:
- Query name (default: derive from the cube, e.g.
ZC_SalesQuery; must be ≤ 28 characters — the analytical engine prepends2Cto the runtime name) - Package (default
$TMP) - Measures / dimensions to expose (default: all measures + key dimensions from the cube)
Step 1: Resolve and read the cube
1a. Find the cube (if the user gave a description, not a name)
SAPSearch(query="<keyword>*", searchType="object", objectType="DDLS")
Pick the candidate whose name/description matches an analytical cube. If multiple match, list them and ask.
1b. Read the cube source and confirm it IS a cube
SAPRead(type="DDLS", name="<cube>")
Verify the source contains @Analytics.dataCategory: #CUBE (or @Analytics: { dataCategory: #CUBE ... }). If it does NOT, stop: an analytical query can only project on a cube or a dimension. Suggest generate-analytics-star-schema to build a cube first.
1c. Get the structured element list
SAPRead(type="DDLS", name="<cube>", include="elements")
This returns every field with key markers and types. Use it to classify each element:
- Measures — numeric fields carrying
@Aggregation.default(e.g.#SUM) in the cube source - Dimensions — key fields and foreign-key-association fields
- Units/currencies — fields referenced by
@Semantics.amount.currencyCode/@Semantics.quantity.unitOfMeasure
Step 2: Look up current analytical-query syntax
Ground the generation in current docs — do NOT rely on memory for annotation names:
search("CDS analytical query provider contract analytical_query transient view")
search("AnalyticsDetails.query.axis ROWS COLUMNS FREE")
Cite the doc IDs you used in your final summary. Key facts the docs confirm (7.58):
- Header form:
define transient view entity <name> provider contract analytical_query as projection on <cube> @AccessControl.authorizationCheck: #NOT_ALLOWEDis mandatory (queries can't be read via ABAP SQL → no DCL allowed; the cube's access control applies)- The
transientkeyword is mandatory (no HANA SQL view is generated) - You cannot define new associations or use
KEYin a query view - A calculated measure (arithmetic / CASE-on-a-measure) needs
@Aggregation.default: #FORMULA
Step 3: Compose the analytical query
Pick the template that matches the request.
Template A — simple projection (1+ dimensions on rows, 1+ measures on columns)
@EndUserText.label: 'Sales Analytical Query'
@AccessControl.authorizationCheck: #NOT_ALLOWED
define transient view entity ZC_SalesQuery
provider contract analytical_query
as projection on ZI_Sales_Cube
{
@AnalyticsDetails.query.axis: #ROWS
RegionId,
@AnalyticsDetails.query.axis: #FREE
CalendarYear,
@AnalyticsDetails.query.axis: #COLUMNS
@Semantics.amount.currencyCode: 'CurrencyCode'
SalesAmount,
CurrencyCode
}
Template B — restricted + calculated measures
@EndUserText.label: 'Sales KPI Query'
@AccessControl.authorizationCheck: #NOT_ALLOWED
define transient view entity ZC_SalesKpiQuery
provider contract analytical_query
as projection on ZI_Sales_Cube
{
@AnalyticsDetails.query.axis: #ROWS
RegionId,
// restricted measure: selection-related CASE — WHEN must reference a DIMENSION
@Semantics.amount.currencyCode: 'CurrencyCode'
case when CalendarYear = '2025' then SalesAmount else null end as SalesAmount2025,
// calculated measure: formula CASE — needs @Aggregation.default: #FORMULA
@Aggregation.default: #FORMULA
case when SalesAmount is initial then abap.int8'0' else abap.int8'1' end as HasSales,
CurrencyCode
}
Template C — query with input parameters (filter prompt)
@EndUserText.label: 'Sales Query (parameterized)'
@AccessControl.authorizationCheck: #NOT_ALLOWED
define transient view entity ZC_SalesParamQuery
provider contract analytical_query
with parameters
p_year : abap.numc(4)
as projection on ZI_Sales_Cube
{
@AnalyticsDetails.query.axis: #ROWS
RegionId,
@Semantics.amount.currencyCode: 'CurrencyCode'
SalesAmount,
CurrencyCode
}
where CalendarYear = $parameters.p_year
Composition rules (enforce before writing):
- Every element you project directly from the cube must use the cube's exact element name (you read them in Step 1c). Calculated and restricted measures (Template B) are the exception — they introduce new aliases (
... as SalesAmount2025) that need not exist in the cube. - Every amount measure needs a
@Semantics.amount.currencyCode: '<field>'and that currency field must also be projected. - Every quantity measure needs
@Semantics.quantity.unitOfMeasure: '<field>'and that unit field must be projected. - Query name ≤ 28 chars.
Step 4: Show the plan, then write
Show the user the composed DDL and the axis layout (which fields are rows / columns / free) before writing. On confirmation:
SAPWrite(action="create", type="DDLS", name="<query>", source="<ddl>", package="$TMP")
For a transportable package, pass package="<pkg>" and transport="<TR>" (the user must supply the TR; create one with SAPTransport if needed).
Step 5: Activate
SAPActivate(name="<query>", type="DDLS")
If activation fails, surface the diagnostics verbatim and let the user re-prompt. Do NOT silently retry. Common failures:
@AccessControl.authorizationChecknot#NOT_ALLOWED→ fix the annotation- Element not found in cube → you used a name not in the cube (re-check Step 1c)
- Measure missing currency/unit reference → add the
@Semantics.*annotation + project the currency/unit field - Name > 28 chars → shorten the query name
Step 6: Verify
SAPRead(type="DDLS", name="<query>", include="elements")
Confirm the query is live and the projected elements appear. Report success with the runtime name (2C<query>).
Error Handling
| Error | Cause | Fix |
|---|---|---|
| Projection target is not a cube | Tried to project on a plain view | Build a cube first via generate-analytics-star-schema |
provider contract syntax error | SAP_BASIS < 7.57 | Stop — analytical_query unsupported on this release |
| Authorization check error on activate | Used a value other than #NOT_ALLOWED | Set @AccessControl.authorizationCheck: #NOT_ALLOWED |
| Element does not exist | Element name typo vs cube | Re-read the cube elements (Step 1c) |
| Name too long | Query name > 28 chars | Shorten it |
Notes
- This skill only creates the query layer. To build the underlying cube + dimensions + texts, use
generate-analytics-star-schemafirst — the two skills chain: star-schema produces the cube, this skill projects on it. - For a transactional (RAP) service rather than analytics, use
generate-rap-serviceinstead. - BTP ABAP and on-prem 7.58 both support this; on 7.57 verify the exact provider-contract form via
search()first.
Generate CDS Unit Test
Generate an ABAP Unit test class for a CDS entity using the CDS Test Double Framework.
This skill replicates SAP Joule's "CDS Unit Test Generation" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices).
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Test class name | ZCL_TEST_<entity_name> | Standard convention |
| Package | $TMP | Fast prototyping |
| Test scope | All testable semantics | User can narrow after seeing the list |
| Risk level | HARMLESS | CDS test doubles don't modify real data |
| Duration | SHORT | Unit tests should be fast |
Input
The user provides a CDS entity name (e.g., ZI_SALESORDER, ZC_TRAVEL).
Only the CDS entity name is required. If the user provides just an entity name, apply Smart Defaults and proceed immediately.
Optionally, the user may specify:
- Test class name (default:
ZCL_TEST_<entity_name>) - Package (default:
$TMP) - Transport request (only needed for non-
$TMPpackages)
Step 1: Gather CDS Entity Context
Read the CDS entity, its field structure, and all dependencies in just 3 tool calls.
1a. Read the CDS DDL source
SAPRead(type="DDLS", name="<entity_name>")
1b. Get structured field list
SAPRead(type="DDLS", name="<entity_name>", include="elements")
Returns a formatted listing of all fields with key markers, aliases, association references, and expression types (calculated, case, cast, coalesce). Use this to understand the entity's structure without parsing raw DDL.
1c. Get dependency context (tables, views, associations)
SAPContext(type="DDLS", name="<entity_name>")
Automatically extracts all data sources (FROM, JOIN), associations, compositions, and projection bases from the CDS DDL. For each dependency, fetches the full source with type fallback (DDLS → TABL → STRU). This gives you:
- Underlying table definitions with field types (needed for correctly-typed test data)
- Other CDS view sources (needed to understand transitive logic)
- Association targets
For deeper dependency graphs (e.g., a consumption view → interface view → table), use depth=2:
SAPContext(type="DDLS", name="<entity_name>", depth=2)
1d. (Optional) Read metadata extensions and behavior definition
SAPRead(type="DDLX", name="<entity_name>")
SAPRead(type="BDEF", name="<entity_name>")
These may fail if no DDLX/BDEF exists — that's fine, skip them. Only needed if the entity has UI annotations or RAP behavior.
Step 2: Analyze CDS Semantics and Propose Test Cases
Preferred (SAP_BASIS 8.16+ — ABAP Platform 2025 / S/4HANA 2025): ask SAP directly. SAP analyzes the entity for you and returns the authoritative list of testable semantics — the same CDS Test Double Framework engine behind SAP Joule's CDS unit-test generation:
SAPDiagnose(action="cds_testcases", name="<entity_name>")
Each suggestion carries a ready testMethod name, a semanticType (NONE = whole view, CALCULATION, CAST, JOIN, CASE, …), a description, and — for calculated/cast cases — the calculatedField. Use this as your proposed test-case list for the "Output to User" block below: it is SAP's own analysis, so prefer it over hand-parsing the DDL. Map each semanticType onto the category table and each testMethod onto a FOR TESTING method in Step 4. If the tool returns a "requires SAP_BASIS 8.16+" message (older releases / NW 7.5x don't expose the endpoint), or you want to cross-check coverage, use the manual analysis below.
Fallback / cross-check — analyze the DDL yourself. Analyze the CDS DDL source you read in Step 1 and identify all testable semantics. Group them by category:
Semantic Categories to Look For
| Category | What to Look For in DDL | Example Test Case |
|---|---|---|
| Calculations | Arithmetic expressions (field1 * field2, field1 - field2) | Insert known values, verify calculated result |
| CASE expressions | case when ... then ... else ... end | One test per branch |
| Type casts | cast(field as abap.dec(15,2)), cast(field as abap.char(10)) | Insert value, verify cast output |
| WHERE filters | where status = 'A' or where amount > 0 | Insert matching + non-matching rows, verify only matching appear |
| HAVING clauses | having sum(amount) > 1000 | Insert data that triggers and doesn't trigger the filter |
| JOINs | inner join, left outer join, association | Insert matching keys in both tables; test with non-matching keys for outer joins |
| Aggregations | sum(), count(), avg(), min(), max() with group by | Insert multiple rows, verify aggregated result |
| Null handling | coalesce(field, 'default'), null-safe expressions | Insert row with null field, verify default |
| Parameters | with parameters p_param : type | Call view with parameter, verify filtering |
| Currency/Unit conversion | currency_conversion(), unit_conversion() | Insert conversion data, verify result |
| String operations | concat(), substring(), length() | Insert string values, verify output |
| Associations | association [0..*] to ... | Insert data in both sides, verify navigation |
Output to User
Present the identified test cases as a numbered list:
Identified test cases for ZI_SALESORDER:
1. [CALCULATION] test_net_amount_calculation — Verify net_amount = gross_amount - discount
2. [CASE] test_status_text_open — Verify status 'O' maps to 'Open'
3. [CASE] test_status_text_closed — Verify status 'C' maps to 'Closed'
4. [JOIN] test_customer_join — Verify customer data is correctly joined
5. [WHERE] test_active_orders_filter — Verify only active orders are returned
6. [NULL] test_description_coalesce — Verify null description gets default value
Ask the user: "Which test cases should I generate? (all / specific numbers / skip any?)"
If the user says "all" or doesn't respond with preferences, generate all.
Step 3: Fetch CDS Test Double Framework Reference
Use mcp-sap-docs to get the latest CDS Test Double Framework patterns. This ensures generated code follows SAP best practices.
search("CDS test double framework cl_cds_test_environment")
Also fetch:
search("ABAP Unit cl_abap_unit_assert")
Use the returned documentation to inform the generated code patterns. Key things to verify:
- Correct
cl_cds_test_environment=>create()signature - Correct
get_double()/insert()pattern - Correct assertion method names
Step 4: Generate the Test Class
Generate a complete ABAP test class following this structure:
Template
"! @testing <CDS_ENTITY_NAME>
CLASS <test_class_name> DEFINITION
PUBLIC FINAL
FOR TESTING
DURATION SHORT
RISK LEVEL HARMLESS.
PUBLIC SECTION.
PROTECTED SECTION.
PRIVATE SECTION.
CLASS-DATA environment TYPE REF TO if_cds_test_environment.
CLASS-METHODS class_setup RAISING cx_static_check.
CLASS-METHODS class_teardown.
METHODS setup.
"! <description of test case 1>
METHODS <test_method_1> FOR TESTING RAISING cx_static_check.
"! <description of test case 2>
METHODS <test_method_2> FOR TESTING RAISING cx_static_check.
" ... one method per selected test case
ENDCLASS.
CLASS <test_class_name> IMPLEMENTATION.
METHOD class_setup.
environment = cl_cds_test_environment=>create( i_for_entity = '<CDS_ENTITY_NAME>' ).
ENDMETHOD.
METHOD class_teardown.
environment->destroy( ).
ENDMETHOD.
METHOD setup.
environment->clear_doubles( ).
ENDMETHOD.
METHOD <test_method_1>.
" Arrange — prepare test data for underlying tables
DATA lt_<table> TYPE STANDARD TABLE OF <underlying_table> WITH EMPTY KEY.
lt_<table> = VALUE #(
( <field1> = '<value1>' <field2> = '<value2>' ... )
).
environment->get_double( '<UNDERLYING_TABLE>' )->insert( lt_<table> ).
" Act — SELECT from the CDS entity under test
SELECT * FROM <cds_entity> INTO TABLE @DATA(lt_result).
" Assert — verify expected behavior
cl_abap_unit_assert=>assert_equals(
act = lines( lt_result )
exp = <expected_count>
msg = |Expected { <expected_count> } rows| ).
cl_abap_unit_assert=>assert_equals(
act = lt_result[ 1 ]-<field>
exp = '<expected_value>'
msg = '<assertion message>' ).
ENDMETHOD.
" ... more test methods
ENDCLASS.
Test Data Generation Rules
Follow these principles when generating test data:
- Minimal rows: Use the fewest rows needed to exercise the semantic. Typically 1-3 rows per test.
- Obvious values: Choose values where the expected result is trivially verifiable:
- For
gross - discount = net: use 100.00 - 10.00 = 90.00, not 37.83 - 4.27 - For CASE branches: use exactly the values from the CASE expression
- For WHERE filters: one row that passes, one that doesn't
- For
- Type-correct: Match ABAP types exactly:
- Use
'001'for NUMC fields (string with leading zeros) - Use
'100.00'for DEC/CURR fields - Use
'20260101'for DATS fields - Use
'EUR'for CUKY fields
- Use
- Key fields populated: Always fill key fields even if not directly tested
- Deterministic: Never use random or date-dependent values
- Isolated: Each test method should be self-contained (clear_doubles in setup ensures this)
Naming Conventions
- Test class:
ZCL_TEST_<ENTITY>orZCL_<ENTITY>_TEST - Test methods:
test_<semantic>_<detail>(e.g.,test_status_case_open,test_net_amount_calc) - Use snake_case for method names (ABAP convention for test methods)
- Keep method names under 30 characters
Step 5: Preview and Confirm
Show the user the complete generated test class source code and ask:
"Here's the generated test class. Should I create it on the SAP system? (yes / edit first / cancel)"
If the user wants edits, incorporate them before proceeding.
Step 6: Create, Activate, and Test
6-pre. Lint-check generated code (optional)
Before writing, validate the generated code against lint rules:
SAPLint(action="lint", source="<generated_source>", name="<test_class_name>")
Fix any lint findings before proceeding. Pre-write lint validation also runs automatically when enabled (default: on).
6a. Create the test class
SAPWrite(action="create", type="CLAS", name="<test_class_name>", source="<generated_source>", package="<package>", transport="<transport>")
6b. Update the source (if create only scaffolds)
SAPWrite(action="update", type="CLAS", name="<test_class_name>", source="<generated_source>", transport="<transport>")
6c. Activate the test class
SAPActivate(type="CLAS", name="<test_class_name>")
Activation returns structured responses with detailed error/warning messages including line numbers. Use these to pinpoint exact issues.
6d. Run the unit tests
SAPDiagnose(action="unittest", type="CLAS", name="<test_class_name>")
6e. Report results
Show the user:
- Number of tests passed / failed / skipped
- For any failures: the assertion message and which test method failed
- Suggested fixes for any failures
If tests fail:
- Analyze the failure message
- Determine if it's a test data issue, assertion issue, or CDS logic issue
- Fix the test method using
SAPWrite(action="edit_method", ...) - Re-activate and re-run
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
CX_CDS_TEST_ENVIRONMENT during class_setup | Entity name wrong or not active | Verify entity name, check activation status |
| Type mismatch in VALUE constructor | Wrong field type in test data | Check DD03L or table structure for correct types |
GET_DOUBLE fails for a data source | Data source name doesn't match | Check CDS DDL for exact data source names (case-sensitive!) |
| Assertion fails with unexpected values | Test data or expected result wrong | Re-check CDS logic, adjust test data or assertion |
| Activation error: "test relation not found" | @testing annotation points to wrong entity | Fix entity name in "! @testing comment |
| Class exists already | Test class already created | Use SAPWrite(action="update", ...) instead |
Notes
BTP vs On-Premise Differences
- BTP: Only Z*/Y* classes can be created. Standard SAP tables cannot be queried via DD03L. Use released CDS entities for type reference.
- On-Premise: Full access to DD03L, DD02L for field catalogs. Can query TADIR for object existence checks.
What This Skill Does NOT Do
- Performance testing: CDS Test Doubles are for logic testing, not performance
- Authorization testing: DCL/CDS access control testing requires separate patterns
- Integration testing: This generates isolated unit tests, not end-to-end flows
- RAP behavior testing: For validations/actions/determinations, use the RAP BO Test Double Framework instead
When to Use This Skill
- When a CDS entity has non-trivial logic (calculations, CASE, filters, joins)
- When the user wants basic test coverage as a starting point
- When refactoring CDS logic and wanting regression tests
- NOT for trivial projections that just rename fields — if analysis in Step 2 finds no testable semantics (just field renames with no calculations, CASE, WHERE, JOINs, or aggregations), warn the user: "This CDS view is a simple projection with no testable logic. Unit tests would only verify that fields are correctly aliased, which provides minimal value. Consider testing the underlying view instead."
Generate RAP Business Logic
Generate RAP determination, validation, and custom action implementations for an existing behavior definition. Reads the RAP stack, identifies empty method stubs (or missing handler signatures) in the behavior pool, and generates ABAP Cloud implementation code.
This skill replicates SAP Joule's "RAP Logic Prediction" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices).
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Entity access | IN LOCAL MODE always | Inside behavior pool, no auth check needed |
| Message style | Hardcoded text via new_message_with_text() | Simplest for prototyping; use MSAG for production (see Notes) |
| Scope | All empty methods | User can narrow after seeing the list |
| Error handling | FAILED + REPORTED structures | Standard RAP error propagation |
Input
The user provides a behavior definition name (e.g., ZI_TRAVEL).
Only the behavior definition name is required. If the user provides just a BDEF name, apply Smart Defaults and proceed to read the stack and present available methods.
Optionally, the user may specify:
- Specific determination/validation (default: list all and let user choose)
- Behavior description — natural language description of desired logic (e.g., "calculate total price from line items", "validate status transitions")
Step 1: Read the RAP Stack
Read the behavior definition, CDS view, and behavior pool to understand the complete RAP context.
1a. Read the behavior definition
SAPRead(type="BDEF", name="<bdef_name>")
⚠️ FAIL-FAST GATE: If the BDEF read fails with 404, the object may not exist — verify the name via SAPSearch. If it fails with 415, check SAPManage(action="probe") for system info and inform the user about the issue.
Parse the BDEF source to identify:
- Scenario: managed / unmanaged / abstract
- Determinations:
determination <Name> on (modify|save) { ... } - Validations:
validation <Name> on save { ... } - Actions:
action <Name> ... - Draft status:
with draftpresent or not - Entity aliases:
alias <Alias> - Persistent table:
persistent table <table_name> - Behavior pool class:
implementation in class <class_name> unique
1b. Read the interface CDS view
SAPRead(type="DDLS", name="<interface_view>")
Understand the data model: field names, types, aliases, associations. This is needed to generate correct READ ENTITIES and MODIFY ENTITIES statements.
If access control exists, also read it to understand CDS-level authorization constraints:
SAPRead(type="DCLS", name="<interface_view>_DCL")
1c. Get dependency context
SAPContext(type="DDLS", name="<interface_view>", action="deps")
Understand underlying tables, associations, and related entities. Useful for cross-entity validations or determinations that read associated data.
1d. Read the behavior pool class
Find the behavior pool class name from the BDEF source (implementation in class <name>), then:
SAPRead(type="CLAS", name="<bp_class>", format="structured")
Use the structured read as the default because it returns metadata, includes, and existing test classes in one response. If you need a concise method catalog afterward, add:
SAPRead(type="CLAS", name="<bp_class>", method="*")
Identify which methods are empty stubs (body is just comments, RETURN, or blank) and which BDEF-declared handlers are missing entirely from the class signature.
1e. Optional history / documentation context
If this is an existing RAP BO that has already been modified by others, inspect recent changes and any attached documentation before overwriting logic:
SAPRead(type="VERSIONS", name="<bp_class>", objectType="CLAS")
SAPRead(type="SKTD", name="<bp_class>")
Step 2: Identify Target Methods
Parse the BDEF for determination and validation declarations. Present a summary table:
Methods in behavior pool ZBP_I_TRAVEL:
| # | Type | Name | Trigger | Fields | Status |
|---|---------------|-----------------------|--------------------|-----------------|-------------|
| 1 | Determination | calculateTotalPrice | on modify | Price, Quantity | empty |
| 2 | Determination | setDefaultStatus | on modify | %create | empty |
| 3 | Validation | validateStatus | on save | Status | implemented |
| 4 | Validation | validateDates | on save | BeginDate | empty |
| 5 | Validation | validateCustomer | on save | CustomerID | empty |
Ask the user: "Which methods should I implement? (all empty / specific numbers / skip any?)"
If the user provided a natural language description, map it to the appropriate method(s).
2b. Missing Handler Signature Recovery
If the BDEF declares action/determination/validation handlers that do not exist in the class definition:
- Run
SAPWrite(action="scaffold_rap_handlers", type="CLAS", name="<bp_class>", bdefName="<bdef_name>")to list missing signatures. - If signatures are missing, rerun with
autoApply=trueto inject declarations plus empty method stubs into class sections when possible. - If unresolved, try MCP quick-fix flow:
SAPDiagnose(action="quickfix", ...)SAPDiagnose(action="apply_quickfix", ...)
- If still unresolved, use ADT quick-fix to generate the missing
METHODS ... FOR ...signature. - Re-read method list with
SAPRead(type="CLAS", name="<bp_class>", method="*")before writing bodies.
Step 3: Research RAP Patterns
Use mcp-sap-docs to fetch current RAP implementation patterns. Start with reference-style queries (includeSamples=false) and then fetch examples (includeSamples=true) only when you need executable patterns:
search(query="RAP validation implementation ABAP example", includeSamples=true, abapFlavor="<cloud|standard>")
search(query="RAP determination on save trigger", includeSamples=false, abapFlavor="<cloud|standard>")
For specific logic patterns:
search(query="RAP calculate total price determination", includeSamples=true, abapFlavor="<cloud|standard>")
search(query="RAP status validation transition", includeSamples=true, abapFlavor="<cloud|standard>")
For backend-driven UI behavior that frequently accompanies logic changes:
search(query="RAP feature control side effects authorization control", includeSamples=false, abapFlavor="<cloud|standard>")
Use documentation to inform correct ABAP Cloud patterns:
READ ENTITIES OF <entity> IN LOCAL MODEfor reading entity dataMODIFY ENTITIES OF <entity> IN LOCAL MODEfor updating entity data- Proper
FAILED/REPORTEDstructure handling - Correct method signatures for determinations vs validations
- Feature control checks are not evaluated for EML with
IN LOCAL MODE
Step 4: Generate Method Implementation
For each selected method, generate ABAP Cloud implementation code.
Determination Template
METHOD <determination_name>.
" Read relevant fields of all affected entities
READ ENTITIES OF <interface_view> IN LOCAL MODE
ENTITY <alias>
FIELDS ( <trigger_fields> )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_entities).
" Calculate derived values
LOOP AT lt_entities ASSIGNING FIELD-SYMBOL(<entity>).
" --- Business logic here ---
" Example: <entity>-TotalPrice = <entity>-Price * <entity>-Quantity.
ENDLOOP.
" Write back modified fields
MODIFY ENTITIES OF <interface_view> IN LOCAL MODE
ENTITY <alias>
UPDATE FIELDS ( <modified_fields> )
WITH VALUE #( FOR entity IN lt_entities
( %tky = entity-%tky
<field> = entity-<field> ) )
REPORTED DATA(lt_update_reported).
reported = CORRESPONDING #( DEEP lt_update_reported ).
ENDMETHOD.
Validation Template
METHOD <validation_name>.
" Read relevant fields of all affected entities
READ ENTITIES OF <interface_view> IN LOCAL MODE
ENTITY <alias>
FIELDS ( <validated_fields> )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_entities).
LOOP AT lt_entities ASSIGNING FIELD-SYMBOL(<entity>).
" --- Validation logic here ---
" Example: check field is not initial
IF <entity>-<Field> IS INITIAL.
APPEND VALUE #( %tky = <entity>-%tky ) TO failed-<alias>.
APPEND VALUE #(
%tky = <entity>-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = '<Error message>' )
%element-<Field> = if_abap_behv=>mk-on
) TO reported-<alias>.
ENDIF.
ENDLOOP.
ENDMETHOD.
Action Template
METHOD <action_name>.
READ ENTITIES OF <interface_view> IN LOCAL MODE
ENTITY <alias>
FIELDS ( <action_input_fields> )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_entities).
LOOP AT lt_entities ASSIGNING FIELD-SYMBOL(<entity>).
" --- Action logic here ---
ENDLOOP.
MODIFY ENTITIES OF <interface_view> IN LOCAL MODE
ENTITY <alias>
UPDATE FIELDS ( <action_output_fields> )
WITH VALUE #( FOR entity IN lt_entities
( %tky = entity-%tky
<field> = entity-<field> ) )
REPORTED DATA(lt_reported)
FAILED DATA(lt_failed).
reported = CORRESPONDING #( DEEP lt_reported ).
failed = CORRESPONDING #( DEEP lt_failed ).
ENDMETHOD.
Output to User
Show the generated code for each method and ask:
"Here's the generated implementation. Should I write it to the SAP system? (yes / edit first / cancel)"
If the user wants edits, incorporate them before proceeding.
Step 5: Write and Validate
Before writing, optionally lint-check the generated code to catch issues before acquiring SAP locks:
SAPLint(action="lint", source="<generated_method_code>", name="<bp_class>")
If you want the generated method body to follow SAP's formatter settings before it is written back:
SAPLint(action="format", source="<generated_method_code>", name="<bp_class>")
Before calling edit_method, confirm the target method exists in SAPRead(..., method="*"). If it does not exist yet, run scaffold_rap_handlers first, then quick-fix flow (quickfix + apply_quickfix) or ADT quick-fix fallback.
Write each method implementation using method-level surgery:
SAPWrite(action="edit_method", type="CLAS", name="<bp_class>", method="<method_name>", source="<generated_code>", transport="<transport>")
Note: The transport parameter is recommended but not always required for edit_method. ARC-1 auto-propagates the lock-provided corrNr when no explicit transport is supplied. Pre-write lint validation runs automatically when enabled (default: on). Prefer edit_method over full-class rewrites for behavior pools.
After writing all methods, run a syntax check:
SAPRead(type="SYNTAX", objectType="CLAS", name="<bp_class>")
If syntax errors occur, try SAP quickfix proposals first before manual edits:
SAPDiagnose(action="quickfix", type="CLAS", name="<bp_class>", source="<current_source>", line=<error_line>, column=<error_col>)
SAP quickfixes can automatically resolve common issues like missing declarations or straightforward syntax corrections.
If syntax errors occur:
- Read the error message carefully
- Common issues: wrong entity name in
READ ENTITIES, incorrect field alias, missingIN LOCAL MODE - Fix the method and re-write
- Re-check syntax
Step 6: Activate and Verify
Activate the behavior pool and behavior definition together:
SAPActivate(objects=[{type:"BDEF", name:"<bdef>"}, {type:"CLAS", name:"<bp_class>"}])
Note: Activation returns structured responses with detailed error/warning messages including line numbers and URIs. Use this to pinpoint exact issues rather than re-reading full source.
Optionally, if a test class exists, run the unit tests:
SAPDiagnose(action="unittest", type="CLAS", name="<bp_class>")
If ATC is available and the change is non-trivial, run it too:
SAPDiagnose(action="atc", type="CLAS", name="<bp_class>")
Present a summary:
RAP Logic Generation Complete!
Implemented methods:
[x] Determination: calculateTotalPrice — calculates total from price * quantity
[x] Determination: setDefaultStatus — sets status to 'N' (New) on create
[x] Validation: validateDates — ensures begin_date < end_date
[x] Validation: validateCustomer — checks customer_id is not empty
[ ] Validation: validateStatus — already implemented, skipped
Next steps:
- Test the logic via the Fiori Elements preview
- Add unit tests (use generate-abap-unit-test skill)
- Add more validations/determinations to the BDEF as needed
Common RAP Logic Patterns
Field Calculation Determination
Calculate a derived field from other fields (e.g., total price = price * quantity):
METHOD calculateTotalPrice.
READ ENTITIES OF zi_order IN LOCAL MODE
ENTITY Order
FIELDS ( Price Quantity )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_orders).
LOOP AT lt_orders ASSIGNING FIELD-SYMBOL(<order>).
<order>-TotalPrice = <order>-Price * <order>-Quantity.
ENDLOOP.
MODIFY ENTITIES OF zi_order IN LOCAL MODE
ENTITY Order
UPDATE FIELDS ( TotalPrice )
WITH VALUE #( FOR order IN lt_orders
( %tky = order-%tky
TotalPrice = order-TotalPrice ) )
REPORTED DATA(lt_reported).
reported = CORRESPONDING #( DEEP lt_reported ).
ENDMETHOD.
Default Value Determination
Set default values when an entity is created:
METHOD setDefaultStatus.
READ ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
FIELDS ( Status )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_travels).
MODIFY ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
UPDATE FIELDS ( Status )
WITH VALUE #( FOR travel IN lt_travels
WHERE ( Status IS INITIAL )
( %tky = travel-%tky
Status = 'N' ) )
REPORTED DATA(lt_reported).
reported = CORRESPONDING #( DEEP lt_reported ).
ENDMETHOD.
Mandatory Field Validation
Check that a required field is not empty:
METHOD validateCustomer.
READ ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
FIELDS ( CustomerID )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_travels).
LOOP AT lt_travels ASSIGNING FIELD-SYMBOL(<travel>).
IF <travel>-CustomerID IS INITIAL.
APPEND VALUE #( %tky = <travel>-%tky ) TO failed-travel.
APPEND VALUE #(
%tky = <travel>-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = 'Customer must be specified' )
%element-CustomerID = if_abap_behv=>mk-on
) TO reported-travel.
ENDIF.
ENDLOOP.
ENDMETHOD.
Cross-Field Validation
Validate that related fields are consistent (e.g., begin date before end date):
METHOD validateDates.
READ ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
FIELDS ( BeginDate EndDate )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_travels).
LOOP AT lt_travels ASSIGNING FIELD-SYMBOL(<travel>).
IF <travel>-BeginDate IS NOT INITIAL
AND <travel>-EndDate IS NOT INITIAL
AND <travel>-BeginDate > <travel>-EndDate.
APPEND VALUE #( %tky = <travel>-%tky ) TO failed-travel.
APPEND VALUE #(
%tky = <travel>-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = 'Begin date must be before end date' )
%element-BeginDate = if_abap_behv=>mk-on
%element-EndDate = if_abap_behv=>mk-on
) TO reported-travel.
ENDIF.
ENDLOOP.
ENDMETHOD.
Status Transition Validation
Validate that status changes follow allowed transitions:
METHOD validateStatus.
READ ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
FIELDS ( Status )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_travels).
LOOP AT lt_travels ASSIGNING FIELD-SYMBOL(<travel>).
CASE <travel>-Status.
WHEN 'N' OR 'O' OR 'A' OR 'X'.
" Valid statuses: New, Open, Accepted, Cancelled
WHEN OTHERS.
APPEND VALUE #( %tky = <travel>-%tky ) TO failed-travel.
APPEND VALUE #(
%tky = <travel>-%tky
%msg = new_message_with_text(
severity = if_abap_behv_message=>severity-error
text = |Invalid status: { <travel>-Status }| )
%element-Status = if_abap_behv=>mk-on
) TO reported-travel.
ENDCASE.
ENDLOOP.
ENDMETHOD.
Number Range Determination
Assign sequential numbers for non-UUID key scenarios:
METHOD setTravelID.
READ ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
FIELDS ( TravelID )
WITH CORRESPONDING #( keys )
RESULT DATA(lt_travels).
" Get next number from number range or max+1
SELECT MAX( travel_id ) FROM ztravel_d INTO @DATA(lv_max_id).
DATA(lv_next_id) = lv_max_id + 1.
LOOP AT lt_travels ASSIGNING FIELD-SYMBOL(<travel>)
WHERE TravelID IS INITIAL.
<travel>-TravelID = lv_next_id.
lv_next_id += 1.
ENDLOOP.
MODIFY ENTITIES OF zi_travel IN LOCAL MODE
ENTITY Travel
UPDATE FIELDS ( TravelID )
WITH VALUE #( FOR travel IN lt_travels
WHERE ( TravelID IS NOT INITIAL )
( %tky = travel-%tky
TravelID = travel-TravelID ) )
REPORTED DATA(lt_reported).
reported = CORRESPONDING #( DEEP lt_reported ).
ENDMETHOD.
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
| 415 Unsupported Media Type on DDLS/BDEF | RAP/CDS endpoint not responding as expected | Check SAPManage(action="probe") for system info. Verify ICF service activation. Try creating the object in ADT to confirm system capability. |
| Method not found in behavior pool | Class name in BDEF doesn't match actual class | Check implementation in class in BDEF source, verify class exists |
Missing METHODS ... FOR ... handler signature | BDEF declaration exists but class signature not generated yet | Run SAPWrite(action="scaffold_rap_handlers", ...) first (optionally autoApply=true), then SAPDiagnose(action="quickfix") + apply_quickfix or ADT quick-fix, then retry edit_method |
Syntax error: <entity> unknown in READ ENTITIES | Wrong entity name or alias | Use the exact alias from the BDEF define behavior for ... alias <Alias> |
Syntax error: field <Field> unknown | Field alias doesn't match CDS view | Check CDS view field aliases — BDEF uses CDS aliases, not table field names |
| Activation fails | BDEF and class are incompatible | Activate BDEF and class together: SAPActivate(objects=[...]) |
FAILED / REPORTED structure mismatch | Wrong alias used in failed-<alias> or reported-<alias> | Use the lowercase entity alias from BDEF (e.g., failed-travel, not failed-Travel) |
IN LOCAL MODE missing | Missing clause causes authorization check | Always use IN LOCAL MODE for internal reads/writes within the behavior pool |
%tky not available | Method signature doesn't provide transactional key | Check method signature — determinations use keys, validations use keys |
Runtime error on MODIFY ENTITIES | Trying to modify read-only fields | Don't modify fields marked field ( readonly ) in BDEF |
Generic save error [?/011] on full class write | Behavior-pool full-class update path is unstable on some systems | Use scaffold_rap_handlers + quickfix path for signatures, then patch method bodies via edit_method only |
Notes
BTP vs On-Prem Differences
- BTP: ABAP Cloud syntax strictly enforced. Only
READ ENTITIES/MODIFY ENTITIES— noSELECTfrom database tables directly. All APIs must be released.strict ( 2 )in BDEF. - On-Prem: More flexible — classic ABAP can be used in the behavior pool (e.g.,
SELECTdirectly), butREAD ENTITIES/MODIFY ENTITIESis strongly recommended for consistency and future compatibility. - Authorization layering:
DCLSenforces CDS row-level access, while BDEF authorization (authorization master) governs behavior operations. Consider both when debugging authorization-related logic.
What This Skill Does NOT Do
- Automatic BDEF declaration authoring: This skill assumes declarations exist in BDEF; it does not redesign BDEF contracts for you.
- Side effects: No end-to-end
side effectsimplementation (UI refresh triggers). Add manually if needed. - Feature control: No end-to-end dynamic feature control (
instance_features/global_features). Add manually, especially when the UI should disable actions or updates. - Authorization: No
authorization masterimplementation. Add authorization checks manually. - Cross-BO logic: No inter-business-object operations. Each determination/validation operates within its own BO.
- Message class creation: Uses hardcoded text for messages. For production services, create a message class afterward:
SAPWrite(action="create", type="MSAG", name="Z<MSG_CLASS>", ...)and replacenew_message_with_text()withnew_message()referencing the message class.
When to Use This Skill
- After creating a RAP service (use generate-rap-service first)
- When the BDEF has determination/validation declarations but empty method stubs
- When adding new business logic to an existing RAP service
- When the user describes desired behavior in natural language (e.g., "validate that the end date is after the begin date")
- NOT for creating the RAP service from scratch (use generate-rap-service)
- NOT for CDS unit tests (use generate-cds-unit-test or generate-abap-unit-test)
Generate RAP OData Service — Research-First
Generate a production-quality RAP OData service through deep system research, best-practice analysis, and iterative planning before writing a single line of code.
This skill produces an implementation plan informed by the target SAP system's actual capabilities, existing code patterns, SAP documentation, and user requirements — then executes it only after explicit user approval.
Smart Defaults (apply silently, do NOT ask before research)
| Setting | Default | Rationale |
|---|---|---|
| Package | User's Z* package with transport | Production-ready; only use $TMP if user explicitly asks |
| Key strategy | UUID (sysuuid_x16), managed numbering | Simplest, no collision risk |
| Behavior scenario | Managed | Framework handles CRUD, most common |
| OData version | V4 | Current SAP standard |
| Draft | Prefer for transactional Fiori Elements UI services; verify against system release and BO constraints | Best default for editable FE apps, but not every RAP service needs draft |
| Strict mode | strict ( 2 ) unless system patterns or SAP constraints justify otherwise | Current RAP best practice, but not universal |
| Naming | SAP standard (see reference section) | Overridden by existing system patterns if found |
| Admin fields | System-appropriate (syuname/timestampl or abp_*) | Detected from system type |
| Service exposure | OData V4 UI provider contract by default | Best fit for Fiori Elements unless the use case is an API-first service |
These defaults are starting points — research in Phase 1 may override them based on existing system patterns.
Input
The user provides a natural language description of the business requirement. This can range from vague ("I need something to track maintenance orders") to detailed ("REST API for plant maintenance with equipment hierarchy, work orders, and time recording").
Only the business requirement is required. Gather initial context — do NOT over-interview at this stage. Research will surface the right questions later.
Optionally, the user may specify:
- Package (required — ask if not provided; only default to
$TMPif user explicitly says so) - Transport request (only needed for non-
$TMPpackages — resolved in Phase 1-pre) - Any known constraints (e.g., "must use existing table ZMAINT_ORDER", "needs to integrate with PM module")
If the user provides just a description, proceed directly to research. Questions come AFTER research, when you know enough to ask the right ones.
Phase 1-pre: Resolve Package and Transport
Ask the user for their target package if not provided. Then resolve the transport request (skip only if package is $TMP):
SAPTransport(action="check", objectType="DDLS", objectName="<placeholder_name>", package="<package>")
This checks if a transport is required and returns existing transports for the package. If a transport is required:
- User provided a transport: Use it for all creates
- Existing transport found: Present the list and ask the user to pick one
- No transport available: Create one:
SAPTransport(action="create", description="RAP Service: <Entity>", package="<package>")
If transport is required but unavailable, STOP — all write operations will fail without a valid transport for non-$TMP packages.
Phase 1: Deep System Research
Research the target system thoroughly before designing anything. Every finding informs the plan.
1a. System Capabilities & Version
Detect what the system supports — this determines available RAP features, syntax, naming, and safe defaults.
If ./system-info.md already exists from bootstrap-system-context, use it as input. Otherwise, reproduce the critical reads inline:
SAPRead(type="SYSTEM")
SAPRead(type="COMPONENTS")
SAPManage(action="probe")
SAPLint(action="list_rules")
Note: rap.available in the probe response is informational — it indicates whether the DDL source endpoint was detected, but RAP may still be available. Proceed with creation and handle errors if they occur.
Extract and note:
- System type: BTP ABAP Environment vs. On-Premise (and release level: 7.52, 7.54, 7.57, S/4HANA 2020+, etc.)
- ABAP language version: Cloud (strict, released APIs only) vs. Standard (full ABAP)
- RAP support level: Managed, unmanaged, abstract BOs? Draft support? Late numbering? Determination on modify vs. save?
- CDS capabilities: View entities vs. classic views? Table entities? Metadata extensions? Access control?
- Available features: ATC, syntax check, unit test runner, transport management, FLP customization, abapGit/gCTS, version history
- FLP support: If
flpfeature is available, the service can be registered in the Fiori Launchpad after creation - Lint profile: cloud vs on-prem preset, active ABAP version, formatter style
1b. Existing RAP Projects — Pattern Mining
Search for existing RAP artifacts to understand the system's established patterns. This is critical for consistency.
SAPSearch(query="BDEF Z*", maxResults=20)
SAPSearch(query="SRVD Z*", maxResults=20)
SAPSearch(query="SRVB Z*", maxResults=20)
SAPSearch(query="DCLS Z*", maxResults=20)
SAPSearch(query="DDLX Z*", maxResults=20)
If NO Z BDEFs are found*, you MUST still ground yourself in at least one real system example before writing any code. Use this deterministic fallback:
SAPRead(type="TABL", name="SCARR")
This shows you the system's actual TABL annotation pattern (enhancement category, delivery class, data maintenance, client handling). Then read one activated CDS view:
SAPSearch(query="DDLS I_*", maxResults=5)
SAPRead(type="DDLS", name="<first_result>")
This shows CDS conventions (client field handling, alias style, annotation patterns). Do NOT proceed to Phase 4 until at least one real system table and one CDS view are in context. Writing from memory of documentation alone is the #1 cause of wasted retries.
If results are found, read 2-3 representative RAP stacks to extract the team's patterns:
SAPRead(type="BDEF", name="<found_bdef>")
SAPRead(type="DDLS", name="<found_interface_view>")
SAPRead(type="DDLS", name="<found_projection_view>")
SAPRead(type="DDLX", name="<found_metadata_ext>")
SAPRead(type="SRVB", name="<found_service_binding>")
SAPContext(type="DDLS", name="<found_interface_view>", action="impact")
SAPRead(type="VERSIONS", name="<found_interface_view>", objectType="DDLS")
SAPRead(type="SKTD", name="<found_interface_view>")
From these, extract:
- Naming conventions: What prefix pattern?
ZI_/ZC_/ZR_? Entity suffix patterns? Table naming? - Architecture style: Managed vs. unmanaged? Draft enabled?
strict ( 2 )orstrict? - Annotation patterns: Which
@UIannotation style? Header info pattern? Facet structure? - Field naming: CamelCase aliases? Underscore style? Abbreviation patterns?
- Admin field patterns: Which timestamp/user field types are used? (
syunamevsabp_creation_user,timestamplvsabp_creation_tstmpl) - Key strategy: UUID (
sysuuid_x16)? Semantic keys? Number ranges? - Behavior patterns: Which determinations/validations are standard? Authorization pattern?
- Draft handling:
with draftpresent? Draft table naming? Draft actions included? - OData exposure: UI vs Web API bindings? V2 or V4? Service definition/provider contract style?
- Recent evolution: Did the revision history show stable patterns or an ongoing migration?
- Documentation presence: Are SKTD notes attached to important RAP artifacts?
1b2. Optional Git / Delivery Context
If SAPManage(action="probe") shows abapGit or gCTS support and the target package may already belong to a repo-backed workflow, inspect that context before creating new artifacts:
SAPGit(action="list_repos")
SAPGit(action="objects", repoId="<repo_id>")
SAPGit(action="history", repoId="<repo_id>", limit=20)
Use this to learn:
- Whether the target package is already repo-managed
- Which naming/branching conventions are active
- Whether the package is under active delivery and should align with an existing repo layout
1c. Existing Database Tables & Domain Objects
If the user mentioned existing tables or business objects, read them:
SAPSearch(query="<mentioned_table_or_object>")
SAPRead(type="TABL", name="<found_table>")
SAPContext(type="TABL", name="<found_table>")
Also search for related SAP standard objects in the domain:
SAPSearch(query="<domain_keyword>", maxResults=10)
Check if there are existing CDS views or tables the new service should build on rather than duplicating data.
If building on existing objects on a BTP system, check their API release state for Clean Core compliance:
SAPRead(type="API_STATE", name="<found_table_or_view>", objectType="TABL")
If an object is deprecated (C2) or not released, avoid building on it — search for its released successor instead.
To understand what already depends on a found CDS object, use CDS-specific impact instead of generic where-used:
SAPContext(type="DDLS", name="<found_view>", action="impact")
Use generic reverse dependencies only for non-DDLS objects:
SAPContext(type="CLAS", name="<found_class>", action="usages")
1d. Code Guidelines & Quality Standards
Check if the system has ATC configuration or custom check variants that indicate code quality standards:
SAPDiagnose(action="atc", type="CLAS", name="<any_existing_class>", variant="DEFAULT")
If existing RAP classes were found in 1b, read one and run lint + formatter discovery to understand the baseline:
SAPRead(type="CLAS", name="<found_bp_class>")
SAPLint(action="lint", source="<class_source>", name="<found_bp_class>")
SAPLint(action="get_formatter_settings")
This reveals what lint rules, strictness levels, and keyword/indentation preferences are enforced.
1e. Best Practices Research — SAP Documentation
Use the SAP documentation MCP server deliberately, not as a generic keyword dump.
- Start with official/reference-oriented queries:
includeSamples=falseabapFlavor="cloud"on BTP / ABAP Cloud systemsabapFlavor="standard"on classic on-prem systems when relevant
- Then run example-oriented queries:
includeSamples=true
- Use
fetch(...)on the top hits you actually rely on. - Use
sap_community_search(...)only for edge cases, undocumented errors, or workaround hunting after official docs are insufficient.
The search terms below are starting suggestions — adapt them based on the user's specific business requirement and the architecture decisions that need to be made. Craft search queries that target the gaps in your knowledge for this particular service.
Architecture and layering:
search(query="RAP projection BO vs RAP BO interface", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="RAP service definition provider contracts odata_v4_ui odata_v4_webapi", includeSamples=false, abapFlavor="<cloud|standard>")
Domain-specific — tailor to the user's business domain:
search(query="<business_domain> RAP example SAP", includeSamples=true, abapFlavor="<cloud|standard>")
For example, if the user wants a travel app: search("RAP travel booking managed scenario example")
Architecture decisions — search only for topics relevant to this service:
search(query="RAP managed vs unmanaged scenario when to use", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="RAP draft handling total etag draft-enabled associations", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="RAP compositions parent child entity", includeSamples=true, abapFlavor="<cloud|standard>")
UI / service behavior — search if the service is UI-facing:
search(query="RAP value help metadata extension additional binding OData V4", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="RAP feature control side effects authorization control", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="metadata-driven UI metadata extension RAP Fiori Elements", includeSamples=false, abapFlavor="<cloud|standard>")
Clean core / released APIs — for BTP or released-object reuse:
search(query="ABAP API release RAP business object interface C1 C0", includeSamples=false, abapFlavor="cloud")
Edge cases / troubleshooting only after official docs fail:
sap_community_search(query="<exact error text or obscure RAP symptom>")
Important: Don't just run these searches verbatim. Analyze the user's spec and craft targeted queries that fill specific knowledge gaps. If the user asks for something unusual (for example, integration with a specific SAP module, specific field types, custom numbering, collaborative draft, or released BO interface consumption), search for those specifics.
No need to research naming conventions at runtime — the official SAP naming schema is documented below in the "SAP Official Naming Conventions" reference section. Use it directly as the default.
1f. Research Summary
Before proceeding, compile a structured research summary. Present this to the user:
## System Research Summary
### System Profile
- Type: [BTP / On-Prem S/4HANA 20XX / ECC with ABAP Platform]
- ABAP Version: [Cloud / Standard ABAP 7.5X]
- RAP Support: [Full managed+draft / Managed only / Basic]
### Existing Code Patterns Found
- Naming: [e.g., "ZI_ prefix for interface views, ZC_ for projections, Z prefix + _D suffix for tables"]
- Architecture: [e.g., "All existing BOs use managed with draft, strict(2), UUID keys"]
- Field Style: [e.g., "CamelCase aliases, abp_ admin field types on BTP"]
- Annotation Style: [e.g., "Metadata extensions for all UI annotations, facet-based layout"]
- Service exposure: [e.g., "projection view + OData V4 UI binding, provider contract aligned"]
- N existing RAP services found: [list names]
### Domain Research
- Related existing objects: [tables, views, classes found]
- SAP standard objects in domain: [relevant standard CDS views, BAPIs]
- Clean core posture: [released APIs confirmed / successor required / custom tables only]
- Best practices from docs: [key findings]
### Quality Baseline
- ATC variant: [DEFAULT / custom]
- Lint findings: [clean / N issues on existing code]
- Strictness: [strict(2) / strict / none]
- Formatter settings: [keywordUpper / keywordLower / keywordAuto, indentation on/off]
Phase 2: Clarifying Questions
Based on research findings, ask targeted questions. Only ask what research couldn't answer. Group questions by category and provide recommendations based on findings.
Architecture Questions
For each question, lead with a concrete recommendation based on the user's spec and research, explain why, then list alternatives with upsides/downsides. These are foundational decisions — changing them after creation requires rebuilding most artifacts. Make sure the user understands the trade-offs.
1. Implementation scenario
Based on your spec [quote relevant part], I would suggest managed because [reason — e.g., "this is a new greenfield BO with no existing persistence logic to wrap"].
Your options:
Option Upside Downside Managed Framework handles CRUD automatically, less code, faster to build Less control over persistence, must follow RAP conventions Unmanaged Full control over persistence, can wrap existing BAPIs/FMs You must implement all CRUD yourself, significantly more code Managed with unmanaged save Managed convenience + custom save (e.g., call BAPI in save phase) More complex, need to understand save sequence Does managed fit, or do you need to wrap existing logic?
2. Entity structure
Based on your spec [quote relevant part], I would suggest [single entity / compositions] because [reason — e.g., "your description mentions line items which is a classic parent-child pattern"].
Your options:
Option Upside Downside Single root entity Simplest, one table, one CDS stack Cannot model hierarchies Compositions (parent → child) Models real business hierarchies (Order → Items), draft cascades to children Each child entity needs its own table + draft table + CDS stack Associations Lightweight references to related entities (e.g., lookup to Customer) No lifecycle dependency, no cascade delete How many entities do you need and what are their relationships?
3. Key strategy
Based on your spec, I would suggest UUID (internal early numbering) because [reason — e.g., "there's no mention of a user-visible business key, and UUID is the simplest and most reliable approach"].
Your options:
Option Upside Downside UUID (internal early numbering) Auto-generated, no user input, no collision risk, simplest Keys are not human-readable Semantic key User-provided meaningful key (e.g., OrderNumber) Needs uniqueness validation, user must know the key upfront Number range Server-assigned sequential numbers, human-readable Needs number range object configuration, more setup Which key strategy fits your use case?
4. Service exposure / provider contract
I recommend OData V4 UI if this is a Fiori Elements-facing service, or OData V4 Web API if it is primarily for programmatic consumers. The service definition provider contract and the service binding type must match.
Important context on service exposure:
- OData V4 UI: Best default for Fiori Elements List Report / Object Page apps.
- OData V4 Web API: Better when the primary consumer is integration code, tests, or external apps.
- OData V2: Use only if there is a hard legacy/UI client requirement.
Which consumer is primary: Fiori UI or API/integration?
4b. Draft model
I recommend draft for transactional Fiori Elements applications unless your use case is explicitly non-draft, API-only, or constrained by system/version realities.
Important constraints from SAP docs:
- Draft requires a dedicated draft table and total ETag.
- Every child in a draft-enabled composition hierarchy must be represented in the BDEF.
- Some OData/Fiori behaviors differ between V2 and V4.
Should this service be draft-enabled?
4c. Authorization model
I recommend
@AccessControl.authorizationCheck: #MANDATORY+ DCLS so the service has explicit row-level authorization from day one. SAP's RAP docs recommend#MANDATORYinstead of#CHECKfor RAP BOs.Your options:
Option Upside Downside #MANDATORY + DCLS Correct RAP baseline, production-ready authorization model Requires access-control design decisions #NOT_ALLOWED / #NOT_REQUIRED Faster prototyping Not suitable for production authorization Should I generate a strict baseline DCLS now (with inheriting conditions) and mark domain-specific rules as follow-up?
Data Model Questions
5. Fields and types
Based on your description, I've identified these business fields:
Field Proposed Type Notes ... ... ... Are these correct? Any fields to add, remove, or change types?
6. Value helps / fixed values
Which fields need dropdowns or value helps?
- Status field → fixed values (e.g., New/Open/Completed)?
- Reference fields → value help from other CDS views?
7. Existing data sources
[If tables/views were found in research] Should this service read from existing table
<TABLE>or create a new table?
7b. Proper DDIC typing (production services)
For production-quality services, I can create proper domains (DOMA) and data elements (DTEL) instead of using inline types. This enables:
- Reusable field types across multiple tables/views
- Fixed value lists on domains (e.g., status domain with A=Active, I=Inactive)
- Consistent field labels (short/medium/long/heading) across all UIs
- Search help attachments on data elements
For
$TMPprototypes, inline types are fine. For transportable packages, proper DOMA/DTEL is recommended. Want me to create dedicated domains and data elements for the business fields?
Naming Questions
8. Entity naming
I'm using the official SAP naming conventions (see reference section below). For an entity named e.g.
Travel:
Artifact SAP Convention Proposed Name Active persistence table A_prefixZA_TRAVELDraft table D_prefixZD_TRAVELBase/interface CDS view R_orI_prefix,TPsuffixZR_TravelTPProjection CDS view C_prefixZC_TravelInterface BDEF Same as root entity ZR_TravelTPProjection BDEF Same as projection view ZC_TravelMetadata extension Same as CDS entity it annotates ZC_TravelService definition UI_prefix (if UI service)ZUI_TravelService binding UI_prefix,_O4suffixZUI_Travel_O4Behavior pool class BP_prefixZBP_R_TravelTP[If different patterns were found on the system]: Note: I found existing RAP projects on your system using a different convention (
<pattern found>). I'm defaulting to SAP standard naming, but if you prefer to match the existing system-wide convention, or use a completely different one, let me know.Any name changes?
UI / Service Questions
9. Fiori Elements frontend
Will this service be consumed by a Fiori Elements app (auto-generated UI from annotations)?
If yes, the metadata extension (DDLX) and UI annotations in the plan will be optimized for Fiori Elements List Report + Object Page (the most common pattern).
Note: ARC-1 currently does not generate the Fiori Elements frontend application itself — only the backend OData service with proper annotations. The Fiori app can be generated from ADT ("Create Fiori Project..." on the service binding) or via the SAP Fiori tools in VS Code. The plan will include guidance on this as a follow-up step.
If no (freestyle UI5 app or non-UI consumer), we can simplify the annotations.
9b. Backend-driven UI features
If this is a Fiori Elements app, should I plan any of these from the start?
- Field-level read-only / mandatory behavior
- Value helps
- Side effects
- Feature control for actions or updates
Note: feature control and side effects are RAP concepts, but they are primarily consumable by Fiori Elements UIs.
10. Searchable fields
Which fields should be searchable (appear in the search bar)?
Business Logic Questions (if applicable)
12. Validations needed
Which business rules should be enforced?
- Mandatory fields?
- Cross-field validations (e.g., start date < end date)?
- Status transition rules?
13. Determinations needed
Which values should be auto-calculated?
- Default values on create?
- Derived fields (e.g., total = price × quantity)?
14. Custom actions
Beyond standard CRUD, do you need actions like "Approve", "Release", "Cancel"?
Important: Don't ask all 14 questions. Research should have answered many of them. Only ask what's genuinely needed. Group remaining questions and present them concisely. Provide your recommendations for each.
Wait for the user to answer before proceeding.
Phase 3: Implementation Plan
Based on research + user answers, create a detailed implementation plan.
3a. Design the Complete Artifact Stack
Create a comprehensive design table:
## RAP Service Implementation Plan: <Service Name>
### Architecture Decisions
| Decision | Choice | Rationale |
|----------|--------|-----------|
| Scenario | Managed / Unmanaged | [why] |
| Service exposure | OData V4 UI / OData V4 Web API / OData V2 | [why] |
| Draft | Yes / No | [why] |
| Key strategy | UUID / Semantic / NumberRange | [why] |
| Provider contract | `odata_v4_ui` / `odata_v4_webapi` / `odata_v2_*` | [why] |
| Strict mode | strict(2) / strict | [system dependent] |
| Admin fields | syuname+timestampl / abp_* types | [system dependent] |
| Authorization | `#MANDATORY + DCLS` / prototype-only | [why] |
| Build engine | ARC-1 (manual stack) / SAP `abap-mcp` generator (single-root seed) | [generator only if it's connected AND the model is a single root, managed+draft] |
### Entity Model
| Entity | Role | Key Fields | Business Fields |
|--------|------|-----------|-----------------|
| <Root> | Root entity | key_uuid | field1, field2, ... |
| <Child> | Composition of Root | key_uuid, parent_uuid | field_a, field_b, ... |
### Artifact Stack
| # | Type | Name | Description | Dependencies |
|---|------|------|-------------|-------------|
| 1 | DDLS | <table> | Database table entity | — |
| 2 | DDLS | <draft_table> | Draft table (if draft) | — |
| 3 | DDLS | ZI_<Entity> | Interface CDS view | #1 |
| 4 | DCLS | ZI_<Entity>_DCL | Access control for interface CDS view | #3 |
| 5 | CLAS | ZBP_I_<Entity> | Behavior pool class | #3 |
| 6 | BDEF | ZI_<Entity> | Interface behavior definition | #3, #5 |
| 7 | DDLS | ZC_<Entity> | Projection CDS view | #3 |
| 8 | BDEF | ZC_<Entity> | Projection behavior definition | #6, #7 |
| 9 | DDLX | ZC_<Entity> | Metadata extension | #7 |
| 10 | SRVD | ZSD_<Entity> | Service definition | #7 |
| 11 | SRVB | ZSB_<Entity>_V4 | Service binding | #10 |
### Field Definitions
| Field | DB Column | CDS Alias | Type | Annotations | Notes |
|-------|-----------|-----------|------|-------------|-------|
| Key | key_uuid | KeyUuid | sysuuid_x16 | @Semantics | Internal numbering |
| ... | ... | ... | ... | ... | ... |
### Behavior Definition Spec
- Scenario: managed
- Draft: with draft / without draft
- ETag: LocalLastChangedAt
- Lock: master [total etag LastChangedAt]
- Numbering: managed (KeyUuid)
- Read-only fields: KeyUuid, CreatedBy, CreatedAt, LastChangedBy, LastChangedAt, LocalLastChangedAt
- Draft actions: Resume, Edit, Activate (optimized), Discard, Prepare
- Determinations (Phase 1): [list with triggers]
- Validations (Phase 1): [list with triggers]
- Custom actions (Phase 1): [list or "none — add later"]
### UI Annotations Spec
- Header: typeName="<Entity>", title=<MainField>, description=<SecondaryField>
- Facets: [list facet structure]
- List columns: [ordered list with position, importance]
- Selection fields: [filter bar fields]
- Search fields: [searchable fields]
### Naming Convention Used
<Document which convention was followed and why — matches existing code / SAP standard / user preference>
### Quality Checks Planned
- Lint validation before each write (automatic via arc-1)
- PrettyPrint of ABAP sources using SAP formatter settings before CLAS writes
- Syntax check after each activation
- ATC check after full stack activation
- Revision/history readback if iterating on pre-existing artifacts
- [If behavior logic]: Unit test skeleton
3b. Present Plan for Approval
Present the plan clearly and ask. Emphasize that changes after creation are significantly harder:
Implementation Plan Ready
I've designed a [managed/unmanaged] RAP service with [N] entities, [with/without] draft, using [naming convention].
[Show the Artifact Stack table and Field Definitions table]
⚠️ Important: Please review carefully before approving. Once the artifacts are created on the SAP system, changing fundamental decisions (managed vs. unmanaged, key strategy, entity structure, draft yes/no) requires deleting and recreating most artifacts. It is much easier to change the plan now than to restructure after creation. If anything is unclear or you're unsure about a decision, ask now.
Please review:
- Are the artifact names correct?
- Are the fields complete and correctly typed?
- Is the architecture (managed/draft/keys) what you need?
- Any questions about the design decisions?
- Any changes before I start creating?
Say "approve" to proceed, or ask questions / tell me what to change.
Do NOT proceed until the user explicitly approves.
Phase 4: Implementation
After approval, create the artifacts. Use batch creation when possible.
Fail fast: If the first DDLS/BDEF write fails with 415 or 500, stop all further CDS writes immediately. Do not retry with different types — the underlying issue is system-level, not object-specific. Run SAPManage(action="probe") to verify rap.available status.
MANDATORY: Error Recovery Protocol
On ANY save failure (400, 007, syntax error) — follow this protocol, no exceptions:
- STOP. Do NOT retry with small variations. Do NOT delete and recreate.
- Read the full error text first. ARC-1 now returns structured DDIC diagnostics (
SBD...message IDs,V1..V4variables, and line-aware details; for source-based DDIC creates it may also append inactive syntax-check results). Use these details to identify the exact failing field/annotation. - Read back the object to see what actually saved:
SAPRead(type=X, name=Y) - Isolate the cause by trying the absolute minimum source (just key fields + all required annotations). If minimum works → add fields one at a time. If minimum fails → the problem is annotations or object type, not your fields.
- Change only ONE thing between retries. Never vary both annotations and fields simultaneously.
- After 3 failures on the same object: STOP. Report the exact error text to the user and ask for guidance. Do NOT continue improvising.
Key principle: The problem is almost always your source content, never the object's state. Deleting and recreating with the same source will produce the same error. Fix the source first.
MANDATORY: Use batch_create First
ALWAYS try batch_create first. Do not start with sequential creates. batch_create creates all objects in one call — put dependencies first in the array (tables → views → DCLS → class → BDEFs → service definition).
SAPWrite(action="batch_create", objects=[...], package="<package>", transport="<transport>")
For composition-linked DDLS or other interdependent siblings (parent's composition [0..*] of ZR_CHILD where the child is also in the same batch), pass activateAtEnd: true so ARC-1 writes inactive drafts for every object first and then issues ONE terminal activateBatch. SAP's activator sees the whole graph at once and resolves cross-references between siblings. Per-object inline activation would fail on the parent with "data source ZR_CHILD does not exist or is not active" because the child is still inactive when the parent gets activated.
SAPWrite(action="batch_create", activateAtEnd: true, objects=[...], package="<package>", transport="<transport>")
If some generated objects need explicit per-item routing, put package and transport on the individual objects. Item-level values override the top-level batch values and are required when a recovered plan mixes packages:
SAPWrite(action="batch_create", objects=[
{type: "TABL", name: "<table>", package: "<package>", transport: "<transport>", source: "<ddl>"},
{type: "DDLS", name: "ZI_<entity>", package: "<package>", transport: "<transport>", source: "<ddl>"}
])
Only fall back to sequential creation (Phase 4b) if batch_create returns an error. If batch fails: read the error, fix the SPECIFIC failing object's source, and retry batch_create. Do NOT switch to sequential mode after one batch failure.
4-pre. Pre-Implementation Check
Before creating artifacts, optionally check for lingering inactive objects that might cause conflicts:
SAPRead(type="INACTIVE_OBJECTS")
Note: This may return 404 on some systems where the /sap/bc/adt/activation/inactive endpoint is not available. If so, skip this check and proceed — it's a convenience check, not a requirement.
If inactive objects with conflicting names exist, resolve them first (activate or delete).
For reset/create preflights that need to know whether target names exist anywhere in the repository, use exact object-directory lookup instead of a long SAPQuery against TADIR:
SAPSearch(searchType="tadir_lookup",
names=["<table>","ZI_<entity>","ZC_<entity>","ZSB_<entity>_V4"],
objectTypes=["TABL","DDLS","BDEF","SRVD","SRVB","CLAS"])
The lookup groups exact matches by requested name and returns missing; do not build large WHERE OBJ_NAME IN (...) SQL lists for this check.
After cleanup, verify the names are truly gone — the default ADT info-system endpoint filters out TADIR rows that don't resolve to a workbench resource, so an orphan "ghost" (TADIR row left behind by an aborted create/delete) is invisible. Re-run the lookup with source: "both" to detect ghosts. This requires sql scope (admin must have SAP_ALLOW_FREE_SQL=true):
SAPSearch(searchType="tadir_lookup",
names=["<table>","ZI_<entity>","ZC_<entity>","ZSB_<entity>_V4"],
source: "both")
If the response contains a splitBrain array, the listed names exist in TADIR but ADT can't resolve them — clean up via SE03 / RS_DD_TADIR_CLEANUP before retrying create.
4-doma. Create Domains and Data Elements (if approved in Phase 2)
If the user opted for proper DDIC typing, create domains and data elements before the table entity:
SAPWrite(action="create", type="DOMA", name="Z<DOMAIN>", package="<package>", transport="<transport>",
dataType="CHAR", length=1, fixedValues=[{low:"A", description:"Active"}, {low:"I", description:"Inactive"}])
SAPWrite(action="create", type="DTEL", name="Z<DATAELEMENT>", package="<package>", transport="<transport>",
typeKind="domain", dataType="Z<DOMAIN>", labels={short:"Status", medium:"Object Status", long:"Object Status", heading:"Status"})
SAPActivate(objects=[{type:"DOMA", name:"Z<DOMAIN>"}, {type:"DTEL", name:"Z<DATAELEMENT>"}])
Then reference the data elements in the table entity DDL instead of inline types (e.g., status : z<dataelement> instead of status : abap.char(1)).
4-gen. (Optional) Delegate the single-root build to SAP's official generator
If the official SAP ABAP MCP server is connected alongside ARC-1 (the abap-mcp server bundled with ABAP Development Tools for VS Code / Eclipse ADT 3.60+) and the approved plan's Build engine is the generator, hand the single-root build to SAP's Generate ABAP Repository Objects framework, then return here for everything it can't do. Only valid for a single root entity (the generator does "a maximum of one entity, no compositions") that is managed+draft on a table with last_changed : abp_lastchange_tstmpl + local_last_changed : abp_locinst_lastchange_tstmpl (or use the from-scratch variant that generates the table). It is one-shot — not for post-generation. Anything else → use 4a/4b.
- Probe + resolve ID (release-specific, never hardcode). No
abap_generators-list_generatorstool → use 4a/4b. Else call it and match "OData UI Service" (or "OData Web API Service") by display name, use the returnedid(uiservice/webapiserviceon SAP_BASIS 758;ui-service/webapi-service/x-ui-serviceon 816). - Schema → generate.
abap_generators-get_schema(generatorId, packageName, referencedObjectType="TABL", referencedObjectName="<table>")→ fill every required field from the returned schema →abap_generators-generate_objects(generatorId, …)into the planned package + transport (a mutation — same guardrails as 4a). - Continue with ARC-1. Validate (4d), then add fields / children / actions / logic and run the quality checks using ARC-1 — the generator won't extend its own output. Record in the summary (Phase 5) which artifacts came from the generator vs ARC-1.
4a. Batch Creation (Preferred)
If the system supports it and the artifact stack is straightforward:
SAPWrite(action="batch_create", objects=[
{type: "TABL", name: "<table>", description: "<desc>", source: "<ddl>"},
{type: "DDLS", name: "ZI_<entity>", description: "<desc>", source: "<ddl>"},
{type: "DCLS", name: "ZI_<entity>_DCL", description: "<desc>", source: "<dcl>"},
{type: "DDLS", name: "ZC_<entity>", description: "<desc>", source: "<ddl>"},
{type: "BDEF", name: "ZI_<entity>", description: "<desc>", source: "<bdef>"},
{type: "BDEF", name: "ZC_<entity>", description: "<desc>", source: "<bdef>"},
{type: "DDLX", name: "ZC_<entity>", description: "<desc>", source: "<ddlx>"},
{type: "SRVD", name: "ZSD_<entity>", description: "<desc>", source: "<srvd>"},
{type: "CLAS", name: "ZBP_I_<entity>", description: "<desc>", source: "<class>"},
{type: "SRVB", name: "ZSB_<entity>_V4", description: "<desc>", serviceDefinition: "ZSD_<entity>", bindingType: "ODataV4-UI"}
], package="<package>", transport="<transport>")
Objects are created in array order — put dependencies first.
4b. Sequential Fallback
If batch creation fails or the stack is complex (compositions, multiple entities), create sequentially in two passes. This avoids BDEF↔behavior-pool deadlocks and reduces retries on on-prem 7.5x.
Pass 1 — minimal working BO (CRUD + compositions):
- Active tables only → Create + Activate each. Defer draft tables.
- Child interface CDS view(s) → Create + Activate.
- Root interface CDS view with compositions (
composition [0..*]) → Create + Activate. - Empty behavior pool class (no
METHODS ... FOR ...declarations) → Create + Activate. - Interface BDEF with CRUD + composition create only. No actions, no determinations/validations, no strict/auth hardening yet.
- Projection CDS view(s) with redirects → Create + Activate.
- Projection BDEF (
projection;header only, use-clauses only) → Create + Activate. - Service definition + service binding → Create + Activate + publish.
At this point the service is previewable and stable.
Pass 2 — business logic + hardening:
- Add actions/determinations/validations to interface BDEF and activate.
- Generate missing behavior handler signatures:
- First preference:
SAPWrite(action="scaffold_rap_handlers", type="CLAS", name="ZBP_I_<entity>", bdefName="ZI_<entity>")to list missing signatures. - Then rerun with
autoApply=trueto inject declarations plus empty implementation stubs into class sections (main,definitions,implementations) when possible. - Next fallback:
SAPDiagnose(action="quickfix", ...)+SAPDiagnose(action="apply_quickfix", ...)if proposals are available. - Fallback: ADT quick-fix in editor if no MCP quick-fix proposal is exposed.
- Implement method bodies with
SAPWrite(action="edit_method", ...)(avoid full-class rewrites when behavior pools are unstable). - Add
strict ( 2 )and authorization handlers only after signatures and method bodies are active. - Add draft last. Prefer generated draft tables (ADT quick-fix) over hand-written draft table definitions.
- Create/activate DCLS and DDLX after BO logic is green.
After pass 2 changes, batch activate interdependent objects:
SAPActivate(objects=[
{type: "CLAS", name: "ZBP_I_<entity>"},
{type: "BDEF", name: "ZI_<entity>"},
{type: "BDEF", name: "ZC_<entity>"}
])
Note: Activation returns structured responses with detailed error/warning messages including line numbers and URIs. Errors block activation; warnings allow it but should be reviewed. Use this information to pinpoint exact issues rather than re-reading full source.
4c. Source Code Templates
Use the source code templates from the plan. Adapt them based on research findings:
- BTP systems: Use
abp_*admin field types, ABAP Cloud syntax,strict ( 2 ) - On-Prem systems: Use
syuname/timestampltypes, classic or Cloud syntax depending on what existing code uses - Follow existing patterns: If existing RAP projects use a specific annotation style or field naming pattern, match it exactly
- Draft: Include draft table, draft actions in interface BDEF,
use draftin projection BDEF - Service exposure: Ensure the service definition provider contract matches the planned binding type
- ABAP formatting: Run
SAPLint(action="format", source="<abap_source>", name="<class_name>")on generated ABAP classes before writing them if you want SAP-native keyword case/indentation
4d. Post-Creation Validation
After all artifacts are created and activated:
-
Syntax check the behavior pool:
SAPRead(type="SYNTAX", objectType="CLAS", name="ZBP_I_<entity>") -
ATC check the full stack (if ATC is available):
SAPDiagnose(action="atc", type="BDEF", name="ZI_<entity>") -
Verify no inactive objects remain (may return 404 on some systems — skip if so):
SAPRead(type="INACTIVE_OBJECTS") -
Read back key artifacts to confirm they're correct:
SAPRead(type="BDEF", name="ZI_<entity>") SAPRead(type="DDLS", name="ZI_<entity>") SAPRead(type="SRVD", name="ZSD_<entity>") -
Lint + formatter check the behavior pool:
SAPRead(type="CLAS", name="ZBP_I_<entity>") SAPLint(action="lint", source="<behavior_pool_source>", name="ZBP_I_<entity>") SAPLint(action="get_formatter_settings")
Fix any issues found. Re-activate if needed.
4e. Create and Publish Service Binding
Create the service binding:
SAPWrite(action="create", type="SRVB", name="ZSB_<entity>_V4", package="<package>", transport="<transport>",
serviceDefinition="ZSD_<entity>", bindingType="ODataV4-UI", description="<Entity> OData V4 Service")
Activate the service binding:
SAPActivate(type="SRVB", name="ZSB_<entity>_V4")
Publish the service binding (makes the OData service available):
SAPActivate(action="publish_srvb", name="ZSB_<entity>_V4")
Verify the publish status and service URL:
SAPRead(type="SRVB", name="ZSB_<entity>_V4")
⚠️ CHECKPOINT: Verify the SRVB read shows published: true, the expected binding type, and a service URL. For OData V4 bindings, publish/unpublish applies to the whole binding, not per service version.
4f. Preview the Service
After the service binding is published, the RAP service can be previewed directly. In ADT, the user can open the service binding, select an entity (e.g., "Root"), and click "Preview..." to launch the Fiori Elements preview in a browser. This generates a preview URL via the ADT business services endpoint.
Inform the user:
Your service is live! Open the service binding
ZSB_<ENTITY>_V4in ADT, select the root entity, and click "Preview..." to see the auto-generated Fiori Elements List Report + Object Page.
Phase 5: Verification & Summary
5a. Final Verification Checklist
RAP Service Generation Complete!
## Architecture
- Scenario: [managed/unmanaged]
- Draft: [enabled/disabled]
- Key strategy: [UUID/semantic/number range]
- OData version: [V4/V2]
- Followed conventions from: [existing code / SAP standard]
## Created Artifacts
[x] Database table entity: <table_name>
[x] Draft table entity: <draft_table> (if applicable)
[x] Interface CDS view: ZI_<Entity>
[x] Interface behavior definition: ZI_<Entity>
[x] Projection CDS view: ZC_<Entity>
[x] Projection behavior definition: ZC_<Entity>
[x] Metadata extension: ZC_<Entity>
[x] Service definition: ZSD_<Entity>
[x] Behavior pool class: ZBP_I_<Entity>
[x] Service binding: ZSB_<Entity>_V4
[x] Service binding published
## Quality Checks
[x] All artifacts activated successfully
[x] Syntax check: clean
[x] Lint check: clean
[x] ATC check: [clean / N findings noted]
## Consistency with Existing Code
[x] Naming matches existing convention: [pattern]
[x] Annotation style matches: [pattern]
[x] Admin fields match: [pattern]
5b. Next Steps
Offer follow-up actions based on the plan:
## Recommended Next Steps
1. **Preview the service** in Fiori Elements (ADT → Service Binding → select entity → Preview...)
2. **Add business logic** → use `generate-rap-logic` skill:
- Determinations: [list from plan]
- Validations: [list from plan]
3. **Add value helps** for reference fields
4. **Add custom actions** if needed (e.g., Approve, Release)
5. **Generate unit tests** → use `generate-abap-unit-test` skill
6. **Add compositions** for child entities (if multi-entity scenario planned for Phase 2)
7. **Register in FLP** (if FLP feature available) → use SAPManage:
- `SAPManage(action="flp_create_catalog", catalogId="Z_<ENTITY>_C", title="<Entity> Catalog")`
- `SAPManage(action="flp_create_tile", catalogId="Z_<ENTITY>_C", tile={id:"Z_<ENTITY>_T", title:"<Entity>", semanticObject:"<Entity>", semanticAction:"manage"})`
- `SAPManage(action="flp_create_group", groupId="Z_<ENTITY>_G", title="<Entity>")`
- `SAPManage(action="flp_add_tile_to_group", groupId="Z_<ENTITY>_G", catalogId="Z_<ENTITY>_C", tileId="Z_<ENTITY>_T")`
8. **Create DOMA/DTEL** (if not done in Phase 4) for proper reusable typing
9. **Release transport** (if transportable package) → use `SAPTransport(action="release_recursive", transport="<TR>")` to release tasks and parent in one step
10. **Attach generated documentation** (optional) → use `SAPWrite(action="create", type="SKTD", refObjectType="SRVD", name="<service_doc_name>", source="<architecture_summary_markdown>")`
11. **Review current assignment + revision context on later iterations** → use `SAPTransport(action="history", type="SRVD", name="ZSD_<ENTITY>")` for the current lock/assignment status and `SAPRead(type="VERSIONS", name="ZSD_<ENTITY>", objectType="SRVD")` for actual revision history. Candidate requests from `history` are assignment choices, not historical membership.
12. **If the package is repo-managed** → use `SAPGit` (`list_repos`, `objects`, `history`) before changing naming or branch conventions
On-Prem 7.5x RAP Quick Reference (read before Phase 4)
This section covers common pitfalls that cause repeated save failures on on-prem ABAP 7.5x systems. Every rule here was learned from real failures — violating any one often returns SBD_MESSAGES 007 save errors. ARC-1 surfaces more detail now, but these pitfalls remain the root causes.
TABL (transparent table) — required annotations
Without ALL of these annotations, the table save always fails with 007:
@EndUserText.label : '<description>'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table <name> {
key client : abap.clnt not null;
key <uuid_key> : sysuuid_x16 not null;
...
}
TABL field types — use qualified names
| Correct | Wrong (causes 007 / activation failure) |
|---|---|
abap.int4 | int4 |
abap.char(N) | char(N) |
abap.numc(N) | numc(N) |
abap.dec(N,M) | dec(N,M) |
abap.clnt | clnt |
sysuuid_x16 | raw(16) for UUID |
timestampl | abap.utclong in TABL |
syuname | abap.uname in TABL |
abap.cuky | cuky |
abap.curr(N,M) | curr(N,M) without reference annotation |
abap.char(1) (X/space booleans) | abap.boolean in TABL |
Client handling
- TABL: Include
key client : abap.clnt not null;as the first key field - CDS view entity: OMIT client from the select list entirely. SAP handles client filtering implicitly. Do NOT add
@ClientHandlingannotation — it is rejected on view entities.
Composition and association rules
- Composition: NO
onclause. Writecomposition [0..*] of ChildView as _Child— the framework resolves by key automatically. Addingoncauses "On conditions are not allowed in compositions." - Association
onconditions: Use CamelCase aliases from the select list, NOT the DB column name. Write$projection.ClubUuid = _Club.ClubUuid, NOT$projection.club_uuid. Using the DB column name causes "The referenced select list name is obscured by an alias." - FK relationship: Express via CDS composition/association in the view entity. Do NOT add
foreign keyclauses in the TABL definition — keep tables simple.
Activation order for parent-child
Activate the child view entity first, then the root. The root's composition references the child, so the child must be active. Use batch activation with both: SAPActivate(objects=[{type:"DDLS",name:"<child>"},{type:"DDLS",name:"<root>"}]) — the activation engine resolves the order.
Lint and non-ABAP types
Pre-write lint runs by default for ABAP sources and DDLS. BDEF/SRVD/SRVB/DDLX/TABL/DOMA/DTEL still need activation or RAP preflight validation for most semantic checks. Keep RAP preflight enabled by default; only use preflightBeforeWrite: false for narrowly-scoped recovery when you understand the specific rule being bypassed. If lint blocks a known-valid case, use lintBeforeWrite: false for that specific write and keep the override local.
Error Recovery
If Research Finds No Existing RAP Projects
This is fine — the system may be new to RAP. Fall back to SAP standard naming conventions and best practices from documentation. Note this in the plan:
"No existing RAP projects found on system. Using SAP standard naming conventions and current best practices from documentation."
If System Doesn't Support Required Features
If research reveals the system lacks a feature the user needs (e.g., draft on old on-prem, table entities pre-7.55):
- Inform the user of the limitation
- Propose an alternative (e.g., classic DDIC table instead of table entity, without draft)
- Adjust the plan accordingly
If Batch Creation Fails
Fall back to sequential creation (Phase 4b). Report which objects succeeded and which failed. Fix the failing object and retry.
Common Issues
| Error | Cause | Fix |
|---|---|---|
| 415 Unsupported Media Type on DDLS/BDEF | RAP/CDS endpoint not responding as expected | Check SAPManage(action="probe") for system info. Verify ICF service activation. Try creating the object in ADT to confirm system capability. |
Resource X does already exist on create | Prior stub or name collision | Switch immediately to SAPWrite(action="update", ...) and resend the full source. Do not retry create with the same payload. |
| Feature not supported | System version too old | Adapt plan to available features |
| Activation error | Dependency order wrong | Use batch activation or sequential in dependency order |
| Lint blocks write | Code doesn't match lint rules | Adjust generated code to pass lint, or check if lint config is too strict |
| BDEF syntax error | Wrong field aliases or entity references | Cross-check CDS aliases with BDEF field references |
| Transport required | Non-$TMP package without transport | Use SAPTransport(action="check") to find or create a transport — see Phase 1-pre |
| Lock conflict on create | Object locked by another user/transport | Wait or use a different name; check SAPTransport(action="list") for conflicting transports |
Annotation with reference to currency code for field X is missing | abap.curr field has no currency reference | Add @Semantics.amount.currencyCode directly above each amount field; pair with abap.cuky field. |
"global or instance" was expected, not "none" | Invalid BDEF auth enum on 7.5x | Use ( global ) or ( instance ), or defer auth until handler exists. |
dependent entity cannot have the identically named field ... as the etag master entity | Root and child etag names collide | Use different etag field names for root vs dependent entities. |
"draft or side" was expected, not "etag" in projection BDEF | use etag header is invalid on 7.5x | Keep projection header as projection; only. |
not a suitable draft persistency ... there is no "X" field | Hand-written draft table column naming mismatch | Generate draft table via quick-fix (preferred), or follow CDS-name derivation exactly. |
Annotation 'UI.headerInfo.X' used at wrong position in DDLX | Unsupported annotation scope in DDLX on 7.5x | Move @UI.headerInfo, @Search.searchable, @ObjectModel.* to projection DDLS source. |
Multiple entries with same name 'X' not allowed in DDLX | Duplicate annotation blocks on same field | Consolidate field annotations into one block. |
[?/011] while updating behavior pool class | Full-class behavior-pool write path unstable for METHODS ... FOR ... | Use SAPWrite(action="scaffold_rap_handlers", ...) first (optionally autoApply=true), then quick-fix fallback, then patch bodies with SAPWrite(action="edit_method", ...). |
Notes
Philosophy
This skill prioritizes correctness and consistency over speed. The extra research time (5-10 minutes) pays off by:
- Avoiding naming conflicts with existing code
- Following established team conventions automatically
- Catching system limitations before hitting errors
- Producing code that looks like it belongs in the codebase
- Giving the user confidence in the architecture before committing
What This Skill Does NOT Do (yet)
- Very large multi-BO landscapes in a single run — keep one business capability per execution
- Unmanaged save implementation (plan it, implement the managed wrapper, note the save handler as a follow-up)
- Custom CDS functions/actions (plan them, implement standard CRUD, add as follow-up)
- Fiori app generation (generates the OData service; Fiori Elements app is auto-generated from annotations)
Relationship to Other Skills
| Skill | Relationship |
|---|---|
generate-rap-service | Vibe code version — faster, less thorough, good for prototypes |
generate-rap-logic | Natural follow-up — implement determinations/validations identified in the plan |
generate-abap-unit-test | Follow-up — generate tests for the behavior pool |
explain-abap-code | Can be used during research to understand existing RAP projects found on the system |
implement-feature | For implementing non-RAP features in the arc-1 codebase itself |
Reference: SAP Official Naming Conventions for RAP Artifacts
Source: SAP Help — Naming Conventions for Development Objects
General Rule
[/<namespace>/][<prefix>]_<object_name>_[<suffix>]
- Use your own namespace reserved for your organization (Z* or Y* for customer objects)
- The
/DMO/namespace is reserved for SAP demo purposes only — never use it in productive development - Prefixes convey semantic differences between types of the same object kind
- Suffixes add secondary differentiation (e.g., OData version, development guide variant)
ABAP Dictionary Objects
| Object | Convention | Example (customer namespace) |
|---|---|---|
| Active persistence table | A_ prefix | ZA_TRAVEL |
| Draft table | D_ prefix | ZD_TRAVEL |
CDS Objects
| Object | Convention | Notes | Example |
|---|---|---|---|
| Base/Root CDS view entity | R_ prefix | The base BO entity. Use TP suffix to indicate transactional processing relevance | ZR_TravelTP |
| Interface CDS view | I_ prefix | Reusable interface view layer (alternative to R_ in some patterns) | ZI_Travel |
| Projection CDS view | C_ prefix | C = consumption layer. If multiple projections exist, the name should represent the projection role | ZC_Travel |
| Extension include view | E_ prefix | For extensibility | ZE_Travel |
| Behavior definition | Same name as root entity | BDEF always shares the name of the CDS view it belongs to | ZR_TravelTP (interface), ZC_Travel (projection) |
| Metadata extension | Same name as CDS entity | If multiple extensions for one entity, add numbered suffix | ZC_Travel, ZC_Travel_2 |
Business Services
| Object | Convention | Notes | Example |
|---|---|---|---|
| Service definition | No mandatory prefix | If not reused across UI/API, may use UI_ or API_ prefix | ZUI_Travel or Z_Travel |
| Service binding (UI) | UI_ prefix | For Fiori Elements / UI consumption | ZUI_Travel_O4 |
| Service binding (Web API) | API_ prefix | For programmatic / integration consumption | ZAPI_Travel_O4 |
| OData V2 suffix | _O2 | ZUI_Travel_O2 | |
| OData V4 suffix | _O4 | ZUI_Travel_O4 |
Source Code Objects
| Object | Convention | Notes | Example |
|---|---|---|---|
| Behavior pool class | BP_ prefix | Global class implementing BO behavior | ZBP_R_TravelTP |
| Local handler class | LHC_ prefix | Local class within behavior pool | LHC_Travel_Create |
| Local saver class | LSC_ prefix | Local class within behavior pool | LSC_Travel |
Complete Example: "Travel" Entity (V4, UI, Draft, Managed)
| # | Object Type | SAP Naming | Name |
|---|---|---|---|
| 1 | Database table (active) | A_ prefix | ZA_TRAVEL |
| 2 | Database table (draft) | D_ prefix | ZD_TRAVEL |
| 3 | Base CDS view entity | R_ prefix + TP suffix | ZR_TravelTP |
| 4 | Projection CDS view | C_ prefix | ZC_Travel |
| 5 | Interface BDEF | = root entity name | ZR_TravelTP |
| 6 | Projection BDEF | = projection view name | ZC_Travel |
| 7 | Metadata extension | = projection view name | ZC_Travel |
| 8 | Service definition | UI_ prefix (optional) | ZUI_Travel |
| 9 | Service binding | UI_ prefix + _O4 suffix | ZUI_Travel_O4 |
| 10 | Behavior pool class | BP_ prefix | ZBP_R_TravelTP |
Notes on R_ vs I_ Prefix
R_(base/root view entity): Used in the SAP standard RAP development guides (managed, unmanaged, draft). This is the current SAP recommendation for new RAP development.I_(interface view): Historically used and still common. Represents a reusable interface layer. Many existing tutorials and older projects useI_instead ofR_.- Both are valid. Default to
R_for new projects following SAP's latest guides. If existing code on the system usesI_, match that for consistency.
Notes on Table Naming
- SAP uses
A_andD_prefixes for active and draft tables respectively - Some older tutorials and community patterns use
_Dsuffix for the table and_DDfor draft — this is not the official SAP convention but is widely seen in practice - The SAP "OData UI Service from Scratch" wizard generates tables with these prefixes automatically
Generate RAP OData UI Service
Generate a complete RAP OData UI service from a natural language description of a business object. Creates the full artifact stack: database table, CDS views, behavior definitions, metadata extension, service definition, and behavior pool class.
This skill replicates SAP Joule's "RAP Service Generation" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices).
v1 Guardrails (fast path): managed scenario only, UUID internal early numbering, single root entity by default, standard CRUD first, draft optional, OData V4 preferred. For multi-entity compositions or heavy custom actions, prefer generate-rap-service-researched.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Package | User's Z* package with transport | Production-ready; only use $TMP if user explicitly asks |
| Key strategy | UUID (sysuuid_x16), managed numbering | Simplest, no collision risk |
| Behavior scenario | Managed | Framework handles CRUD |
| OData version | V4 | Current SAP standard |
| Draft | Prefer for transactional Fiori Elements UI services; verify against release/constraints | Best default for editable FE apps, but not every RAP service needs draft |
| Admin fields | syuname/timestampl (on-prem) or abp_* types (BTP) | System-appropriate |
| Strict mode | strict ( 2 ) unless system patterns or SAP constraints justify otherwise | Current RAP best practice, but not universal |
| Entity prefix | Z + entity name (e.g., ZTRAVEL) | SAP standard Z namespace |
| Naming | SAP standard: ZI_, ZC_, ZSD_, ZSB_, ZBP_I_ | Consistent with SAP docs |
| Service exposure | OData V4 UI provider contract by default | Best fit for Fiori Elements unless the use case is API-first |
Input
The user provides a natural language description of the business object (e.g., "a travel booking app with fields for agency, customer, destination, begin/end date, total price, currency, status").
Only the business object description is required. If the user provides just a description, apply Smart Defaults and proceed immediately.
Optionally, the user may specify:
- Entity name prefix (default: auto-generate from description)
- Package (required — ask if not provided; only default to
$TMPif user explicitly says so) - Transport request (only needed for non-
$TMPpackages — see Step 1b) - Draft enabled (default: yes on BTP, no on-prem)
- OData version (default: V4)
Step 1: Check System Capabilities
Verify the SAP system supports RAP/CDS and detect the system type.
SAPManage(action="probe")
If you need a firmer baseline for syntax and formatter behavior, also read:
SAPRead(type="SYSTEM")
SAPLint(action="list_rules")
SAPLint(action="get_formatter_settings")
Critical gate: If probe clearly reports RAP/CDS unavailable, stop and tell the user RAP object creation cannot proceed via ARC-1 until the endpoint/system setup is fixed.
Determine BTP vs on-prem — this affects naming conventions, language version, and draft handling.
Step 1b: Resolve Package and Transport
Ask the user for their target package if not provided. Then resolve the transport request (skip only if package is $TMP):
SAPTransport(action="check", objectType="DDLS", objectName="<first_object_name>", package="<package>")
This checks if a transport is required and returns existing transports for the package. If a transport is required:
- User provided a transport: Use it for all creates
- Existing transport found: Present the list and ask the user to pick one
- No transport available: Create one:
SAPTransport(action="create", description="RAP Service: <Entity>", package="<package>")
If transport is required but unavailable, STOP — all write operations will fail without a valid transport for non-$TMP packages.
If the package does not exist yet and the user wants a new one, create it first:
SAPManage(action="create_package", name="<package>", description="<description>", transport="<transport_if_required>")
BTP vs On-Prem Differences
| Aspect | BTP (ABAP Cloud) | On-Prem (ABAP Platform) |
|---|---|---|
| Namespace | Z*/Y* only | Z*/Y* or customer namespace |
| Language version | ABAP for Cloud Development (strict) | Standard ABAP or ABAP for Cloud |
| Draft tables | Must be explicitly created (framework manages data, not table) | Must be explicitly created |
| OData version | V4 preferred | V2 or V4 |
| Behavior pool | ABSTRACT class, ABAP Cloud only | ABSTRACT class, classic ABAP allowed |
| Table entity | DEFINE TABLE ENTITY DDL syntax | Classic DDIC table (SE11) or table entity |
On-Prem 7.5x Fast Guardrails
- In TABL source, use
syuname+timestampl(notabap.uname/abap.utclong). - Use
abap.char(1)for boolean-like flags in TABL (notabap.boolean). - Every
abap.curr(...)field needs@Semantics.amount.currencyCodeabove it. - Keep projection BDEF header as
projection;(do not adduse etagheader lines). - Keep RAP preflight checks enabled (default) so deterministic TABL/BDEF/DDLX issues are blocked before activation churn. Only use
preflightBeforeWrite=falseas a local escape hatch. - If behavior-pool full-class writes fail with generic save errors, use
SAPWrite(action="scaffold_rap_handlers", ...)first to derive/apply signatures, then use quickfix fallback +SAPWrite(action="edit_method")for method bodies.
Step 2: Design the Data Model
Based on the user's description, design the complete artifact stack. Follow SAP naming conventions:
Naming Conventions
| Artifact | Pattern | Example |
|---|---|---|
| Database table (table entity) | Z<ENTITY>_D | ZTRAVEL_D |
| Interface CDS view | ZI_<Entity> | ZI_TRAVEL |
| Projection CDS view | ZC_<Entity> | ZC_TRAVEL |
| Metadata extension | ZC_<Entity> | ZC_TRAVEL |
| Interface behavior definition | ZI_<Entity> | ZI_TRAVEL |
| Projection behavior definition | ZC_<Entity> | ZC_TRAVEL |
| Access control (DCL) | ZI_<Entity>_DCL | ZI_TRAVEL_DCL |
| Service definition | ZSD_<Entity> | ZSD_TRAVEL |
| Service binding | ZSB_<Entity>_V4 | ZSB_TRAVEL_V4 |
| Behavior pool class | ZBP_I_<Entity> | ZBP_I_TRAVEL |
| Draft table (if draft) | Z<ENTITY>_DD | ZTRAVEL_DD |
Field Design Rules
Every entity gets these standard fields:
| Field | Type | Purpose |
|---|---|---|
key_uuid | sysuuid_x16 | UUID primary key (internal early numbering) |
created_by | syuname / abp_creation_user | Admin: created by |
created_at | timestampl / abp_creation_tstmpl | Admin: created at |
last_changed_by | syuname / abp_locinst_lastchange_user | Admin: last changed by |
last_changed_at | timestampl / abp_locinst_lastchange_tstmpl | Admin: last changed at (local instance) |
local_last_changed_at | timestampl / abp_lastchange_tstmpl | Admin: total ETag field |
Add business fields based on user description. Choose appropriate ABAP types:
- Text:
abap.char(N)orabap.sstring(N) - Amount:
abap.curr(15,2)with a currency code field (abap.cuky(5)) - Date:
abap.dats - Status:
abap.char(1)with fixed values - Quantity:
abap.quan(13,3)with a unit field (abap.unit(3)) - Integer:
abap.int4
Output to User
Present the complete design as a table:
Proposed artifact stack for "Travel Booking":
| # | Type | Name | Description |
|---|------|------|-------------|
| 1 | TABL | ZTRAVEL_D | Database table entity |
| 2 | DDLS | ZI_TRAVEL | Interface CDS view entity |
| 3 | DCLS | ZI_TRAVEL_DCL | CDS access control (authorization rules) |
| 4 | BDEF | ZI_TRAVEL | Interface behavior definition |
| 5 | DDLS | ZC_TRAVEL | Projection CDS view entity |
| 6 | BDEF | ZC_TRAVEL | Projection behavior definition |
| 7 | DDLX | ZC_TRAVEL | Metadata extension (UI annotations) |
| 8 | SRVD | ZSD_TRAVEL | Service definition |
| 9 | CLAS | ZBP_I_TRAVEL | Behavior pool class |
| 10 | SRVB | ZSB_TRAVEL_V4 | Service binding |
Fields: key_uuid, agency_id, customer_id, destination, begin_date, end_date,
total_price, currency_code, status, created_by, created_at,
last_changed_by, last_changed_at, local_last_changed_at
Ask the user: "Should I proceed with this design? (yes / modify fields / change names)"
Step 3: (Optional) Research RAP Patterns
If mcp-sap-docs is available, fetch current RAP best practices. Start with reference-style queries (includeSamples=false) and then use examples (includeSamples=true) only where needed:
search(query="RAP projection BO vs RAP BO interface", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="RAP draft handling total etag draft-enabled associations", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="service definition provider contracts odata_v4_ui odata_v4_webapi", includeSamples=false, abapFlavor="<cloud|standard>")
search(query="metadata-driven UI metadata extension RAP Fiori Elements", includeSamples=false, abapFlavor="<cloud|standard>")
Use the returned documentation to inform correct annotation patterns, draft handling, provider contracts, and behavior definition syntax.
Step 3b: (Optional) Delegate the build to SAP's official ABAP generator
If the official SAP ABAP MCP server is connected alongside ARC-1 (it ships with ABAP Development Tools for VS Code and is enabled in Eclipse ADT 3.60+, where it appears as the abap-mcp server), you can hand the single-root build to SAP's own Generate ABAP Repository Objects framework and skip the manual templates in Steps 4–13. This is optional — every step below has an ARC-1 fallback, and the generator only fits a narrow shape.
Use the generator only when ALL of these hold (otherwise skip to Batch Creation below):
- Exactly one root entity — the generator does "a maximum of one entity", no compositions or hierarchies.
- Managed + draft — the only mode it produces.
- The base table carries the modern timestamp fields
last_changed : abp_lastchange_tstmplandlocal_last_changed : abp_locinst_lastchange_tstmpl(the generator requires them), or you use the from-scratch variant that generates the table for you. - You accept it is one-shot — "not intended for post-generation". Re-running won't extend an existing BO; later changes are manual (ARC-1's job).
3b-1. Probe the server
If you do not have a tool named abap_generators-list_generators (the official abap-mcp server), it isn't connected → skip to Batch Creation. Don't ask the user — just fall back silently.
3b-2. Resolve the generator ID (IDs are release-specific — NEVER hardcode)
Call abap_generators-list_generators and pick the generator whose display name is "OData UI Service" (for a Fiori UI app) or "OData Web API Service" (for a headless API), then use the id it returns. The IDs differ by release — proven live:
| Release | UI service | Web API service | From scratch (generates the table too) |
|---|---|---|---|
| S/4HANA 2023 (SAP_BASIS 758) | uiservice | webapiservice | — |
| ABAP Platform 2025 (SAP_BASIS 816) | ui-service | webapi-service | x-ui-service |
If no matching generator is listed, the framework isn't available on this release → skip to Batch Creation.
3b-3. Read the input schema
abap_generators-get_schema needs five inputs and errors without a real referenced table:
abap_generators-get_schema(
generatorId = "<id from 3b-2>",
packageName = "<target package>", // your allowlisted package, or $TMP
referencedObjectType = "TABL",
referencedObjectName = "<existing base table>")
(The from-scratch x-ui-service does not need a referenced table — confirm from the schema it returns.) Typical config points in the returned schema: package, data model (root entity name + EML alias), behavior (draft table name), service projection name, service definition, service binding (OData service name), transport. Read the real schema and fill every required field — don't assume field names from this doc; they vary by release.
Observed shape on S/4HANA 2023 (uiservice, referenced table ZARC1_DEMO_BOOK) — verified live; yours may differ, so read the live response:
dataModelEntity.cdsName → ZR_ARC1_DEMO_BOOK (root CDS)
implementationClass → ZBP_ARC1_DEMO_BOOK (behavior pool class)
draftTable → ZARC1_DEMO_BOOKD
serviceProjection.name → ZC_ARC1_DEMO_BOOK (projection CDS, exposed by the service)
serviceDefinition.name → ZUI_ARC1_DEMO_BOOK_O4
serviceBinding.name → ZUI_ARC1_DEMO_BOOK_O4 (binding type: OData V4 - UI)
3b-4. Generate
abap_generators-generate_objects(generatorId="<id>", <filled schema>). This is a mutation — apply the same guardrails as any ARC-1 write (allowlisted package + a real transport, or $TMP). One call creates the CDS root + projection, BDEF + behavior class, metadata extension (DDLX), draft table, service definition, and service binding.
3b-5. Verify, then continue with ARC-1
Activate/verify with ARC-1 (SAPActivate, SAPRead) or the official abap_activate_objects. Publish the service binding with ARC-1 — SAPActivate(action="publish_srvb", name="<binding>") — because on 7.5x the generator creates and activates the SRVB but its own publish step returns a 406 (publish-job content negotiation), leaving it published:false with no runtime URL. ARC-1's publish_srvb handles the 758 content type and flips it to published:true (verified live on S/4HANA 2023: the generated binding went unpublished → published, and $metadata then returned HTTP 200). Then use ARC-1 for anything the single-entity, one-shot generator can't do — add fields, compositions/children, actions + handler bodies (SAPWrite action="edit_method"), determinations, validations, and all later edits.
State which path you took ("base BO generated via abap-mcp <id>, extended via ARC-1" vs "built entirely via ARC-1") so the run stays auditable.
Batch Creation (Preferred)
Instead of creating each artifact individually in Steps 4-13, you can use batch creation to create all RAP artifacts in a single tool call:
SAPWrite(action="batch_create", objects=[
{type: "TABL", name: "<table_name>", description: "<Entity> Table", source: "<table_ddl>"},
{type: "DDLS", name: "ZI_<entity>", description: "<Entity> Interface View", source: "<interface_view_ddl>"},
{type: "DCLS", name: "ZI_<entity>_DCL", description: "<Entity> Access Control", source: "<interface_dcl_source>"},
{type: "DDLS", name: "ZC_<entity>", description: "<Entity> Projection View", source: "<projection_view_ddl>"},
{type: "BDEF", name: "ZI_<entity>", description: "<Entity> Interface Behavior", source: "<interface_bdef>"},
{type: "BDEF", name: "ZC_<entity>", description: "<Entity> Projection Behavior", source: "<projection_bdef>"},
{type: "DDLX", name: "ZC_<entity>", description: "<Entity> Metadata Extension", source: "<ddlx_source>"},
{type: "SRVD", name: "ZSD_<entity>", description: "<Entity> Service Definition", source: "<srvd_source>"},
{type: "CLAS", name: "ZBP_I_<entity>", description: "<Entity> Behavior Pool", source: "<class_source>"},
{type: "SRVB", name: "ZSB_<entity>_V4", description: "<Entity> Service Binding", serviceDefinition: "ZSD_<entity>", bindingType: "ODataV4-UI"}
], package="<package>", transport="<transport>")
Objects are created and activated in array order — put dependencies first (table before CDS views, DCLS after DDLS, CDS views before BDEFs, behavior pool before interface BDEF). The batch stops on the first failure and reports which objects succeeded and which failed.
Set package and transport at the top level when every artifact shares them. If a batch item needs to override either value, put package and/or transport on that object; item-level values win.
Pass activateAtEnd: true for stacks with cross-sibling references (e.g. composition-linked DDLS where the parent's composition [0..*] of ZR_CHILD references a child that's also in this batch). ARC-1 writes inactive drafts for every object and then issues one terminal activateBatch — SAP's activator sees the whole graph and resolves the cross-references in a single pass. Without this flag, the parent's inline activation fails with "data source ZR_CHILD does not exist or is not active".
If batch creation fails, fall back to the sequential approach below (Steps 4-13).
Step 4: Create Database Table (Sequential Fallback)
Create the table entity via CDS DDL.
SAPWrite(action="create", type="TABL", name="<table_name>", package="<package>", transport="<transport>", source="<ddl_source>")
Table Entity DDL Template
@EndUserText.label : '<Entity description>'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table <table_name> {
key client : abap.clnt not null;
key key_uuid : sysuuid_x16 not null;
<business_field_1> : <type>;
<business_field_2> : <type>;
// ... more business fields
created_by : syuname;
created_at : timestampl;
last_changed_by : syuname;
last_changed_at : timestampl;
local_last_changed_at : timestampl;
}
Activate the table:
SAPActivate(type="TABL", name="<table_name>")
Fallback: If table entity creation fails (e.g., on older on-prem systems), instruct the user to create the table manually via SE11 or ADT, providing the field list and types.
Step 5: Create Interface CDS View
SAPWrite(action="create", type="DDLS", name="ZI_<entity>", package="<package>", transport="<transport>", source="<ddl_source>")
Interface View DDL Template
@AccessControl.authorizationCheck: #MANDATORY
@EndUserText.label: '<Entity description>'
define root view entity ZI_<Entity>
as select from <table_name>
{
key key_uuid as KeyUuid,
<business_field_1> as <CamelCaseAlias1>,
<business_field_2> as <CamelCaseAlias2>,
// ... more business fields
@Semantics.amount.currencyCode: 'CurrencyCode'
total_price as TotalPrice,
currency_code as CurrencyCode,
@Semantics.user.createdBy: true
created_by as CreatedBy,
@Semantics.systemDateTime.createdAt: true
created_at as CreatedAt,
@Semantics.user.localInstanceLastChangedBy: true
last_changed_by as LastChangedBy,
@Semantics.systemDateTime.localInstanceLastChangedAt: true
local_last_changed_at as LocalLastChangedAt,
@Semantics.systemDateTime.lastChangedAt: true
last_changed_at as LastChangedAt
}
Activate:
SAPActivate(type="DDLS", name="ZI_<entity>")
Step 5a: Create Interface Access Control (DCLS)
Create a basic CDS access control role for the interface view.
SAPWrite(action="create", type="DCLS", name="ZI_<entity>_DCL", package="<package>", transport="<transport>", source="<dcl_source>")
Interface DCL Template
@EndUserText.label: '<Entity description> Access Control'
@MappingRole: true
define role ZI_<Entity>_DCL {
grant select on ZI_<Entity>
where inheriting conditions from super;
}
Activate:
SAPActivate(type="DCLS", name="ZI_<entity>_DCL")
Step 5b: Create Draft Table (if draft enabled)
If draft is enabled, create the draft table entity before creating the behavior definition that references it. The RAP framework manages runtime persistence of draft data to this table, but the table itself must be created explicitly.
SAPWrite(action="create", type="TABL", name="<draft_table>", package="<package>", transport="<transport>", source="<ddl_source>")
Draft Table Entity DDL Template
@EndUserText.label : '<Entity description> - Draft'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #RESTRICTED
define table <draft_table> {
key client : abap.clnt not null;
key key_uuid : sysuuid_x16 not null;
<business_field_1> : <type>;
<business_field_2> : <type>;
// ... same business fields as the main table
created_by : syuname;
created_at : timestampl;
last_changed_by : syuname;
last_changed_at : timestampl;
local_last_changed_at : timestampl;
}
Activate the draft table:
SAPActivate(type="TABL", name="<draft_table>")
Note: On BTP ABAP Environment, the draft table must still be explicitly created — the framework manages draft data persistence at runtime, not the table's existence.
Step 6: Create Interface Behavior Definition
SAPWrite(action="create", type="BDEF", name="ZI_<entity>", package="<package>", transport="<transport>", source="<bdef_source>")
With Draft
managed implementation in class ZBP_I_<Entity> unique;
strict ( 2 );
with draft;
define behavior for ZI_<Entity> alias <Entity>
persistent table <table_name>
draft table <draft_table>
etag master LocalLastChangedAt
lock master total etag LastChangedAt
authorization master ( instance )
{
field ( readonly )
KeyUuid,
CreatedBy,
CreatedAt,
LastChangedBy,
LastChangedAt,
LocalLastChangedAt;
field ( numbering : managed )
KeyUuid;
create;
update;
delete;
draft action Resume;
draft action Edit;
draft action Activate optimized;
draft action Discard;
draft determine action Prepare;
}
Without Draft
managed implementation in class ZBP_I_<Entity> unique;
strict ( 2 );
define behavior for ZI_<Entity> alias <Entity>
persistent table <table_name>
etag master LocalLastChangedAt
lock master
authorization master ( instance )
{
field ( readonly )
KeyUuid,
CreatedBy,
CreatedAt,
LastChangedBy,
LastChangedAt,
LocalLastChangedAt;
field ( numbering : managed )
KeyUuid;
create;
update;
delete;
}
Do NOT activate the interface BDEF individually — it references the behavior pool class (ZBP_I_) which does not exist yet. It will be activated in the batch activation step after the class is created.
Step 7: Create Projection CDS View
SAPWrite(action="create", type="DDLS", name="ZC_<entity>", package="<package>", transport="<transport>", source="<ddl_source>")
Projection View DDL Template
@AccessControl.authorizationCheck: #MANDATORY
@EndUserText.label: '<Entity description> - Projection'
@Metadata.allowExtensions: true
@Search.searchable: true
define root view entity ZC_<Entity>
provider contract transactional_query
as projection on ZI_<Entity>
{
key KeyUuid,
@Search.defaultSearchElement: true
<BusinessField1>,
@Search.defaultSearchElement: true
<BusinessField2>,
// ... more business fields
TotalPrice,
CurrencyCode,
CreatedBy,
CreatedAt,
LastChangedBy,
LastChangedAt,
LocalLastChangedAt
}
Mark the most important business fields (typically name, ID, description) with @Search.defaultSearchElement: true.
Activate:
SAPActivate(type="DDLS", name="ZC_<entity>")
Step 8: Create Projection Behavior Definition
SAPWrite(action="create", type="BDEF", name="ZC_<entity>", package="<package>", transport="<transport>", source="<bdef_source>")
With Draft
projection;
strict ( 2 );
use draft;
define behavior for ZC_<Entity> alias <Entity>
{
use create;
use update;
use delete;
use action Resume;
use action Edit;
use action Activate;
use action Discard;
use action Prepare;
}
Without Draft
projection;
strict ( 2 );
define behavior for ZC_<Entity> alias <Entity>
{
use create;
use update;
use delete;
}
Do NOT activate the projection BDEF individually — it uses use create, use update, use delete which reference the interface BDEF (ZI_), and that BDEF is not yet activated. It will be activated in the batch activation step after all artifacts are created.
Step 9: Create Metadata Extension (DDLX)
SAPWrite(action="create", type="DDLX", name="ZC_<entity>", package="<package>", transport="<transport>", source="<ddlx_source>")
Metadata Extension Template
@Metadata.layer: #CUSTOMER
@UI: {
headerInfo: {
typeName: '<Entity Name>',
typeNamePlural: '<Entity Name Plural>',
title: { type: #STANDARD, value: '<MainBusinessField>' },
description: { type: #STANDARD, value: '<SecondaryField>' }
}
}
annotate view ZC_<Entity> with
{
@UI.facet: [
{
id: 'idIdentification',
type: #IDENTIFICATION_REFERENCE,
label: 'General Information',
position: 10
}
]
@UI.hidden: true
KeyUuid;
@UI: {
lineItem: [{ position: 10, importance: #HIGH }],
identification: [{ position: 10 }],
selectionField: [{ position: 10 }]
}
<BusinessField1>;
@UI: {
lineItem: [{ position: 20, importance: #HIGH }],
identification: [{ position: 20 }],
selectionField: [{ position: 20 }]
}
<BusinessField2>;
// ... more business fields with incrementing positions
@UI: {
lineItem: [{ position: 50, importance: #MEDIUM }],
identification: [{ position: 50 }]
}
TotalPrice;
@UI.hidden: true
CreatedBy;
@UI.hidden: true
CreatedAt;
@UI.hidden: true
LastChangedBy;
@UI.hidden: true
LastChangedAt;
@UI.hidden: true
LocalLastChangedAt;
}
Position numbering: increment by 10. Assign importance: #HIGH to the most relevant business fields (shown in narrow screens), #MEDIUM for secondary fields. Add @UI.selectionField to fields the user would filter by.
Activate:
SAPActivate(type="DDLX", name="ZC_<entity>")
Step 10: Create Service Definition
SAPWrite(action="create", type="SRVD", name="ZSD_<entity>", package="<package>", transport="<transport>", source="<srvd_source>")
Service Definition Template
@EndUserText.label: '<Entity description> Service'
define service ZSD_<Entity>
provider contracts odata_v4_ui
{
expose ZC_<Entity> as <Entity>;
}
If the primary consumer is an API/integration use case rather than Fiori Elements, switch the provider contract and binding type together:
define service ZSD_<Entity>
provider contracts odata_v4_webapi
{
expose ZC_<Entity> as <Entity>;
}
Activate:
SAPActivate(type="SRVD", name="ZSD_<entity>")
Step 11: Create Behavior Pool Class
Create the behavior pool class BEFORE batch activation — the interface BDEF references this class via implementation in class ZBP_I_<Entity>.
Before writing, optionally run the SAP PrettyPrinter so the class source matches the system's keyword style and indentation:
SAPLint(action="format", source="<class_source>", name="ZBP_I_<entity>")
SAPWrite(action="create", type="CLAS", name="ZBP_I_<entity>", package="<package>", transport="<transport>", source="<class_source>")
Behavior Pool Class Template
CLASS zbp_i_<entity> DEFINITION
PUBLIC ABSTRACT FINAL
FOR BEHAVIOR OF zi_<entity>.
ENDCLASS.
CLASS zbp_i_<entity> IMPLEMENTATION.
ENDCLASS.
Activate:
SAPActivate(type="CLAS", name="ZBP_I_<entity>")
Step 12: Batch Activate All Artifacts
First, optionally check for any lingering inactive objects that might interfere:
SAPRead(type="INACTIVE_OBJECTS")
Note: This may return 404 on some systems where the /sap/bc/adt/activation/inactive endpoint is not available. If so, skip this check and proceed.
Activate all artifacts together to resolve cross-dependencies:
SAPActivate(objects=[
{type:"TABL", name:"<table_name>"},
{type:"DDLS", name:"ZI_<entity>"},
{type:"DCLS", name:"ZI_<entity>_DCL"},
{type:"CLAS", name:"ZBP_I_<entity>"},
{type:"BDEF", name:"ZI_<entity>"},
{type:"DDLS", name:"ZC_<entity>"},
{type:"BDEF", name:"ZC_<entity>"},
{type:"DDLX", name:"ZC_<entity>"},
{type:"SRVD", name:"ZSD_<entity>"}
])
Note: Activation returns structured responses with detailed error/warning messages including line numbers and URIs. Errors block activation; warnings allow it but should be reviewed.
If batch activation fails, activate sequentially in dependency order:
- Table entity
- Interface CDS view
- Interface access control (DCLS)
- Behavior pool class
- Interface behavior definition
- Projection CDS view
- Projection behavior definition
- Metadata extension
- Service definition
If behavior pool activation fails because METHODS ... FOR ... signatures are missing:
- Use
SAPWrite(action="scaffold_rap_handlers", type="CLAS", name="<bp_class>", bdefName="ZI_<entity>")to list missing signatures. - If needed, rerun with
autoApply=trueto inject signatures into class declarations plus empty method stubs. - If signatures are still unresolved, use
SAPDiagnose(action="quickfix", ...)andSAPDiagnose(action="apply_quickfix", ...)when proposals are available. - Fallback to ADT editor quick-fix generation, then patch method bodies with
SAPWrite(action="edit_method", ...).
For any failing object, run syntax check to identify the issue:
SAPRead(type="SYNTAX", objectType="<type>", name="<name>")
Step 13: Create and Publish Service Binding
Create the service binding:
SAPWrite(action="create", type="SRVB", name="ZSB_<entity>_V4", package="<package>", transport="<transport>",
serviceDefinition="ZSD_<entity>", bindingType="ODataV4-UI", description="<Entity> OData V4 Service")
Activate the service binding:
SAPActivate(type="SRVB", name="ZSB_<entity>_V4")
Publish the service binding (makes the OData service available):
SAPActivate(action="publish_srvb", name="ZSB_<entity>_V4")
Verify the publish status and service URL:
SAPRead(type="SRVB", name="ZSB_<entity>_V4")
⚠️ CHECKPOINT: Verify the SRVB read shows published: true, the expected binding type, and a service URL. For OData V4 bindings, publish/unpublish applies to the whole binding.
Step 14: Verify Complete Service
Read back key artifacts and run final checks:
SAPRead(type="DDLS", name="ZI_<entity>")
SAPRead(type="DCLS", name="ZI_<entity>_DCL")
SAPRead(type="BDEF", name="ZI_<entity>")
SAPRead(type="DDLS", name="ZC_<entity>")
SAPRead(type="SYNTAX", objectType="CLAS", name="ZBP_I_<entity>")
Present a summary checklist:
RAP Service Generation Complete!
Created artifacts:
[x] Database table entity: <table_name>
[x] Interface CDS view: ZI_<Entity>
[x] Interface access control: ZI_<Entity>_DCL
[x] Interface behavior definition: ZI_<Entity>
[x] Projection CDS view: ZC_<Entity>
[x] Projection behavior definition: ZC_<Entity>
[x] Metadata extension: ZC_<Entity>
[x] Service definition: ZSD_<Entity>
[x] Behavior pool class: ZBP_I_<Entity>
[x] Service binding: ZSB_<Entity>_V4
[x] Service binding published
Next steps:
- Add validations and determinations (use generate-rap-logic skill)
- Add value helps for business fields
- Add custom actions if needed
- Generate unit tests (use generate-abap-unit-test skill)
- Register in FLP launchpad (use SAPManage flp_create_catalog, flp_create_tile, flp_create_group)
- Create proper DOMA/DTEL for reusable typing (use SAPWrite with type=DOMA/DTEL)
- Attach SKTD documentation to the service or BDEF (optional)
- Review later iterations with `SAPTransport(action="history", type=…, name=…)` for current lock/assignment status plus `SAPRead(type="VERSIONS", ...)` for actual revision history
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
| 415 Unsupported Media Type on DDLS/BDEF | RAP/CDS endpoint not responding as expected | Check SAPManage(action="probe") for system info. Verify ICF service activation. Try creating the object in ADT to confirm system capability. |
Resource X does already exist on create | Existing object or stub collision | Switch to SAPWrite(action="update", ...) and resend full source. Do not retry create blindly. |
| Activation error: dependency not found | Objects activated in wrong order | Use sequential activation in dependency order (Step 12 fallback) |
| Draft table not found | Draft table not yet created | Create draft table entity first, or remove with draft from BDEF |
| Field mapping incomplete | BDEF field names don't match CDS aliases | Verify CDS field aliases match BDEF field references exactly |
| ETag field not found | LocalLastChangedAt missing or misnamed | Verify admin fields exist in CDS view with correct aliases |
| Behavior pool not found | Class name doesn't match BDEF implementation in class | Ensure class name in BDEF matches the created class exactly |
BDEF creation/save fails with generic [?/011] | Behavior-pool full-class save path is unstable for RAP handler declarations | Keep class minimal, generate signatures via quickfix (MCP or ADT), then use edit_method for bodies |
| Lint blocks write | Blocking finding or unsupported parser syntax | Check lint/version and ask SAP to check the proposed source. Correct genuine errors; do not rewrite SAP-accepted syntax just to satisfy abaplint. |
| Table entity creation not supported | Older on-prem system | Create table via SE11 manually, provide field list |
| Transport required | Non-$TMP package without transport | Use SAPTransport(action="check") to find or create a transport — see Step 1b |
| Lock conflict on create | Object locked by another user/transport | Wait or use a different name; check SAPTransport(action="list") for conflicting transports |
| Currency reference annotation missing | abap.curr field has no currency semantics annotation | Add @Semantics.amount.currencyCode above each amount field and ensure a abap.cuky field exists |
"draft or side" was expected, not "etag" | Invalid projection BDEF header syntax on 7.5x | Keep header as projection; only |
Notes
BTP vs On-Prem Summary
- BTP: Z*/Y* namespace only, ABAP Cloud syntax enforced, draft tables must be explicitly created (framework manages draft data at runtime), V4 OData preferred,
strict ( 2 )in BDEF, table entity DDL syntax, released SAP APIs only. - On-Prem: More namespace flexibility, classic ABAP allowed in behavior pool (not recommended), explicit draft table creation may be needed, V2 or V4,
strictlevel depends on release.
What This Skill Does NOT Do (v1)
- Complex compositions / child hierarchies: Use
generate-rap-service-researchedfor multi-entity BOs and two-pass rollout. - Custom actions: No
actiondeclarations beyond draft actions. Use generate-rap-logic skill after. - Determinations / validations: No business logic. Use generate-rap-logic skill to add these after.
- Value helps: No
@Consumption.valueHelpDefinitionannotations. Add manually. - Feature control / side effects: No backend-driven UI behavior beyond standard CRUD. Add manually when the UI needs dynamic enablement or recalculation hints.
- Unmanaged / abstract BOs: Only managed scenario with UUID keys.
- DOMA/DTEL creation: Uses inline types. For production services, create proper domains and data elements afterward using
SAPWrite(type="DOMA"/"DTEL"). - FLP registration: Does not auto-register in Fiori Launchpad. Use
SAPManageFLP actions afterward.
When to Use This Skill
- When starting a new RAP application from scratch
- When the user describes a business object in natural language
- When prototyping a Fiori Elements app quickly
- NOT for adding to an existing RAP service (use manual editing or generate-rap-logic)
- NOT for complex data models with multiple entities (v1 is single root entity only)
Migrate Custom Code
ATC-driven S/4HANA custom code migration assistant with automated fix proposals.
This skill replicates SAP Joule's "Custom Code Migration" capability by combining ARC-1 (SAP system access) with mcp-sap-docs (documentation & best practices). It runs ATC readiness checks, groups and explains findings, and generates replacement code following modern ABAP patterns.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Object type | Auto-detect via SAPSearch | Don't make user look up the type |
| ATC variant | System default | Omitting variant makes ARC-1 resolve and send systemCheckVariant |
| Scope | fix (explain + fix proposals) | Most actionable output |
| Priority filter | All priorities (start with Priority 1 errors) | Don't miss anything, but fix most critical first |
Input
The user provides an object or package to check (e.g., ZCL_SALES_HANDLER, Z_REPORT_POSTING, ZSALES_PKG).
Only the object name is required. If the user provides just an object name, auto-detect the type and proceed with the default variant and fix scope.
Optionally, the user may specify:
- Object type (default: auto-detect via SAPSearch)
- Target release variant (e.g.,
S4HANA_2023,S4HANA_READINESS; default: system default) - Scope —
explain(findings only) orfix(explain + fix proposals; default:fix)
Step 1: Run ATC Readiness Check
ATC gotchas (verified live on S/4HANA 2023):
- ATC skips
$TMP/ local objects. A check run against a$TMPobject resolves to an empty object set and returns zero findings — this is not "clean code", it's "not checked". Run ATC against objects in a transportable package. If the user points you at$TMPcode, say so and ask them to assign it to a transportable package first.- The check variant must exist on the system.
ABAP_CLOUD_READINESSis the standard name on SAP BTP ABAP / S/4HANA Cloud, but on-premise systems often shipS4HANA_READINESS_<release>(e.g.S4HANA_READINESS_2023) orSAP_CLOUD_PLATFORM_DEFAULTinstead. If the named variant is absent ARC-1 rejects the call (SAP would silently runDEFAULT) — list the real names withSAPDiagnose(action="atc_variants"), or omitvariantto bind the system's configured default.
1a. Run ATC on the target object
SAPDiagnose(action="atc", type="<type>", name="<object_name>", variant="<variant>")
If no variant was specified, run with the system default first (omitting variant makes ARC-1 resolve systemCheckVariant from ATC customizing and send it explicitly — SAP's own empty-checkVariant behavior would run the Code Inspector variant DEFAULT instead):
SAPDiagnose(action="atc", type="<type>", name="<object_name>")
Then suggest a readiness variant if available (e.g., S4HANA_READINESS_2023, ABAP_CLOUD_READINESS). If a run returns zero findings on code you expect to be flagged, first confirm the object is not in $TMP (see the gotcha above).
1b. For package-level checks — find all objects first
SAPRead(type="DEVC", name="<package_name>")
This returns all objects in the package. Then run ATC on each object individually. For large packages, prioritize PROG, CLAS, FUGR, FUNC types first as they typically contain the most migration-relevant findings.
Step 2: Group and Prioritize Findings
Organize findings into a structured summary. Deduplicate findings with the same checkTitle across multiple locations.
Summary Table
Present findings grouped by priority and category:
Migration Readiness Report for <object_name>
=============================================
Total findings: <N>
Priority 1 (Errors): <n>
Priority 2 (Warnings): <n>
Priority 3 (Info): <n>
| # | Priority | Check | Category | Count | Affected Objects |
|---|----------|-------|----------|-------|------------------|
| 1 | 1 | Use of obsolete statement MOVE | Syntax Change | 3 | Z_REPORT_POSTING |
| 2 | 1 | Call to released API CL_GUI_ALV_GRID | Deprecated API | 1 | Z_REPORT_POSTING |
| 3 | 2 | SELECT...ENDSELECT pattern | Performance | 5 | Z_REPORT_POSTING |
| ...
Categories
Group findings into these categories:
- Deprecated API: Calls to functions, classes, or methods that are deprecated or not released in S/4HANA
- Syntax Change: Obsolete ABAP statements that must be replaced
- Semantic Change: Behavior differences in S/4HANA (e.g., changed table structures, removed fields)
- Performance: Patterns that need optimization for S/4HANA
- Simplification: Items from the S/4HANA simplification list
Ask the user: "Which findings should I explain and fix? (all / specific numbers / errors only)"
Step 3: Explain Findings
For each selected finding, provide a detailed explanation.
3a. Read the affected source code
SAPRead(type="<type>", name="<object_name>")
Show the code context around each finding (the line with the issue and a few lines before/after).
3b. Search documentation for migration guidance
search("<checkTitle> S/4HANA migration")
search("<deprecated_api> replacement ABAP")
For specific simplification items:
search("<simplification_item_id> simplification list")
3c. Search SAP Notes (if SAP Notes MCP is available)
sap_notes_search(q="<checkTitle>")
sap_notes_search(q="<deprecated_api> replacement")
3d. Present explanation for each finding
For each finding, present:
- What: The finding description and where it occurs (file, line)
- Why: Why this is a problem for S/4HANA (compatibility, removal, behavior change)
- Replacement: The recommended modern ABAP pattern or API to use instead
- Impact: Risk level of the change (low = syntax swap, medium = logic change, high = redesign needed)
Step 4: Generate Fix Proposals
For each fixable finding, generate replacement code based on documentation and modern ABAP patterns.
4a. Check SAP quickfix first (before LLM-generated fixes)
For each finding location, first check whether SAP provides a native quickfix:
SAPDiagnose(action="quickfix", type="<type>", name="<object_name>", source="<current_source>", line=<finding_line>, column=0)
If proposals are returned:
- Present them as SAP-verified fixes (higher confidence than LLM-generated fixes)
- If the user selects one, apply it and get exact text deltas:
SAPDiagnose(action="apply_quickfix", type="<type>", name="<object_name>", source="<current_source>", line=<finding_line>, column=0, proposalUri="<proposal_uri>", proposalUserContent="<proposal_user_content>")
apply_quickfixreturns ranged text deltas — it does not persist. Apply the returned deltas to the source yourself, then write the result viaSAPWrite(action="update"). When applying multiple fixes to the same object, re-resolve each finding's line after each write (earlier edits shift later line numbers), or fix top-to-bottom.
Quickfix availability is system-dependent. SAP only offers quickfix proposals where the system has the corresponding check/cloudification content installed. On a bare ABAP trial or a system without the Clean-Core remediation content,
getFixProposalsreturns[]and ATC findings carryhasQuickfix=false— that's expected, not a bug. In that case skip straight to LLM-generated fixes (the options below). Prefer SAP quickfixes only when they actually come back.
Match the proposal to the finding — don't blindly apply
proposals[0].quickfixreturns every proposal applicable at that source position, which often includes generic refactorings unrelated to the finding (verified live on S/4HANA 2023: a position returned "Rename", "Convert to attribute", "Convert to importing parameter", "Extract local variable", …). Pick the proposal whosename/descriptionactually addresses the finding; ignore the rest.
Review quick-fix deltas before saving. Pass its
userContentunchanged (including an empty string)./providers/refactoring/alone does not make a proposal unsupported.apply_quickfixreturns edits without saving; inspect affected objects and run a syntax check beforeSAPWrite. Some SAP proposals need additional input or suggest types that require correction.
Fix Options
Present 4 options per finding:
- Apply — Auto-write the fix via ARC-1
- Show — Display the before/after diff without applying
- Skip — Move to the next finding
- SAP Quick Fix — Apply SAP's quickfix proposal when available (preferred over LLM-generated fix)
Group related fixes that can be applied together (e.g., multiple deprecated statements in the same method).
Common Migration Patterns
Use these replacement patterns when generating fixes:
| Old Pattern | New Pattern | Notes |
|---|---|---|
CALL FUNCTION '<fm>' | Class method call | Find replacement class in documentation |
SELECT...ENDSELECT | SELECT INTO TABLE + loop | Avoid row-by-row processing |
MOVE-CORRESPONDING src TO dst | dst = CORRESPONDING #( src ) | New ABAP syntax |
READ TABLE itab WITH KEY k = v | line_exists( itab[ k = v ] ) or VALUE #( itab[ k = v ] OPTIONAL ) | Use table expressions |
FORM/PERFORM | Method call | Extract to class method |
DESCRIBE TABLE itab LINES lv_cnt | lv_cnt = lines( itab ) | Built-in function |
CALL METHOD obj->method | obj->method( ) | Functional call syntax |
CREATE OBJECT obj TYPE cls | obj = NEW cls( ) | NEW operator |
TRANSLATE str TO UPPER CASE | str = to_upper( str ) | Built-in function |
| Classic DB view | CDS view entity | Redesign required |
WRITE: / ALV list | Fiori / RAP service | Major redesign |
Step 5: Apply Selected Fixes
5a. Apply fixes
For method-level fixes in classes:
SAPWrite(action="edit_method", type="CLAS", name="<class>", method="<method>", source="<fixed_source>", transport="<transport>")
For full-source updates (programs, functions):
SAPWrite(action="update", type="<type>", name="<object_name>", source="<fixed_source>", transport="<transport>")
5b. Validate after each batch of fixes
SAPRead(type="SYNTAX", objectType="<type>", name="<object_name>")
If syntax errors are introduced: revert by writing back the original source and report the issue.
5c. Activate
SAPActivate(type="<type>", name="<object_name>")
Step 6: Re-validate
Run ATC again to confirm findings are resolved:
SAPDiagnose(action="atc", type="<type>", name="<object_name>", variant="<variant>")
Report results
Present a final summary:
Migration Fix Summary for <object_name>
========================================
Findings fixed: <n>
Findings remaining: <n>
Findings needing manual fix: <n>
Fixed:
- [FIXED] Use of obsolete statement MOVE (3 occurrences)
- [FIXED] SELECT...ENDSELECT replaced with SELECT INTO TABLE
Remaining:
- [MANUAL] CL_GUI_ALV_GRID replacement requires UI redesign
- [SKIPPED] User skipped FORM/PERFORM migration
Next steps:
- Address remaining manual findings
- Run full regression tests
- Consider running ATC on dependent objects
Error Handling
Common Issues and Fixes
| Error | Cause | Fix |
|---|---|---|
| ATC variant not found | Variant doesn't exist on this system (hard error — SAP would otherwise silently run DEFAULT) | List the real names with SAPDiagnose(action="atc_variants"), or omit variant for the system default |
| Object locked by another user | Object is being edited elsewhere | Inform user, suggest trying later or contacting the lock holder |
| Fix causes new syntax error | Generated replacement code is incorrect | Revert to original source, show the diff, suggest manual correction |
| No mcp-sap-docs available | Documentation MCP not configured | Explain findings using ATC finding text only, recommend user check SAP Help Portal |
| Package has too many objects | Large package with 100+ objects | Suggest breaking into smaller batches by sub-package or object type |
| ATC returns no findings | Object is already S/4HANA ready | Inform user — no findings is good news, suggest checking with a stricter variant |
| Transport required but not provided | Object is in a transportable package | Ask user for transport request number before applying fixes |
Notes
BTP vs On-Premise Differences
- BTP: Limited ATC variants — primarily cloud readiness checks. BTP objects already use ABAP Cloud syntax, so migration focus is different: deprecated released APIs, not classic ABAP constructs. Fewer findings expected since ABAP Cloud enforces modern patterns.
- On-Premise: Full range of S/4HANA readiness variants available (2020, 2021, 2022, 2023+). Classic ABAP objects may have many findings. FORM/PERFORM, function modules, classic reports, and DB views are common migration targets. Custom Code Migration Worklist (SCMA) may provide additional context.
Quickfix Availability
- SAP quickfixes are available for many common ATC findings (for example obsolete statements, missing declarations, straightforward syntax issues).
- Not every finding has a quickfix. Deprecated API replacements and architecture-level redesign usually still require manual/LLM-guided refactoring.
What This Skill Does NOT Do
- No transport management: User is responsible for creating and releasing transport requests
- No migration dossier: Handles one object or one package finding workflow — for reviewed, saved, or visual package-level dossiers, use sap-migration-dossier
- No custom ATC variant creation: Uses existing ATC variants on the system
- No table structure migration: Cannot modify DDIC table structures (e.g., field length changes for S/4HANA)
- No test execution: Does not run regression tests after fixes — user should validate manually or use generate-abap-unit-test skill
When to Use This Skill
- When preparing custom code for S/4HANA migration
- When checking if code meets ABAP Cloud readiness standards
- When investigating ATC findings and needing explanation + fix proposals
- When modernizing legacy ABAP code patterns (FORM, obsolete statements)
- NOT for greenfield development — use generate-rap-service for new objects
Migrate SEGW OData V2 service ➜ RAP service
Reverse-engineer a classic SEGW-built OData V2 service (MPC/DPC/MPC_EXT/DPC_EXT) into a modern RAP service (CDS root + projection + BDEF + SRVD + SRVB + behavior pool) on the same SAP system. Runs side-by-side: the legacy service stays live; the new RAP service lands in a separate, resettable package.
Domain example. Templates in this skill use an illustrative
Project → Tasks → TimeEntriesdomain (entity names likeZR_DM_PROJECT,ZBP_DM_PROJECT,ZDM_PROJECT_D) so the shape is concrete. Substitute the user's entities throughout — the LLM running this skill should rewrite every entity identifier to match the source service.
Smart defaults (apply silently — do NOT ask before research)
| Setting | Default | Rationale |
|---|---|---|
| Discovery strategy | MPC class source (Tier 1) | ARC-1 reads it natively; richer than $metadata |
| Target package | User-provided. If absent, create a child of the source package via SAPManage(action="create_package"); default name <source_package>_RAP. Only fall back to $TMP if the user explicitly asks. | Keeps the migration output isolated and resettable. |
| Target transport | User-provided existing, or auto-created via SAPTransport(action="create", description="RAP migration of <legacy_service>", package="<target_package>"). | Required for non-$TMP packages. |
| OData version on target | V4 | Current SAP standard; FE-ready |
| RAP scenario | Managed with internal numbering | Simplest read-mostly; matches legacy SEGW behaviour |
| Draft | Off for read-mostly entities. ON when the legacy service exposed CUD (function imports, deep inserts, or sap:updatable=true on entity sets) and the user wants Fiori Elements compatibility. | Match the legacy service's behavior contract; FE list+OP work best with draft on. |
| Strict mode | strict ( 2 ) | Current best practice |
| Projection layer | Mandatory — always create a ZC_* projection alongside every ZR_* root view. Service binding exposes the projection, never the root. | Run 1 of the skill skipped projections after a misread CDS error; spell out so the LLM never drops them. |
provider contract on projections | On the root projection only, not on the root view, not on child projections. The contract sits at exactly one level. Use transactional_query when combining projection BDEF + use draft on 7.58; transactional_interface for read-mostly without draft. | Putting it on a root view → "only valid on projection views". Putting it on child projections → "inappropriate provider contract on …". Children are exposed via redirected to parent and inherit the BO contract from the root projection. Run 3 confirmed _query is needed for draft on 7.58. |
| CDS composition syntax (managed) | composition [0..*] of <child> as <name> — no on clause. Key linking is implicit via matching key fields / with foreign key in the child | 7.58 rejects on on managed compositions. The recovery is dropping on, not switching to association to. |
@Semantics.* on 7.58 | createdAt, lastChangedAt, and localInstanceLastChangedAt are all valid on 7.58 — put localInstanceLastChangedAt on the local-instance etag field (abp_locinst_lastchange_tstmpl), exactly as SAP's own RAP generator does. @Semantics.businessDate.from/to also work. | Verified live on S/4HANA 2023 (758, 2026-06-12): standalone CDS views with localInstanceLastChangedAt and with businessDate.from/to both activate. An earlier "unknown annotation on 7.58" note was a misdiagnosis — draft annotations are genuinely absent only on pre-7.55 releases. |
| Draft table field names (when draft=ON) | Use BO-alias casing without underscores — e.g. projectid, startdate, NOT project_id, start_date. ABAP normalizes BDEF aliases (ProjectId, StartDate) to PROJECTID, STARTDATE — the draft table lookup is by that normalized name, not by the active table's snake_case. | Run 2: BDEF activation failed with "key field PROJECTID expected at position 2, found PROJECT_ID". The active table can keep snake_case (BDEF mapping handles it); the draft table cannot — it has no mapping clause. |
| Naming | SAP-standard Z<prefix>_<entity>: ZR_ root, ZC_ projection, ZI_<entity>_BEH BDEF, ZBP_ behavior pool, ZUI_<service>_O4 V4 SRVB | Aligns with SAP-internal conventions; the leading Z is the customer namespace |
| Pre-write lint | On | Set SAP_ABAP_RELEASE=<your_release> in ARC-1 config (PR #255) so the lint preset matches the system release. The older SAP_LINT_BEFORE_WRITE=false workaround is no longer needed. |
| Pre-write SAP check | On for activation-blockers only | We rely on activation feedback, not --check-before-write |
Input
The user must provide at minimum:
- One of: a SEGW service technical name (e.g.
Z<SOMETHING>_SRV), a package containing the SEGW-generated classes, or an MPC class name directly. Ask if not given. - Target package for the new RAP objects. Skill will create one (
<source_package>_RAP) if not given and the source package is known; otherwise asks. Only defaults to$TMPif the user explicitly asks. - Transport for non-
$TMPwrites — existing or auto-created (see Smart Defaults).
Optional:
- RAP scenario (default: managed with internal numbering).
- Draft on/off (skill infers from legacy CUD surface).
- OData version (default: V4).
- Naming overrides (default: SAP standard
Z<prefix>_<entity>).
If only the legacy identifier is given, skill applies smart defaults and surfaces the resolved
plan in Phase 5 for user ok before any writes.
Phase 0 — Authorization preflight
Run before any modelling work. Aborts cleanly if anything is missing, with the specific SAP auth object the user needs.
0a. Server-side capability + auth probe
SAPManage(action="probe")
Assert from the response:
systemType∈ {onprem,btp} — needed for naming + admin-field choicesrap.available == true— fail with: "This system doesn't expose RAP/CDS endpoints. Migration cannot proceed."transport.available == true— fail with: "Transport API unavailable; check ICF/sap/bc/adt/cts/transports."authProbe.searchAccess == true— fail with: "User cannot search ADT objects; needS_DEVELOPACTVT=03 OBJTYPE=CLAS DEVCLASS=<source-pkg>."authProbe.transportAccess == true— fail with: "User cannot read transports; needS_TRANSPRTACTVT=03."
0b. Read the legacy MPC class — confirms read on source
SAPRead(type="CLAS", name="<MPC>", method="*")
On HTTP 403: stop with "Cannot read <MPC> — need S_DEVELOP ACTVT=03 OBJTYPE=CLAS
DEVCLASS=<source-pkg> P_GROUP=<auth-group>. Run SU53 in SAP GUI to see the missing field."
0c. Confirm write on target package
SAPTransport(action="check", objectType="DDLS", objectName="ZX_PRECHECK", package="<target_package>")
Then dry-run a write+delete on a throwaway DDLS:
SAPWrite(action="create", type="DDLS", name="ZR_DM_PRECHECK",
source="@AccessControl.authorizationCheck: #NOT_REQUIRED\ndefine root view entity ZR_DM_PRECHECK as select from t000 { client }",
description="ARC-1 preflight",
package="<target_package>",
transport="<transport>")
SAPWrite(action="delete", type="DDLS", name="ZR_DM_PRECHECK")
On 403 from create: stop with "Cannot write to <target_package> — need S_DEVELOP ACTVT=01,02,07
OBJTYPE=DDLS DEVCLASS=<target_package>."
If all three pass, print "Phase 0 ✓ Authorizations OK — proceeding to discovery." and continue.
Phase 1 — Discover the legacy service
1a. Resolve the MPC class name
If user gave a service name (e.g. <legacy_service>):
- Try convention: trim
_SRV→ append_MPC→<MPC_class>. Verify withSAPRead. - If not found:
and ask the user to pick.SAPQuery(action="sql", sql="SELECT obj_name, devclass FROM tadir WHERE pgmid = 'R3TR' AND object = 'CLAS' AND obj_name LIKE 'Z%_MPC' ORDER BY obj_name")
If user gave a package (e.g. <source_package>):
-
Filter for classes endingSAPRead(type="DEVC", name="<package>")_MPC.
If user gave an MPC class directly: use it as-is.
Determine the corresponding _MPC_EXT, _DPC, _DPC_EXT by name convention.
1b. Confirm the four classes exist + record metadata
SAPSearch(action="object", query="<base>_*", maxResults=10)
Expected: 4 hits. Record objectName + packageName for each.
Print to user:
Legacy service: <legacy_service>
Package: <source_package>
MPC class: <MPC_class> (model)
MPC_EXT: <MPC_EXT_class> (model overrides — usually empty)
DPC class: <DPC_class> (data provider — generated)
DPC_EXT: <DPC_EXT_class> (data provider — your custom code)
Phase 2 — Extract the OData model from MPC source
The MPC class's private DEFINE_* methods carry the full model. Read them.
2a. Method inventory
SAPRead(type="CLAS", name="<MPC>", method="*")
You're looking for:
DEFINE_<entity>— one per entity typeDEFINE_ASSOCIATIONS— all associations + nav propertiesDEFINE_ACTIONS— all function imports
2b. Per-entity read
For each DEFINE_<entity> method:
SAPRead(type="CLAS", name="<MPC>", method="DEFINE_<ENTITY>")
Parse the body for:
- Entity type name + entity set name (look for
create_entity_type(...)andcreate_entity_set(...)) - Underlying ABAP DDIC bind (look for
bind_structure(...)orset_data_source(...)) - Each property: name, EDM type, max-length, is-key, sortable/filterable/creatable/updatable
(look for
create_property(...)followed byset_*calls)
2c. Associations
SAPRead(type="CLAS", name="<MPC>", method="DEFINE_ASSOCIATIONS")
Parse for each create_association(...):
- Association name
- Principal entity + cardinality
- Dependent entity + cardinality
- Navigation property name(s)
- Referential constraints (principal property ↔ dependent property)
2d. Function imports
SAPRead(type="CLAS", name="<MPC>", method="DEFINE_ACTIONS")
Parse for each create_action(...):
- Action / function-import name
- HTTP method
- Return type (entity / complex / primitive / void)
- Return cardinality
- Parameters: name, type, length, mode (in/out/inout)
2e. Compile into a structured model
After Phase 2, you should be able to print a complete table like:
=== Extracted OData model ===
Entity types (3):
Project bound to ZDM_PROJECT key: ProjectId 12 properties
Task bound to ZDM_TASK key: TaskId 15 properties (FK ProjectId)
TimeEntry bound to ZDM_TIMEENTRY key: EntryId 15 properties (FKs TaskId, ProjectId)
Entity sets (3): ProjectSet, TaskSet, TimeEntrySet
Associations (2):
Project_Tasks Project [1] ↔ Task [0..n] ref: ProjectId ↔ ProjectId nav on Project: Tasks
Task_TimeEntries Task [1] ↔ TimeEntry [0..n] ref: TaskId ↔ TaskId nav on Task: TimeEntries
Function imports (1):
ApproveProject POST in: ProjectId (Edm.String, len 10) return: Project (Entity, 1)
Print it and ask the user "Does this match what you expected?" before proceeding.
Phase 3 — Extract the behavior from DPC_EXT
3a. Method inventory
SAPRead(type="CLAS", name="<DPC_EXT>", method="*")
Categorize each redefined method:
| Method pattern | Maps to RAP |
|---|---|
<EntitySet>_GET_ENTITYSET | CDS view's read access — usually free in managed scenario |
<EntitySet>_GET_ENTITY | Same — free in managed scenario |
<EntitySet>_CREATE_ENTITY | BDEF create enabled (with optional determination/validation) |
<EntitySet>_UPDATE_ENTITY | BDEF update enabled |
<EntitySet>_DELETE_ENTITY | BDEF delete enabled |
/IWBEP/IF_MGW_APPL_SRV_RUNTIME~EXECUTE_ACTION | BDEF static or instance action(...) per function import |
3b. Per-method body read (only the ones with logic)
For each redefined method, decide:
- Trivial GET (just
SELECT * FROM <table> WHERE <key>+MOVE-CORRESPONDING): drop entirely — RAP managed scenario does this for free. - Filtered GET (additional WHERE clauses, derived fields): translate to CDS view filters or field aliases.
- Function imports: read the body, identify the business effect (status update, calculation, external call), translate to BDEF action with appropriate behavior pool method.
SAPRead(type="CLAS", name="<DPC_EXT>", method="<METHOD_NAME>")
For mostly-trivial methods, this is a 30-line read. For complex business logic, expect 100+ lines and plan to rewrite carefully.
3c. Compile into a behavior summary
=== Extracted behavior ===
Read-only (drop, free in RAP managed):
PROJECTSET_GET_ENTITYSET, PROJECTSET_GET_ENTITY,
TASKSET_GET_ENTITYSET, TASKSET_GET_ENTITY,
TIMEENTRYSET_GET_ENTITYSET, TIMEENTRYSET_GET_ENTITY
Function imports → BDEF actions:
ApproveProject(ProjectId) ➜ static action ApproveProject parameter $self
sets Status='A' + admin fields, returns Project
(legacy did UPDATE + COMMIT WORK + reread; RAP managed
handles persistence — no manual COMMIT needed)
Custom create/update/delete: none (read-only service)
If _CREATE_ENTITY / _UPDATE_ENTITY / _DELETE_ENTITY were present, list them with notes
on what would become BDEF determinations / validations.
Phase 4 — Read underlying tables
For each table identified in Phase 2 (e.g. ZDM_PROJECT, ZDM_TASK, ZDM_TIMEENTRY):
SAPRead(type="TABL", name="<table>")
Record:
- Field list with ABAP types + lengths
- Key fields
- Admin fields convention (classic
ERNAM/ERDAT/ERZET/AENAM/AEDAT/AEZETvs modernabp_*) - Foreign-key references (the
with foreign keyclauses)
The tables stay as-is — the new RAP CDS views read from them.
Phase 5 — Design plan + user approval
Before any write operation, present the complete RAP design as a design plan, get explicit user approval, then proceed.
5a. Naming
Legacy → New RAP
ZDM_PROJECT (table, untouched) ─► ZR_DM_PROJECT (CDS root view entity)
ZC_DM_PROJECT (CDS projection view, exposed via service)
ZI_DM_PROJECT (BDEF for root)
ZDM_TASK (table, untouched) ─► ZR_DM_TASK + ZC_DM_TASK
ZDM_TIMEENTRY (table, untouched) ─► ZR_DM_TIMEENTRY + ZC_DM_TIMEENTRY
(no SEGW project on the new side) ─► ZUI_DM_PROJECTS (service definition — exposes ZC_*)
ZUI_DM_PROJECTS_O4 (service binding, OData V4 UI)
ZBP_DM_PROJECT (behavior pool class for actions)
5b. Composition tree
root: ZR_DM_PROJECT
composition [0..*] of ZR_DM_TASK as _Tasks
composition [0..*] of ZR_DM_TIMEENTRY as _TimeEntries
Maps the SEGW associations 1:1 — except now they're compositions (parent owns children), which gives RAP managed lifecycle semantics for free.
5c. Action
ZI_DM_PROJECT (BDEF):
define behavior for ZR_DM_PROJECT alias Project
persistent table zdm_project
lock master
authorization master ( instance )
etag master last_changed_at
{
field ( readonly ) ProjectId;
action approve_project result [1] $self; ← matches SEGW ApproveProject
}
The approve_project action → handler in ZBP_DM_PROJECT → sets status='A' + admin fields
via the framework's MODIFY ENTITIES interface (no manual UPDATE + COMMIT).
5d. Service binding URL
Old (SEGW V2): /sap/opu/odata/sap/<legacy_service>
New (RAP V4): /sap/opu/odata4/sap/zui_dm_projects_o4/srvd_a2x/sap/zui_dm_projects/0001
(or the FLP-bound URL if the service binding is published as UI.)
5e. Show + ask
Print the full plan to the user. Wait for explicit "yes, proceed" or modifications. If the user wants changes (different naming, draft enabled, different RAP scenario), revise and re-present.
Non-interactive mode. If the user's initial prompt already supplied the Phase-5 equivalent inputs (legacy service, target package, transport, scenario, draft on/off) AND said "run end-to-end" / "don't stop for review", skip the rhetorical "yes, proceed?" gate. Print the plan as a manifest and advance directly to Phase 5f / Phase 6. Only stop if Phase 5 surfaced a genuine conflict (missing input, contradictory scenario flags, etc.). See Run 6 findings — full-chain automations otherwise hit a phantom gate.
5f. Lock the artifact list as a Phase-6 contract
Before leaving Phase 5, the skill MUST emit an artifact-list contract that Phase 6 will echo back with status. Print this verbatim:
=== Phase 6 will create + activate these artifacts (Phase 5 → Phase 6 contract) ===
Roots (CDS): [ ] ZR_DM_PROJECT [ ] ZR_DM_TASK [ ] ZR_DM_TIMEENTRY
Projections (CDS): [ ] ZC_DM_PROJECT [ ] ZC_DM_TASK [ ] ZC_DM_TIMEENTRY
(projections are MANDATORY — service binding never exposes roots directly)
Draft tables (TABL): [ ] ZDM_PROJECT_D [ ] ZDM_TASK_D [ ] ZDM_TIMEENTRY_D
(only when draft is on — based on Phase 5d)
BDEFs: [ ] ZR_DM_PROJECT (root behavior) [ ] ZC_DM_PROJECT (projection behavior)
Behavior pool (CLAS): [ ] ZBP_DM_PROJECT (empty shell — generate_behavior_implementation will populate)
Service definition: [ ] ZUI_DM_PROJECTS (exposes projections, NOT roots)
Service binding: [ ] ZUI_DM_PROJECTS_O4 (OData V4 UI)
Manual steps remaining after Phase 6 build:
[ ] /IWFND/MAINT_SERVICE — register V4 service group ZUI_DM_PROJECTS_O4 (else 403 at runtime)
Phase 6 must walk through this list at the end and print the same checkbox list with each
item marked ✓ or ✗ (with the failing tool call args + response on ✗). Do NOT declare
Phase 6 done until every box is ✓ or explicitly waived by the user.
Phase 6 — Build the RAP stack
6a. Reset existing artifacts (idempotent re-runs)
If <target_package> package contains objects from a previous run, delete them first:
SAPRead(type="DEVC", name="<target_package>")
For each object in reverse dependency order (SRVB → SRVD → BDEF → DDLS_C → DDLS → CLAS → TABL):
SAPWrite(action="delete", type="<type>", name="<name>", transport="<transport>")
(SAP recommends releasing the transport before re-running, but for resettable demos we just
reuse <transport> — it's fine.)
Plus a TADIR cross-check (Run 1 found a stub draft table sitting in a different transport
that the package scan missed; Run 6 found that ADT 404s can coexist with TADIR ghost rows —
the "split-brain" failure mode). On ARC-1 ≥ 0.9.5 (PR #270), the canonical reset truth
comes from source="both" mode, which queries ADT and DB TADIR in one call and emits a
splitBrain warning array for any divergent names:
SAPSearch(searchType="tadir_lookup",
source="both",
names=["ZDM_PROJECT_D","ZDM_TASK_D","ZDM_TIMEENTRY_D",
"ZR_DM_PROJECT","ZR_DM_TASK","ZR_DM_TIMEENTRY",
"ZC_DM_PROJECT","ZC_DM_TASK","ZC_DM_TIMEENTRY",
"ZI_DM_PROJECT_BEH","ZI_DM_TASK_BEH","ZI_DM_TIMEENTRY_BEH",
"ZBP_DM_PROJECT","ZUI_DM_PROJECTS","ZUI_DM_PROJECTS_O4"])
Read the response in this order:
results— names found via ADT discovery (the "is the object actually live" question). Empty = the package is clean from ADT's perspective.splitBrain— names where ADT and DB disagree (the "ghost" cases). For each, the array entry tells you which source saw it. The pragmatic interpretation: if a name is in DB-only (TADIR row, no ADT object), it's a ghost — treat as already absent for the purposes ofSAPWrite create. If it's in ADT-only (rare), there's a stale ADT cache —SAPSearchagain after a few seconds.
source="both" requires sql scope (the DB leg uses the free-SQL path). If your profile
doesn't have it, fall back to source="adt" (default) for the live check + SAPQuery for
a broader package sweep:
SAPQuery(action="sql", sql="SELECT obj_name, object, devclass, korrnum FROM tadir
WHERE devclass = '<target_package>' AND obj_name LIKE 'Z%'")
If a planned name appears in a different package, it's a leftover stub — delete via its actual transport before proceeding.
6a-gen. (Optional) Seed the root BO via SAP's official ABAP generator
If the official SAP ABAP MCP server is connected alongside ARC-1 (ships with ABAP Development
Tools for VS Code; enabled in Eclipse ADT 3.60+; appears as the abap-mcp server), its
Generate ABAP Repository Objects framework can scaffold the root managed+draft BO for you.
It does not replace this skill — Phases 1–5 (discovery + translation) and most of Phase 6 are
still ARC-1's job, because the generator is single-entity and one-shot:
"a maximum of one entity, no compositions or hierarchies" and "not intended for post-generation — subsequent changes require manual developer intervention."
So it fits a SEGW migration only when the legacy service is effectively a single root entity,
managed+draft, whose table carries the modern timestamp fields last_changed : abp_lastchange_tstmpl
and local_last_changed : abp_locinst_lastchange_tstmpl. Most SEGW services are multi-entity with
classic ERDAT/AEDAT admin fields and function imports → the generator does not apply; use the
manual build (6b) as normal. Where it does apply, it only seeds the root; ARC-1 still adds the
children, compositions, actions, and field mappings afterward (the generator can't, being one-shot).
If you use it:
- Probe. No
abap_generators-list_generatorstool (theabap-mcpserver) → skip to 6b, build manually. - Resolve the ID — release-specific, never hardcode. Call
abap_generators-list_generators, match the "OData UI Service" generator by display name, use the returnedid(proven live:uiserviceon SAP_BASIS 758 / S4 2023;ui-serviceon 816 / ABAP Platform 2025; 816 also hasx-ui-service"from scratch"). Not listed → skip to 6b. - Schema → generate.
abap_generators-get_schema(generatorId, packageName="<target_package>", referencedObjectType="TABL", referencedObjectName="<root table, e.g. ZDM_PROJECT>"), fill every required field from the returned schema, thenabap_generators-generate_objects(generatorId, …). This is a mutation — target<target_package>+<transport>, same guardrails as any write. - Hand back to ARC-1. Continue at Step 2 onward in 6b for the children/compositions, the
projection contract level, the action (
approve_project) + handler body, and activation — adapting the names the generator chose for the root. Reconcile its root CDS/BDEF naming with this skill'sZR_*/ZC_*/ZI_*_BEHplan, or accept the generator's names and update Phase 5f's contract.
State which path you took so the run stays auditable. When in doubt, prefer the manual build (6b) — it is the proven path for the multi-entity SEGW shape and never depends on a second MCP server.
6b. Build order — strict, no improvisation
The order below was learned the hard way (Run 1, calls #22–33). Do not reorder. Each step prevents a specific failure mode in the next.
Step 1 — Draft tables (only if Phase 5d.draft = ON)
SAPWrite(action="batch_create", objects=[
{ type: "TABL", name: "ZDM_PROJECT_D", source: "<draft table source — see template below>", package: "<target_package>", transport: "<transport>" },
{ type: "TABL", name: "ZDM_TASK_D", source: "<...>", package: "<target_package>", transport: "<transport>" },
{ type: "TABL", name: "ZDM_TIMEENTRY_D", source: "<...>", package: "<target_package>", transport: "<transport>" }
])
SAPActivate(action="activate", objects=[ {type:"TABL", name:"ZDM_PROJECT_D"}, ... ])
Draft table template — three rules learned in Run 2:
- Field names use BO-alias casing without underscores (
projectid,startdate, notproject_id,start_date). ABAP normalizes BDEF aliases to uppercase no-underscore; draft binding looks up by that name, not by the active table's snake_case. creationtimestampandlastchangedstampcolumns required fortotal etag+etag masterclauses in the BDEF to bind.@AbapCatalog.enhancement.category : #NOT_EXTENSIBLEis mandatory — without it the TABL save fails on 7.58.
@EndUserText.label : 'Demo: Project (draft shadow)'
@AbapCatalog.enhancement.category : #NOT_EXTENSIBLE
@AbapCatalog.tableCategory : #TRANSPARENT
@AbapCatalog.deliveryClass : #A
@AbapCatalog.dataMaintenance : #ALLOWED
define table zdm_project_d {
" Field names match the BO aliases (no underscore) — required by RAP draft binding.
" The active table ZDM_PROJECT can keep its snake_case names; the BDEF mapping bridges
" them. The draft table has no mapping clause, so its names must align with the BO directly.
key client : abap.clnt not null;
key projectid : abap.char(10) not null;
title : abap.char(100);
description : abap.char(255);
status : abap.char(1);
startdate : abap.dats;
enddate : abap.dats;
erdat : abap.dats;
erzet : abap.tims;
ernam : abap.char(12);
aedat : abap.dats;
aezet : abap.tims;
aenam : abap.char(12);
" Required for `total etag CreationTimeStamp` + `etag master LastChangedStamp` in BDEF.
" Computed in CDS root view via dats_tims_to_tstmp(...); persisted on draft instances.
creationtimestamp : abap.dec(15,0);
lastchangedstamp : abap.dec(15,0);
include sych_bdl_draft_admin_inc;
}
ZDM_TASK_D mirrors with taskid + projectid (FK), all task-specific columns aliased
no-underscore. ZDM_TIMEENTRY_D mirrors with entryid + taskid + projectid (FKs).
Step 2 — CDS roots (ZR_DM_*)
Top-down: parent first, then children. Use composition [0..*] of <child> as <name> —
no on clause for managed scenario.
If your legacy DPC_EXT did Aedat → Erdat fallback (run 1 found this), bake it into the root
view's timestamp computation. On 7.58 use @Semantics.systemDateTime.createdAt,
lastChangedAt, and localInstanceLastChangedAt — the last annotates the local-instance
etag field (abp_locinst_lastchange_tstmpl) that a managed-draft BO needs, and is exactly what
SAP's own RAP generator emits on 758. Verified live on S/4HANA 2023: standalone views with
localInstanceLastChangedAt and with @Semantics.businessDate.from/to both activate. Only
genuinely old releases (< 7.55, before draft support) lack these — do NOT strip them on 7.58.
@Semantics.systemDateTime.createdAt : true
dats_tims_to_tstmp(
zdm_project.erdat,
zdm_project.erzet,
abap_system_timezone($session.client, 'NULL'),
$session.client,
'NULL'
) as CreationTimeStamp,
@Semantics.systemDateTime.lastChangedAt : true
dats_tims_to_tstmp(
case zdm_project.aedat when '00000000' then zdm_project.erdat else zdm_project.aedat end,
case zdm_project.aedat when '00000000' then zdm_project.erzet else zdm_project.aezet end,
abap_system_timezone($session.client, 'NULL'),
$session.client,
'NULL'
) as LastChangedStamp
Activation order for composition CDS. The default
batch_createactivates each object inline in array order, so the parentcomposition [0..*] of ZR_DM_TASK as _Tasksactivates beforeZR_DM_TASKexists, hitting "data sourceZR_DM_TASKdoes not exist" (Run 6 reproducer). Three safe paths, pick whichever fits the run:
batch_createwithactivateAtEnd: true(ARC-1 ≥ 0.9.5, PR #270). Writes inactive drafts for every object, then issues one terminalactivateBatchso SAP's activator resolves the cross-references in a single pass. This is the recommended pattern when ARC-1 supports it — single tool call, no recovery dance:SAPWrite(action="batch_create", activateAtEnd: true, objects=[...])- Per-file
SAPWrite(action="create")for each root, then a singleSAPActivate(action="activate", objects=[...])batch at the end (after every DDL source has landed). Works on every ARC-1 release.- Manual bottom-up:
SAPWrite createparent →SAPActivatechild first → activate parent last. More tool calls; rarely needed.The same fix applies to Step 3 projections (composition chain mirrored). Activate the projection trio together at the end, not inline.
Step 3 — CDS projections (ZC_DM_*) — DO NOT SKIP
This is where Run 1 silently dropped the layer. A provider contract error here means
"create projections", NOT "remove the contract".
Critical: provider contract transactional_interface goes on the root projection
ONLY (ZC_DM_PROJECT). Child projections (ZC_DM_TASK, ZC_DM_TIMEENTRY) use bare
as projection on … and inherit the BO contract via redirected to parent. Putting
the contract on children yields "inappropriate provider contract on …" on activation
(Run 2).
Root projection — WITH contract
Pick the contract based on scenario:
- Managed + draft + CUD (this skill's default):
provider contract transactional_query(Run 3 evidence on 7.58: combining projection BDEF +use draftrejectstransactional_interface). - Read-mostly, no draft, no CUD:
provider contract transactional_interface.
@AccessControl.authorizationCheck : #NOT_REQUIRED
@EndUserText.label : 'Demo project — UI projection (root)'
@Metadata.allowExtensions: true
define root view entity ZC_DM_PROJECT
provider contract transactional_query
as projection on ZR_DM_PROJECT
{
key ProjectId,
Title,
Description,
Status,
StartDate,
EndDate,
Erdat, Erzet, Ernam, Aedat, Aezet, Aenam,
CreationTimeStamp,
LastChangedStamp,
_Tasks : redirected to composition child ZC_DM_TASK
}
Child projections — WITHOUT contract, with redirected to parent
@AccessControl.authorizationCheck : #NOT_REQUIRED
@EndUserText.label : 'Demo task — UI projection (child)'
@Metadata.allowExtensions: true
define view entity ZC_DM_TASK
as projection on ZR_DM_TASK
{
key TaskId,
ProjectId,
Title, Description, Status, Priority, DueDate, AssignedTo, EstimatedHours,
Erdat, Erzet, Ernam, Aedat, Aezet, Aenam,
_Project : redirected to parent ZC_DM_PROJECT,
_TimeEntries : redirected to composition child ZC_DM_TIMEENTRY
}
Same shape for ZC_DM_TIMEENTRY (no contract, _Task : redirected to parent ZC_DM_TASK).
Note
define view entity(notdefine root view entity) on children — only the BO root hasdefine root view entity.
Step 4 — Empty behavior pool (skeletons created automatically by Step 7)
Write only the empty global class shell. The local handler classes (lhc_project,
lhc_task, lhc_timeentry) are no longer pre-created here — Step 7's
SAPWrite action=generate_behavior_implementation (PR-C, ARC-1 ≥ post-2026-05-10)
auto-creates them when missing, then injects every required handler signature and stub
in one call. Run 2's mandatory ADT-paste pause for CCDEF/CCIMP is gone.
SAPWrite(action="create", type="CLAS", name="ZBP_DM_PROJECT",
source="CLASS zbp_dm_project DEFINITION
PUBLIC ABSTRACT FINAL
FOR BEHAVIOR OF zr_dm_project.
ENDCLASS.
CLASS zbp_dm_project IMPLEMENTATION.
ENDCLASS.",
description="Behavior pool for ZR_DM_PROJECT BO",
package="<target_package>", transport="<transport>")
SAPActivate(type="CLAS", name="ZBP_DM_PROJECT")
Expected activation behavior. The
SAPActivatehere may return "no behavior definition forzr_dm_project" — that's expected and OK. The BDEF doesn't exist yet; it's created in Step 5. Don't treat this as a real failure. The class will activate cleanly once the BDEF is in place; Step 7 (generate_behavior_implementation) re-activates the class with handlers anyway. Either:
- Skip activation here (write only) and rely on Step 7 to activate.
- Or accept the warning and re-activate the class as part of Step 10's batch activate.
That's it. No CCDEF/CCIMP write here. No ADT pause. Continue to Step 5.
Step 5 — Root BDEF with the managed-with-draft rules baked in
Run 1 calls #22–31 discovered ten managed-with-draft rules the hard way. Bake them in:
managed implementation in class zbp_dm_project unique;
strict ( 2 );
with draft;
define behavior for ZR_DM_PROJECT alias Project
persistent table zdm_project
draft table zdm_project_d
lock master
total etag CreationTimeStamp " <- required by `with draft`
etag master LastChangedStamp
authorization master ( instance )
{
create;
update;
delete;
field ( readonly : update ) ProjectId;
field ( readonly ) CreationTimeStamp, LastChangedStamp;
" composition associations: only `create` is allowed in the inline block
association _Tasks { create; with draft; }
draft action Edit;
draft action Activate optimized;
draft action Discard;
draft action Resume;
draft determine action Prepare; " <- 'determine' keyword required, not just 'draft action'
action approve_project result [1] $self; " <- DO NOT remove on activation failure;
" Step 7 (generate_behavior_implementation)
" auto-creates the lhc_project skeleton and
" injects the handler in one call.
mapping for zdm_project { … all field maps … }
}
define behavior for ZR_DM_TASK alias Task
persistent table zdm_task
draft table zdm_task_d
lock dependent by _Project " <- not _Project of root; use the cross-BO assoc you added in roots
etag dependent by _Project
authorization dependent by _Project
{
update; delete;
field ( readonly : update ) TaskId, ProjectId; " <- lock-by reference fields MUST be readonly
association _Project { with draft; }
association _TimeEntries { create; with draft; }
" NO draft Edit/Activate/Discard/Resume — those belong on the root only.
mapping for zdm_task { … }
}
define behavior for ZR_DM_TIMEENTRY alias TimeEntry
persistent table zdm_timeentry
draft table zdm_timeentry_d
lock dependent by _Project " <- not by _Task — chain must reach a `lock master`
etag dependent by _Project
authorization dependent by _Project
{
update; delete;
field ( readonly : update ) EntryId, TaskId, ProjectId;
association _Project { with draft; }
association _Task { with draft; }
mapping for zdm_timeentry { … }
}
If TimeEntry can only reach _Task and not _Project, you must add a cross-BO
association to ZR_DM_PROJECT as _Project in ZR_DM_TIMEENTRY (root view) — the lock
chain has to terminate at the entity that holds lock master.
Step 6 — Projection BDEF
Declares the behavior alias for the projection. Run 6 found that 7.58 enforces two non-obvious syntax rules in projection BDEFs — bake them in:
use draft;at the top (not inside the body) when the root BDEF declaredwith draft. Without it,use action Edit/Activate/Discard/Resume/Prepareis rejected.- Inside
use association _X { ... }blocks, write bare operation names (create;), notuse create;— theusekeyword belongs at the top level only.
Canonical projection BDEF for the root projection (managed + draft + CUD scenario):
projection;
strict ( 2 );
use draft;
define behavior for ZC_DM_PROJECT alias Project
use etag
{
use create;
use update;
use delete;
use action Edit;
use action Activate;
use action Discard;
use action Resume;
use action Prepare;
use action approve_project;
use association _Tasks { create; } " <- bare 'create;' inside, NOT 'use create;'
}
Child projections (ZC_DM_TASK, ZC_DM_TIMEENTRY) need their own projection BDEF blocks
in the same DDLS or as separate definitions, each using
use association _Project / _Task to expose the upward composition for the lock-master
chain. Bare create; inside association bodies, same rule.
Step 7 — Generate the behavior implementation (one call, fully autonomous)
SAPWrite(action="generate_behavior_implementation", type="CLAS", name="ZBP_DM_PROJECT")
That single call (PR-C, ARC-1 ≥ post-2026-05-10) does:
- Reads class metadata → extracts
<class:rootEntityRef>to auto-discover the bound BDEF (no need to passbdefName). - Cross-validates that MAIN's
FOR BEHAVIOR OF zr_dm_projectand the BDEF'smanaged implementation in class zbp_dm_project uniqueagree. Refuses to mutate on mismatch. - Calls the same scaffold engine
scaffold_rap_handlersuses, withautoApply=true:- Auto-creates missing
lhc_<alias>skeletons (CCDEF + CCIMP). - Injects
METHODS …signatures for every action / determination / validation / authorization the BDEF requires. - Injects empty
METHOD … ENDMETHOD.stubs in CCIMP.
- Auto-creates missing
- Writes CCDEF + CCIMP via the PR #257 include= path under one stateful lock.
- Activates the class.
Returns a structured JSON report including discovery, validation, scaffoldChanged,
counts, and activation.success. If activation fails with the well-known "Local classes
of CL_ABAP_BEHAVIOR_HANDLER…" stale-active coupling, the response includes a guided
activation.hint with concrete recovery options instead of throwing — the just-written
CCDEF/CCIMP source remains useful for both recovery paths.
If activation fails for any non-obvious reason, run SAPDiagnose(action="object_state", type="CLAS", name="ZBP_DM_PROJECT") (PR #254) to see active vs inactive divergence per
include before retrying. It surfaces the exact include that's out of sync without dumping
raw source.
Lower-level alternative: if you need to scaffold against an existing populated class
or want a dry-run-style preview without auto-activating, use scaffold_rap_handlers
directly with autoApply=true|false and bdefName explicit. Prefer
generate_behavior_implementation for fresh behavior pools.
Step 8 — Fill action body via edit_method
SAPWrite(action="edit_method", type="CLAS", name="ZBP_DM_PROJECT",
method="lhc_project~approve_project",
source="
METHOD approve_project.
READ ENTITIES OF zr_dm_project IN LOCAL MODE
ENTITY Project FIELDS ( ProjectId Status Aedat Aezet Aenam )
WITH CORRESPONDING #( keys )
RESULT DATA(projects).
MODIFY ENTITIES OF zr_dm_project IN LOCAL MODE
ENTITY Project
UPDATE FIELDS ( Status Aedat Aezet Aenam )
WITH VALUE #( FOR p IN projects (
%tky = p-%tky
Status = 'A'
Aedat = sy-datum
Aezet = sy-uzeit
Aenam = sy-uname
) ).
READ ENTITIES OF zr_dm_project IN LOCAL MODE
ENTITY Project ALL FIELDS WITH CORRESPONDING #( keys )
RESULT DATA(updated).
result = VALUE #( FOR u IN updated ( %tky = u-%tky %param = u ) ).
ENDMETHOD.",
transport="<transport>")
(No COMMIT WORK — the framework saves automatically on action commit.)
Step 9 — Service definition + binding
SAPWrite(action="batch_create", objects=[
{ type: "SRVD", name: "ZUI_DM_PROJECTS",
source: "@EndUserText.label : 'Demo Project Manager (V4)'\ndefine service ZUI_DM_PROJECTS {\n expose ZC_DM_PROJECT as Project;\n expose ZC_DM_TASK as Task;\n expose ZC_DM_TIMEENTRY as TimeEntry;\n}",
package: "<target_package>", transport: "<transport>" },
{ type: "SRVB", name: "ZUI_DM_PROJECTS_O4",
bindingType: "ODataV4-UI",
serviceDefinition: "ZUI_DM_PROJECTS",
package: "<target_package>", transport: "<transport>" }
])
Note: SRVD exposes
ZC_DM_*(projections), neverZR_DM_*(roots). If you exposed roots, the projection layer is missing — go back to Step 3.
Step 10 — Activate everything
SAPActivate(action="activate", objects=[
{ type: "DDLS", name: "ZR_DM_PROJECT" },
{ type: "DDLS", name: "ZR_DM_TASK" },
{ type: "DDLS", name: "ZR_DM_TIMEENTRY" },
{ type: "DDLS", name: "ZC_DM_PROJECT" },
{ type: "DDLS", name: "ZC_DM_TASK" },
{ type: "DDLS", name: "ZC_DM_TIMEENTRY" },
{ type: "BDEF", name: "ZR_DM_PROJECT" },
{ type: "BDEF", name: "ZC_DM_PROJECT" },
{ type: "CLAS", name: "ZBP_DM_PROJECT" },
{ type: "SRVD", name: "ZUI_DM_PROJECTS" },
{ type: "SRVB", name: "ZUI_DM_PROJECTS_O4" }
])
Step 11 — Publish the V4 service binding
SAPActivate(action="publish_srvb", name="ZUI_DM_PROJECTS_O4")
Step 12 — CONTINGENT manual step: V4 service-group registration
publish_srvb activates the binding at ADT level. On most 7.5x systems there are two
runtime URL shapes that consume the binding, and only one needs Gateway-hub registration:
| Path | Behavior on a fresh publish_srvb (no IWFND step) |
|---|---|
Gateway hub — http://<host>:50000/sap/opu/odata4/sap/<srvb>_o4/srvd_a2x/sap/<srvb_short>/0001/ | Returns 403 with IWBEP/CM_V4_COS/136 — Service 'ZUI_DM_PROJECTS' repository 'SRVD_A2X' is not assigned to group 'ZUI_DM_PROJECTS_O4'. Needs registration. |
SRVD-direct — https://<host>:50001/sap/opu/odata4/sap/<srvb>_o4/srvd/sap/<srvb>/0001/ | Returns 200 without IWFND registration — verified Run 5 + Run 6. Path segment srvd/sap/<srvb> (not srvd_a2x/sap/<srvb_short>). |
Decision:
- Try the SRVD-direct path in Phase 7 first (no manual step). If it works, proceed — Step 12 becomes a no-op.
- Only return here to do the manual step if the SRVD-direct path also fails on the target system, OR if the consumer (FE app, partner) is hardwired to the hub path.
If you do need the manual step, in SAP GUI:
/n/IWFND/MAINT_SERVICE
Add Service → System Alias = LOCAL → Filter "ZUI_DM_PROJECTS*" → Get Services
Select ZUI_DM_PROJECTS_O4 → Add Selected Services → Package <target_package> → Transport <transport>
(Or, on systems with the V4-specific transaction:)
/n/IWFND/V4_ADMIN
→ Service Group "ZUI_DM_PROJECTS_O4" → Assign SRVD_A2X service "ZUI_DM_PROJECTS"
Note: the hub path can return a transient 503 CM_V4_RUNTIME/000 ("Service alias cache
outdated") immediately after publish_srvb, followed by 403 COS/136 on the next call.
Distinct symptoms — the 503 is an alias-cache wedge, the 403 is the missing registration.
Wait a few seconds and re-test before assuming the registration is the cause.
Step 13 — Phase 5 → Phase 6 contract echo
Walk the artifact-list contract from Phase 5f and print every box's status:
=== Phase 6 contract echo ===
Roots (CDS): [✓] ZR_DM_PROJECT [✓] ZR_DM_TASK [✓] ZR_DM_TIMEENTRY
Projections (CDS): [✓] ZC_DM_PROJECT [✓] ZC_DM_TASK [✓] ZC_DM_TIMEENTRY
Draft tables (TABL): [✓] ZDM_PROJECT_D [✓] ZDM_TASK_D [✓] ZDM_TIMEENTRY_D
BDEFs: [✓] ZR_DM_PROJECT (root) [✓] ZC_DM_PROJECT (projection)
Behavior pool (CLAS): [✓] ZBP_DM_PROJECT (with lhc_project, lhc_task, lhc_timeentry skeletons)
[✓] approve_project handler stub injected via scaffold_rap_handlers
[✓] approve_project body filled via edit_method
Service definition: [✓] ZUI_DM_PROJECTS (exposes 3 projections)
Service binding: [✓] ZUI_DM_PROJECTS_O4 (published at ADT level)
Manual steps remaining:
[✗ — waiting on user] /IWFND/MAINT_SERVICE V4 group registration
If any box is ✗ and not waived, do not advance to Phase 7. Either fix or escalate to
the user.
Phase 7 — Side-by-side smoke test
Verify the new V4 service returns the same data as the legacy V2.
7a. Legacy V2 baseline
curl -u "$USER:$PASS" "<base>/sap/opu/odata/sap/<legacy_service>/ProjectSet/\$count"
# expect: 5
curl -u "$USER:$PASS" "<base>/sap/opu/odata/sap/<legacy_service>/ProjectSet('PRJ-0001')/Tasks/\$count"
# expect: 3
7b. New V4 — pick the URL shape that works
Try both in parallel. The SRVD-direct path usually works without the Step 12 manual registration; the Gateway hub path requires it.
# SRVD-direct (HTTPS, port 50001, /srvd/sap/<srvb>/ path) — preferred, no Step 12 needed
NEW_BASE_DIRECT="https://<host>:50001/sap/opu/odata4/sap/zui_dm_projects_o4/srvd/sap/zui_dm_projects_o4/0001"
# Gateway hub (HTTP, port 50000, /srvd_a2x/sap/<srvb_short>/ path) — needs Step 12
NEW_BASE_HUB="<base>/sap/opu/odata4/sap/zui_dm_projects_o4/srvd_a2x/sap/zui_dm_projects/0001"
# Smoke-test the SRVD-direct path first
curl -s -o /dev/null -w "%{http_code}\n" -u "$USER:$PASS" \
"$NEW_BASE_DIRECT/Project?\$top=1&sap-client=001"
# 200 = good; 403 = check Gateway hub registration; 503 = transient alias cache, retry
Pick whichever path returned 200, then use it for the rest of Phase 7. Pin the working URL into RUN-NOTES for the demo.
7c. Draft V4 keying — non-obvious
For a service generated from a managed-with-draft BDEF, the entity keys exposed in
$metadata are composite: every primary key field PLUS IsActiveEntity (Edm.Boolean).
Bare Project('PRJ-0001') returns 400; the correct form is:
NEW_BASE="$NEW_BASE_DIRECT" # or $NEW_BASE_HUB after Step 12
# Counts — same as legacy V2 if the migration is byte-equivalent
curl -u "$USER:$PASS" "$NEW_BASE/Project/\$count?sap-client=001"
# expect: 5
# Composite key — note ProjectId AND IsActiveEntity, not just ProjectId
curl -u "$USER:$PASS" \
"$NEW_BASE/Project(ProjectId='PRJ-0001',IsActiveEntity=true)/_Tasks/\$count?sap-client=001"
# expect: 3
Filter the active row set explicitly via ?$filter=IsActiveEntity eq true if you want
parity with legacy V2's no-draft semantics.
7d. Action invocation — CSRF + If-Match required
V4 bound actions on draft entities need both X-CSRF-Token (with session cookies) and
If-Match: <etag>. Missing If-Match returns 428 CX_OD_PRECOND_REQUIRED.
# 1. Fetch CSRF token + session cookies
curl -s -u "$USER:$PASS" -c /tmp/cookies.txt \
-H "X-CSRF-Token: Fetch" \
"$NEW_BASE/?sap-client=001" -D - -o /dev/null | grep -i 'x-csrf-token'
# 2. Get the current etag for the target row
ETAG=$(curl -s -u "$USER:$PASS" -b /tmp/cookies.txt \
"$NEW_BASE/Project(ProjectId='PRJ-0003',IsActiveEntity=true)?sap-client=001" \
-D - -o /dev/null | grep -i 'etag' | awk '{print $2}' | tr -d '\r')
# 3. POST the action with both headers
curl -u "$USER:$PASS" -b /tmp/cookies.txt -X POST \
"$NEW_BASE/Project(ProjectId='PRJ-0003',IsActiveEntity=true)/com.sap.gateway.srvd.zui_dm_projects.v0001.approve_project?sap-client=001" \
-H "Content-Type: application/json" \
-H "X-CSRF-Token: <from step 1>" \
-H "If-Match: $ETAG" \
-d '{}'
# expect: 200 + entity with Status="A"
If counts don't match, the CDS where-clauses are likely wrong — re-read the legacy DPC_EXT
methods for filters you missed. If actions fail with 412/428 even with both headers, the
service likely needs a fresh publish_srvb to pick up newer BDEF action declarations.
Reset / re-run
Re-run this skill — Phase 6a deletes everything in <target_package> first, so multiple runs
are safe. Transport <transport> stays in D (modifiable) state until you explicitly release
it. To clear the transport too:
SAPTransport(action="release_recursive", number="<transport>")
SAPTransport(action="create", description="ARC-1 RAP migration outputs (resettable)", transportType="K")
…then update the transport ID in this skill's smart defaults.
Error handling
| Symptom | Likely cause | Fix |
|---|---|---|
Phase 0 — rap.available=false | System release < 7.54 OR ABAP-Cloud-mode disabled | Migration cannot proceed; tell user |
| Phase 0 — preflight DDLS create returns 403 | S_DEVELOP ACTVT=01,02 missing for DDLS in target package | User runs SU53 in SAP GUI; basis admin grants role |
| Phase 1 — MPC class not found by convention | Service uses non-standard naming or is in a sub-package | Fall back to TADIR query (1a alt path) |
Phase 2 — DEFINE_<entity> body uses helper methods you can't parse | SEGW uses define_<entity>_property_<n>(...) calls | Read those helper methods too — SAPRead method="DEFINE_PROJECT_PROPERTY_1" |
Phase 3 — EXECUTE_ACTION body has multiple IF iv_action_name = 'X' branches | One DPC_EXT, multiple function imports | Translate each branch to a separate BDEF action |
| Phase 6 — activation fails with "released-API contract violation" | Legacy DPC_EXT used unreleased ABAP API; CDS where-clause inherits the same | Replace with released equivalent (use mcp__sap-docs__search to look up modern API) |
Phase 6 — scaffold_rap_handlers returns 0 missing methods | Activation order inverted | Activate BDEF before scaffolding the behavior pool — scaffold_rap_handlers reads activated BDEF |
Phase 7 — V4 Project/$count differs from V2 ProjectSet/$count | CDS view has implicit filter (e.g. WHERE delivered_status <> 'X') you forgot | Re-read DEFINE_PROJECT for any set_filter_* calls in MPC |
Phase 7 — V4 _Tasks returns empty | Composition wrong direction or missing referential constraint | Inspect ZR_DM_PROJECT source; the composition of clause must reference the child by FK |
Phase 7 — V4 endpoint returns 403 with IWBEP/CM_V4_COS/136 … not assigned to group | Skipped Phase 6 Step 12 (V4 routing-group registration) | User runs /n/IWFND/MAINT_SERVICE Add Service for ZUI_DM_PROJECTS_O4 |
Phase 6 Step 5 — BDEF activation rejects association _X { update; delete; } | Only create is allowed in association inline block | Remove update/delete from association blocks; the child entity's own behavior block declares them |
Phase 6 Step 5 — BDEF rejects draft action Prepare | Must be draft determine action Prepare (the determine keyword is mandatory) | Fix to draft determine action Prepare |
Phase 6 Step 5 — BDEF rejects child entity Edit/Activate/Discard/Resume declarations | Draft lifecycle actions belong on the root only (the entity with lock master) | Move them to root; children only need composition associations + update;/delete; |
Phase 6 Step 5 — BDEF rejects with draft without total etag | RAP requires a total etag field when draft is on | Add total etag CreationTimeStamp (or your timestamp field) to the root behavior |
Phase 6 Step 5 — BDEF rejects child lock dependent by _Task if _Task itself has no lock master | Lock chain must terminate at a lock master entity | Add cross-BO association to ZR_DM_<root> as _Project in the grandchild root view, and use lock dependent by _Project in the BDEF |
Phase 6 Step 5 — BDEF rejects child entity ProjectId updates when used in lock dependent by _Project | Lock-by reference fields must be readonly | Add field ( readonly : update ) <field> to the child behavior block |
Phase 6 Step 5 — BDEF rejects strict ( 2 ) without authorization on every entity | strict ( 2 ) enforces explicit auth declarations | Add authorization master ( instance ) on root, authorization dependent by _Project on children. Step 7 (generate_behavior_implementation) auto-creates the matching lhc_<alias> skeletons and injects the get_instance_authorizations stub — no manual pre-create required. Do NOT drop strict ( 2 ) as the workaround. |
Phase 6 Step 7 — generate_behavior_implementation returns activation: { success: false, hint: <stale-active recovery> } | The well-known stale-active CCDEF/CCIMP coupling: active includes are SAP placeholder comments while inactive includes now contain real handlers, and RAP refuses the inactive→active transition. | Two recovery options in the hint: (a) activate the class once via Eclipse "Generate Behavior Implementation" wizard (it bypasses the coupling), or (b) SAPManage(action="delete", type="CLAS") + SAPWrite(action="create") + rerun generate_behavior_implementation against the freshly created class. The just-written CCDEF/CCIMP source is correct in either path. |
Phase 6 — CDS rejects composition [0..*] of <child> as <name> on … | Managed compositions don't take an on clause; key linking is implicit / via with foreign key in the child | Remove the on clause; do NOT switch to association to |
Phase 6 — CDS rejects provider contract transactional_interface on root view | The contract is only valid on projection views (ZC_DM_*) | This error means you're missing the projection layer — create the ZC_DM_* projection (Step 3) and put the contract there |
Phase 6 — CDS rejects tstmp_from_dat_tim(...) | Function name wrong | Use dats_tims_to_tstmp(...) (note the order: dats first, tims second) |
Phase 6 — Batch activate emits ED 064 — "no next/previous object found" warning | Benign batch-activate quirk in 7.58 | Ignore the warning; if all objects show active, batch succeeded. If a real error mixed in, retry with single-object activate. |
Phase 6a — SAPWrite create returns "object exists" but Phase 6a reset showed empty package | Object exists in a different transport, not the target package | Query TADIR for the name across all packages: SAPQuery sql="SELECT * FROM tadir WHERE obj_name = '<name>'". If found, delete it first using its actual transport, then retry create. |
Phase 6 Step 2/3 — CDS genuinely rejects @Semantics.systemDateTime.localInstanceLastChangedAt or @Semantics.businessDate.* as "unknown annotation" | The system is pre-7.55 (before draft support). On 7.58 these are valid — verified live on S/4HANA 2023; SAP's own generator emits localInstanceLastChangedAt on 758 | On 7.58 keep them. Only on a genuinely older release (< 7.55) fall back to createdAt/lastChangedAt and omit the local-instance / businessDate annotations. |
Phase 6 Step 3 — CDS rejects "inappropriate provider contract on ZC_DM_<child>" | provider contract transactional_interface was put on a child projection | Remove the contract from ZC_DM_TASK / ZC_DM_TIMEENTRY. The contract goes only on the root projection (ZC_DM_PROJECT). Children declare bare as projection on … and use redirected to parent for upward navigation. |
Phase 6 Step 5 — BDEF activation rejects with "key field PROJECTID expected at position 2, found PROJECT_ID" (or similar field-name mismatch on a draft table) | Draft table was written with snake_case field names (project_id, start_date) instead of the BO-alias-normalized names (projectid, startdate) | Rewrite the draft TABL with field names matching the BO aliases: drop underscores. Active table can keep snake_case (BDEF mapping bridges); draft table cannot. Use update + activate via SAPWrite — Run 2 confirmed this works. |
Phase 6a — SAPQuery returns HTTP 400 on a long WHERE obj_name IN ('a','b','c',…) filter | ARC-1 ≥ 0.10.0 auto-chunks simple long IN (…) literal lists (PR #254). Older builds and complex filters (NOT IN, multi-SELECT, subqueries) still hit 400. | Prefer SAPSearch(searchType="tadir_lookup", source="both", names=[...]) for cross-package existence checks (PR #256 + PR #270) — no SQL needed; the splitBrain warning array surfaces ADT/DB divergence in one call. As broader-sweep fallback, SAPQuery with devclass = '<package>'. |
Notes
- This skill never touches the legacy source package, the legacy SEGW project, or its transport. The migration runs side-by-side; legacy stays live until the user explicitly retires it.
- Use
mcp__sap-docs__searchwhenever the legacy DPC_EXT body contains an unfamiliar API call — it'll tell you the released-cloud equivalent. - Use
mcp__sap-docs__abap_feature_matrixto check which RAP features are available on the user's release (e.g.etag master,unmanaged save,lock master). generate-rap-service-researched.mdis the canonical creator. This skill's job is the discovery + translation; delegating the actual create+activate to the deeper skill keeps this one focused.
Modernize UI5 freestyle JS app ➜ UI5 TypeScript app
Convert a legacy UI5 freestyle JavaScript app (typical 2018–2021 era — sync bootstrap, JS
controllers, jQuery.sap.*, global formatter, ES5 patterns, no types, sap_belize) into a
modern UI5 TypeScript app on a recent 1.x release with async loading, manifest-driven
configuration, a proper BaseController, sap_horizon theme, ES modules, typed event handlers,
and clean ui5-linter + tsc --noEmit output. Runs side-by-side: the legacy app stays
untouched at <source_app>/; the modern app lands in <modern_app>/.
This skill is one of two parallel UI paths after the RAP backend lands. Pick this one if
the target architecture is a freestyle TypeScript app (custom controllers, manual binding,
explicit i18n). Pick convert-ui5-to-fiori-elements.md instead if the target is a
Fiori Elements V4 app (annotation-driven; minimal custom code). Both start from the same
legacy JS app + the same V4 RAP service produced by migrate-segw-to-rap.
migrate-segw-to-rap.md (backend: SEGW V2 → RAP V4)
│
┌─────────────┴─────────────┐
▼ ▼
modernize-ui5-app.md convert-ui5-to-fiori-elements.md
(freestyle TS) (Fiori Elements V4)
Path/namespace placeholders.
<source_app>/,<modern_app>/,<source_namespace>,<modern_namespace>are user-provided. Defaults: source islegacy-*-app/(sibling of the target); modern app namespace is derived from source by appending.modern.
Which MCPs this skill uses (and which it doesn't)
| MCP | Used for | When |
|---|---|---|
UI5 MCP (mcp__SAPUI5_MCP_Server__*) | Authoritative TS conversion guidelines, general UI5 guidelines, app scaffolding, API reference lookups, linter, manifest validator, version info | Throughout — this is the primary MCP for this skill |
sap-docs MCP (mcp__sap-docs__*) | OData V4 binding patterns, draft handling, control documentation | When V2→V4 binding behaviour is non-obvious (e.g. composite key on draft, $expand=_Tasks, action invocation) |
| arc-1 MCP | OPTIONAL — service binding URL lookup, status-code semantics | Only if the V4 URL isn't readily available (e.g. you can't read the FE app's manifest); skip otherwise |
| fiori-mcp | NOT USED | This is a freestyle TS app, not Fiori Elements — no annotations to generate |
There is no "convert to TS" tool in the UI5 MCP. Conversion is mechanical and driven by
mcp__SAPUI5_MCP_Server__get_typescript_conversion_guidelines, which returns the authoritative
playbook. You call it once at the start and follow it verbatim.
Also use mcp__sap-docs__search during the run whenever a UI5 best-practice is non-obvious
or contested (FCL routing, V4 binding semantics, draft handling, accessibility, theming). The
SAP help portal indexed there is authoritative and version-specific — quote it rather than
guessing.
Critical traps — read these BEFORE writing any code
Past runs of this skill tripped on three issues that took multiple iterations to diagnose. They are easy to avoid if you know about them up front; brutal if you don't. Even a strong LLM lost ~15-20 minutes debugging "blank page, no console error" because of Traps 1 + 2.
Trap 1: FCL stays at "OneColumn" — only one column visible
Symptom: Both views are routed correctly, console is clean, accessibility tree shows content for both columns — but visually only the left column renders.
Root cause: sap.f.routing.Router only changes the FCL layout property when the matched
route explicitly declares one. A route with no layout leaves FCL at its initial value
(OneColumn), so the mid / end columns stay hidden even though the router placed targets in
them.
Fix: Every FCL route MUST have a layout property. Not just detail/drill-down — also
the home / main / not-found route, every route that targets anything other than the
beginColumnPages aggregation alone.
"routes": [
{
"pattern": "",
"name": "main",
"target": ["main", "welcome"],
"layout": "TwoColumnsMidExpanded" // ← REQUIRED — Welcome lives in mid column
},
{
"pattern": "Project/{projectId}",
"name": "detail",
"target": ["main", "detail"],
"layout": "TwoColumnsMidExpanded" // ← REQUIRED
}
]
Trap 2: Blank page — DOM populated but every element has height: 0
Symptom: Console is clean, accessibility tree shows all content, but visually the page is
blank. DevTools confirms every nested element has height: 0 cascading from the body's
component div.
Root cause: UI5's ComponentSupport module strips the data-sap-ui-component attribute
from the body's container div during processing. CSS selectors that match against that
attribute (body > div[data-sap-ui-component] { height: 100% }) stop matching after
ComponentSupport runs, so the wrapper div has no height and data-height="100%" resolves to
100% of 0.
Fix: Put style="height: 100%" inline on the component div in index.html. CSS
selectors keyed on data-sap-ui-component are not reliable here.
<body class="sapUiBody" id="content">
<div
data-sap-ui-component
data-name="<source_namespace>.modern"
data-id="container"
data-height="100%"
style="height: 100%"></div> <!-- ← REQUIRED inline, not in <style> -->
</body>
Trap 3: import Event from "sap/ui/base/Event" is a code smell
Symptom: Strange casts like (event.getParameters() as { listItem?: ListItemBase }).listItem
appear in the controller. TypeScript can't see event parameters; you compensate with as casts
on getParameter or getParameters return values.
Root cause: Importing the generic Event type from sap/ui/base/Event forfeits the strong
typing UI5 ≥ 1.115 provides. UI5 generates <Control>$<Event>Event and
<Control>$<Event>EventParameters types for every control event — those are what to import.
Fix: If you find yourself writing import Event from "sap/ui/base/Event", stop and find
the right specific type. Common ones for this skill's surface:
| Event source | Specific type | Module |
|---|---|---|
sap.m.List / sap.m.Table selectionChange | ListBase$SelectionChangeEvent | sap/m/ListBase |
sap.m.List / sap.m.Table itemPress | ListBase$ItemPressEvent | sap/m/ListBase |
sap.m.List / sap.m.Table updateFinished | ListBase$UpdateFinishedEvent | sap/m/ListBase |
sap.m.List / sap.m.Table delete | ListBase$DeleteEvent | sap/m/ListBase |
sap.m.ListItemBase press | ListItemBase$PressEvent | sap/m/ListItemBase |
sap.m.SearchField liveChange | SearchField$LiveChangeEvent | sap/m/SearchField |
sap.m.Button press | Button$PressEvent | sap/m/Button |
sap.ui.core.routing.Route patternMatched | Route$PatternMatchedEvent | sap/ui/core/routing/Route |
Important — ListBase inheritance:
sap.m.Listandsap.m.Tableinherit their selection / item-press / update / delete / swipe events fromsap.m.ListBase. The TS event types live onsap/m/ListBase, not onsap/m/Listorsap/m/Table. Confirmed in the SAP Help portal: "Both sap.m.List and sap.m.Table offer the same events, inheriting them from sap.m.ListBase." Don't go looking forTable$SelectionChangeEvent— it doesn't exist; useListBase$SelectionChangeEventfromsap/m/ListBaseand TypeScript accepts it for both controls'selectionChangeevents without casts.
If you can't find a specific event type for a UI5 ≥ 1.115 control, call
mcp__SAPUI5_MCP_Server__get_api_reference(query="sap.m.<Control>#<eventName>") to confirm
the typed name exists. Do not fall back to the generic Event.
Trap 4: onApprove(event: Button$PressEvent) — declare with no parameter
Symptom: ESLint flags _event (or event) as no-unused-vars. You drop the parameter,
then ESLint flags the now-orphaned import { Button$PressEvent } as no-unused-imports. Two
edits, two re-lint cycles, one minute lost.
Root cause: UI5 button-press handlers typically don't use the event payload — oCtx,
projectId, etc. all come from this.getView() or from class fields populated by route
matching. Declaring event: Button$PressEvent is a knee-jerk reflex from the typed-events
rule that doesn't apply here.
Fix: declare press handlers with no parameters when you don't read the event:
// CORRECT:
public async onApprove(): Promise<void> {
const projectId = this.projectId;
// ...
}
// WRONG — generates two lint errors that need two edits to fix:
public async onApprove(_event: Button$PressEvent): Promise<void> {
void _event; // dead code
const projectId = this.projectId;
}
The same applies to onNavBack, onItemPress (when you derive the source from this.byId
not the event), and any other handler where the event payload is unused.
Trap 5: Manifest v2 + missing "type": "View" — routes match but nothing renders
Symptom: Page is blank. FCL columns exist with the right widths but each NavContainer is empty. Console is otherwise clean except for one easily-missed warning a millisecond after each route match:
page stack is empty but should have been initialized -
application failed to provide a page to display
Routing logs show the route matches correctly ("The route named 'main' did match"), but no
view ever gets placed in any column.
Root cause: With "_version": "2.0.0" or higher (introduced in UI5 1.136 — the same
version we're targeting in this skill), the older routing keys viewName, viewPath,
viewLevel are removed and replaced by name, path, level — and a routing target
no longer has an implicit "type": "View" default. Without an explicit type, target
resolution silently produces nothing.
Source: SAP Help, "Migration Information for Upgrading the Manifest File", the 2.0.0
(1.136) "Deprecated Manifest Entries" row: "The routing properties ViewId, viewName,
viewPath and viewLevel can no longer be used. Please use the documented alternatives by
replacing them with the properties id, name, path and level, respectively along with adding
the type: "view"."
Fix: in the routing block of manifest.json:
- Add
"type": "View"torouting.config(so it's the default for all targets in the block — saves repeating it). - Use
path(NOTviewPath) for the view-folder namespace. - Use
name(NOTviewName) on each target — and add"type": "View"per target too (belt + braces; some UI5 versions don't propagate the config default reliably). - Use
level(NOTviewLevel) on each target.
"routing": {
"config": {
"routerClass": "sap.f.routing.Router",
"type": "View", // ← REQUIRED in manifest v2
"viewType": "XML",
"path": "<ns>.view", // ← NOT "viewPath"
"async": true,
"controlId": "flexibleColumnLayout",
"controlAggregation": "beginColumnPages",
"bypassed": { "target": "notFound" }
},
"routes": [ /* ... layout property per Trap 1 ... */ ],
"targets": {
"main": {
"type": "View", // ← REQUIRED per target
"id": "main",
"name": "Main", // ← NOT "viewName"
"level": 1, // ← NOT "viewLevel"
"controlAggregation": "beginColumnPages"
},
// ... other targets
}
}
This shape works in both manifest v1.x and v2.x — adding type: "View" is backwards-compatible
(it became available in 1.14.0 / UI5 1.62). The new key names (name/path/level) are also
backwards-compatible. So always emit the v2 shape, even if you're not sure whether the
project ends up on v1 or v2 — there's no downside.
Quick diagnostic when you see this: open the browser console, search for "page stack is
empty". If you find it: you have Trap 5. If you don't, you're probably looking at Trap 1
(missing layout) or Trap 2 (height cascade).
Why the validators DON'T catch this (verified empirically against @ui5/linter@1.19.0
and @ui5/manifest@1.86.0, the same versions wrapped by the UI5 MCP):
| Tool | Catches Trap 5? | Why |
|---|---|---|
run_ui5_linter (@ui5/linter) | No | The no-removed-manifest-property rule exists but only checks resources/js, rootView/async, routing/config/async. Does NOT check routing targets for viewName/viewPath/viewLevel. The linter source reads target.name ?? target.viewName — it gracefully accepts either, without warning. |
run_manifest_validation (@ui5/manifest schema + Ajv) | No | The schema marks viewName/viewPath/viewLevel as "deprecated": true with a description pointing to the v2 replacement, but Ajv with the MCP's strict: false config ignores the deprecated flag. The schema also has both legacyTargetAddition AND actualTargetAdditionStandard as alternatives side-by-side (no _version-conditional if/then branch), so a manifest with viewName validates as isValid: true. |
npm run ts-typecheck | No | Manifest is JSON — TypeScript doesn't see it. |
eslint webapp | No | ESLint doesn't model UI5 manifest semantics. |
| Browser runtime | Indirectly | The "page stack is empty but should have been initialized" console warning is the ONLY automated signal, and it only fires at runtime, not at lint time. |
Implication for the skill: the Phase 7 acceptance gates (linter / manifest validation / ts-typecheck) WILL all report green for a v2 manifest with the deprecated routing keys. The ONLY honest gate for this trap is the Phase 8d browser-render verification — that's why Phase 8d is mandatory, not optional. Don't believe a "clean lint + clean validation" report means the routing config is correct.
If you have the cycles to file an upstream issue, this is a clear gap in @ui5/linter's
no-removed-manifest-property rule — adding routing.targets[].viewName/viewPath/viewLevel
to the checked-property list would close it.
Self-help: when the skill doesn't have the answer
The skill captures common patterns, but every project has its own quirks. When you hit something the skill doesn't cover, investigate before guessing. UI5 has a fragmented middleware ecosystem and a deep type system; an educated guess often gets the wrong key name or the wrong inheritance branch. The investigations below cost 30 seconds and save iterations.
Pattern A — Middleware / proxy / build-tool config option
Trigger: you're setting a config key on a UI5 middleware (ui5-middleware-simpleproxy,
ui5-middleware-livereload, fiori-tools-proxy, ui5-tooling-transpile, anything in
ui5.yaml's customMiddleware or customTasks).
Why investigate: UI5 middlewares silently ignore unknown configuration keys — no error, no
warning, but they do the wrong thing. The naming conventions differ across packages: TLS-skip
is strictSSL: false in ui5-middleware-simpleproxy, ignoreCertErrors: true in
fiori-tools-proxy, and other names elsewhere. Don't extrapolate from one to another.
Recipe:
Bash: cat <target>/node_modules/<package-name>/README.md
# or:
WebFetch: https://www.npmjs.com/package/<package-name>
WebFetch: https://github.com/<owner>/<package-name>
If the README isn't local yet (pre-npm install), use WebFetch or gh api against the GitHub
mirror.
Pattern B — UI5 control event TypeScript type
Trigger: you're typing an event handler parameter and you're not sure what the specific
<Control>$<Event>Event type is called or where it lives.
Why investigate: events are inherited — they're defined on a parent class and reused by
subclasses. Looking for Table$SelectionChangeEvent returns nothing because selectionChange
is defined on ListBase, not Table. The Trap 3 table covers the events this skill commonly
hits; for anything else, ask the UI5 MCP.
Recipe:
mcp__SAPUI5_MCP_Server__get_api_reference(
projectDir="<absolute target>",
query="sap.m.<Control>#<eventName>"
)
Read the result for: (a) which class actually defines the event (= which module to import
from), (b) the canonical event type name. If query returns nothing, search broader
(query="sap.m.<Control>") and inspect the event list; the type name is <DefiningClass>$<EventName>Event.
Pattern C — OData V4 binding / draft / action semantic
Trigger: you're writing V4-specific code (composite keys, $expand=_X navigation, action
invocation, draft handling, batched updates) and you're not sure of the canonical pattern.
Why investigate: V4 differs from V2 in non-obvious ways, and the difference is
version-specific. Guessing usually costs a tsc cycle or a runtime "no metadata" error.
Recipe:
mcp__sap-docs__search(
query="<feature> OData V4 model UI5",
sources=["sapui5","sap-help"],
includeOnline=true
)
mcp__sap-docs__fetch(id="<best result id>")
Useful starting topics (search these terms verbatim):
- "Draft Handling with the OData V4 Model"
- "Operations" (V4 actions/functions)
- "Auto-
$expand/$select" - "Reducing the Number of Requests Required to Get the Properties of a Single Entity"
- "Reducing Roundtrips"
- "Filtering" + "Sorting"
Pattern D — FCL routing behaviour surprise
Trigger: FCL renders the wrong column count, columns flicker, deep-link doesn't restore layout, "Close" button absent.
Why investigate: sap.f.routing.Router is layout-driven. Almost every FCL surprise is a
missing or wrong layout value on the route — not a view-XML bug.
Recipe: open manifest.json, audit every entry under routing.routes[] for a layout
property. The home/main route needs one too (Trap 1). If you're not sure which LayoutType
enum value to use, search:
mcp__sap-docs__search(query="sap.f.LayoutType FCL three-column")
Pattern E — Page renders blank but DOM is populated
Trigger: accessibility tree shows content, console is clean, viewport is empty.
Why investigate: height cascading. Some ancestor element resolves to height: 0 and
collapses every descendant. The trap is usually a data- attribute selector that doesn't
match because ComponentSupport stripped it (Trap 2), but other height-cascade variants exist
(e.g. <body> without height: 100%, a Page with implicit container width but no height).
Recipe: in browser DevTools, click the body, walk the descendant tree in the Elements
panel, watch the computed height. The first element with 0 is where the chain breaks.
Apply style="height: 100%" inline (preferred) or a CSS selector keyed on a non-stripped
attribute (id, class — never data-sap-ui-*).
Pattern F — TypeScript compiles but ui5-linter fails
Trigger: npm run ts-typecheck is clean, but ui5lint flags issues — and tsc won't help
diagnose them.
Why investigate: ts-typecheck checks types; ui5-linter checks UI5-runtime concerns
(deprecated APIs, framework conventions, manifest cross-references, XML view binding
correctness). They're orthogonal. The right order is eslint --fix first (cleans mechanical
TS-level noise), then ui5-linter (catches the UI5-specific issues), then tsc (any
remaining type errors).
If ui5-linter complains about a finding you don't understand, request context:
mcp__SAPUI5_MCP_Server__run_ui5_linter(
projectDir="<absolute target>",
filePatterns=["<the file>"],
provideContextInformation=true
)
The provideContextInformation: true flag returns API-reference excerpts and documentation
links explaining each finding.
Pattern G — UI5 best-practice you're not sure about
Trigger: "should I use Form or SimpleForm?", "should this be a JSONModel or a path?",
"is core:require the right way to load this formatter?", "should the manifest declare a
specific theme?"
Why investigate: SAPUI5 has version-specific guidelines. The MCP returns the authoritative list for the project's version.
Recipe — start with the two pinned guideline tools:
mcp__SAPUI5_MCP_Server__get_guidelines # general UI5 dev rules
mcp__SAPUI5_MCP_Server__get_typescript_conversion_guidelines # TS-specific rules
If the answer isn't in those, escalate to sap-docs:
mcp__sap-docs__search(query="<your question>")
Pattern H — You've debugged the same problem twice this run
Trigger: you've written code, hit an error, fixed it, and the same shape of error recurred on a different file or step. That's a signal the skill is missing a generally-applicable pattern.
Action: capture it as a Run-Notes entry with: symptom, root cause, fix, and a one-line "generic rule" extracted. After the run, propose adding it to the Critical Traps section if it's likely to recur in future projects.
Naming overrides for this project (deviation from older SAPUI5 JS conventions)
These two conventions override the older SAPUI5 JS Coding Guidelines. Apply silently — do not preserve the legacy style during conversion.
| Convention | Older SAPUI5 JS Guidelines | This skill's rule |
|---|---|---|
| Variable prefixes | Hungarian recommended (oModel, sQuery, iTotal, aFilters, mArgs, fHours, bFlag) | No Hungarian notation. Use plain names: model, query, total, filters, args, hours, flag. TypeScript types make the prefix redundant. |
| "Main" entity name | "master" (e.g. Master.view.xml, i18n key masterTitle) | "main" everywhere — controller / view / route / target / file / i18n keys. Aligns with SAP's own Inclusive Language guide ("master branch → main branch"). |
Rename map for the typical SEGW-to-RAP demo surface:
| Legacy | Modern |
|---|---|
Master.controller.js | Main.controller.ts |
Master.view.xml | Main.view.xml |
controllerName="...controller.Master" | controllerName="...modern.controller.Main" |
route "name": "master" | route "name": "main" |
target "master" | target "main" |
i18n key masterTitle | mainTitle |
i18n key masterSearchPlaceholder | mainSearchPlaceholder |
i18n key masterCount | mainCount |
var oModel = ... | const model = ... |
var sQuery = ... | const query = ... |
var iTotal = ... | const total = ... |
var aFilters = ... | const filters = ... |
var oCtx = ... | const ctx = ... (or const context = ... if clearer) |
var oList = ... | const list = ... |
var oRouter = ... | const router = ... |
var oEvent = ... (parameter) | event |
var that = this; | drop entirely; use arrow function |
Exception: keep a prefix only when dropping it would collide with a reserved word, a
same-named import, or a UI5 control name (e.g. local const event = ... collides with no
common UI5 import, so it's fine; but const Date = ... would shadow the global, so call it
oDate or rename it workDate).
Include a "Naming overrides:" line in the Phase 2 plan output so the user can confirm them for this run.
Atomic-rename tip: the master → main rename touches at minimum 7 locations: file name, view
controllerName attribute, manifest route name, manifest target name + key + viewName, i18n
keys × 2 locale files, BaseController.onNavBack fallback, every navTo("master", ...) call
in any controller. To avoid re-edits, grep up-front to enumerate all hits, then edit in
one batch:
Bash: grep -rn -E "master|Master" <target>/webapp
Review the output, decide which hits are renames (not, e.g., the word "master" inside a sentence in the legacy German comments — those should be dropped anyway). Edit all in one pass, then verify with a second grep that returns empty.
Smart defaults (apply silently — do NOT ask before research)
| Setting | Default | Rationale |
|---|---|---|
| Source app | <source_app>/ | The freestyle JS app under the workspace |
| Target app | <modern_app>/ | Empty folder reserved for this skill's output |
| Target UI5 version | 1.147.2 | Latest 1.x at writing; matches the FE app in the demo; aligned with 2.0-API |
| Framework | SAPUI5 | Matches the legacy app's ui5.yaml and the FE app's runtime |
| Language | TypeScript | Per get_typescript_conversion_guidelines |
| Types package | @sapui5/types@1.147.2 | Required by UI5 MCP TS guidelines (NOT the older sap-ui5-types typo) |
| App namespace | Source namespace + .modern (e.g. <source_namespace>.modern) | Distinguishes from legacy in routing; keeps grep continuity |
| Theme | sap_horizon | UI5 1.108+ default; legacy sap_belize is deprecated |
| Layout | Translate sap.m.SplitApp ➜ sap.f.FlexibleColumnLayout (FCL) | Modern responsive default for main + detail |
| Naming | No Hungarian prefixes; "main" not "master" — see "Naming overrides" section above | Aligned with TS-idiomatic names + SAP Inclusive Language |
| Bootstrap | data-sap-ui-async="true" + data-sap-ui-on-init="module:sap/ui/core/ComponentSupport" | Per UI5 guidelines; sync is deprecated and breaks 2.x |
| Manifest version | _version: 1.60.0 or later | Required for sap.app.dataSources + declarative models |
| OData model | The V4 service produced by migrate-segw-to-rap (or any V4 service the user names), via dev-server proxy. Pattern: /sap/opu/odata4/sap/<service_binding>/srvd/sap/<service_binding>/0001/ for SRVD-direct, or check $metadata of a sibling reference app if one exists | V4 demonstrates the modern pattern; same backend as any FE app you've already built |
| Routing | sap.m.routing.Router ➜ sap.f.routing.Router with per-FCL-column targets | FCL needs the f-router |
| BaseController | Required | Single source of truth for getRouter, getModel, getResourceBundle, getOwnerComponent |
| Event types | Use <Control>$<Event>Event (e.g. Button$PressEvent) | UI5 ≥ 1.115 supports them; UI5 guideline says MUST use |
| Formatters | OData types (sap.ui.model.odata.type.*) first; custom only for unique business logic | Per UI5 guideline §1 |
| Forms | sap.ui.layout.form.Form + ColumnLayout if any | Never SimpleForm (UI5 guideline §4) |
| Casts | Real control types (as Button), never as any / as unknown as ... | Per TS conversion §General Rules |
| Tests | OPA5 + QUnit skipped from first cut | Promoted to follow-up if Run 1 is green |
| Linter | mcp__SAPUI5_MCP_Server__run_ui5_linter → 0 findings | Hard acceptance criterion |
| Manifest validation | mcp__SAPUI5_MCP_Server__run_manifest_validation → 0 errors | Hard acceptance criterion |
| Type check | npm run ts-typecheck (script added to package.json) → 0 errors | Hard acceptance criterion |
Input
The user provides one of:
- A relative path to the legacy app, e.g.
<source_app>/ - A target folder name, e.g.
<modern_app>/(skill infers source as the siblinglegacy-*) - Nothing — assume defaults (
<source_app>/➜<modern_app>/)
If both folders exist and the target is non-empty, ask: "<target>/ already has content.
Wipe it and start over, or migrate into the existing structure?" Default to wipe-and-rewrite
for the demo.
Phase 0 — Preflight
0a. Legacy app readable
Bash: cat <legacy>/webapp/manifest.json
Bash: ls <legacy>/webapp/{controller,view,model,fragment,i18n}
Assert: manifest.json parses; webapp/controller/ and webapp/view/ both exist; at least
one *.controller.js and one *.view.xml are present. If any of these fail, stop with
"<legacy> does not look like a UI5 app — check the path."
0b. UI5 MCP server reachable
mcp__SAPUI5_MCP_Server__get_version_info(frameworkName="SAPUI5")
Assert: returns at least 1.147.x in the version map. If the tool errors, stop with "UI5
MCP server is not configured; configure it in .cursor/mcp.json before running this skill."
0c. Pull the authoritative guidelines (do this BEFORE writing any code)
mcp__SAPUI5_MCP_Server__get_typescript_conversion_guidelines
mcp__SAPUI5_MCP_Server__get_guidelines
Read both responses fully. They are the source of truth for:
- dev-dependency versions (
@ui5/cli,typescript,ui5-tooling-transpile,ui5-middleware-livereload,typescript-eslint) tsconfig.jsonshape (target: es2023,module: es2022,types: ["@sapui5/types"], paths map)ui5.yamlshape (ui5-tooling-transpile-task+ui5-tooling-transpile-middleware)- The 5-step code conversion sequence: (1) class syntax, (2) ES modules, (3) type annotations, (4) casts for generic getters, (5) remaining issues
- The
@namespaceJSDoc rule: required immediately before each exported class for the back-transformation to re-add the UI5 class name - The casts to avoid: never
any, neverunknown as ...— use real control types - The control-event-type rule: import
Button$PressEventfromsap/m/Button, notEventfromsap/ui/base/Event
These tool responses are large and version-specific — do not paraphrase from memory; quote them when you need to.
0d. npm + node available
Bash: node --version && npm --version
Assert: Node 22+ (CLAUDE.md requirement) and npm 10+.
Phase 1 — Discover the legacy app
Read every relevant file in <legacy>/webapp/. Classify findings as blocker (must fix for
modern UI5), cleanup (worst-practice but works), or cosmetic (style).
1a. Manifest scan
Pull _version, sap.ui5.dependencies.minUI5Version, sap.ui5.rootView,
sap.ui5.dependencies.libs, sap.ui5.routing, sap.ui5.models, sap.ui5.contentDensities,
sap.ui5.resources, theme references.
Common legacy patterns:
_version: 1.40.0➜ blocker (target 1.60+)minUI5Version< 1.108 ➜ blocker (no async guarantees)routerClass: "sap.m.routing.Router"with FCL target ➜ blocker- Hard-coded service URLs in
sap.ui5.models➜ cleanup (move tosap.app.dataSources) contentDensities: { compact: true, cozy: true }➜ cleanup (still supported, just move to manifest)supportedThemes: ["sap_belize"]➜ cleanup (drop; sap_horizon is default)
1b. Component.js scan
Read <legacy>/webapp/Component.js. Look for:
jQuery.sap.require("...")➜ blocker (delete; use ES imports)- Hardcoded service URL constant +
new sap.ui.model.odata.v2.ODataModel(...)ininit➜ blocker (move model to manifestsap.ui5.models[""]) - Manual
devicemodel creation ➜ keep (it's normal, but typed in TS) sap.ui.model.BindingMode.TwoWayfor OData V4 ➜ blocker (V4 prefersOneWayreads + explicit edits)useBatch: false➜ N/A for V4 (V4 always batches differently)- Mixed concerns (formatter loaded via
jQuery.sap.requirein Component) ➜ blocker
1c. Controller scan (per controller)
For each <legacy>/webapp/controller/<X>.controller.js:
Read: <legacy>/webapp/controller/<X>.controller.js
Flag:
var that = this;followed by closures ➜ cleanup (arrow functions)oCtx.getPath()regex parsing (.replace(/^\/Set\('/, "")) ➜ blocker (useoCtx.getProperty("Key"))sap.ui.getCore().byId(...)➜ cleanup (this.byId(...))sap.ui.getCore().getModel(...)➜ blocker (this.getOwnerComponent()!.getModel(...)with cast)sap.ui.core.UIComponent.getRouterFor(this)➜ cleanup (move to BaseController)sap.m.MessageBoxaccessed as global ➜ blocker (import MessageBox from "sap/m/MessageBox")jQuery.sap.require(...)➜ blocker (ES import)- Global formatter calls (
window.com.demo.formatter.X) ➜ blocker (consolidate into formatter module, import in views viacore:require) oModel.callFunction("/X", {method:"POST", urlParameters: {...}})(OData V2 function-import) ➜ blocker (translate to V4 action:model.bindContext("/Action(...)").execute())setTimeout(..., 500)for "refresh after data arrives" ➜ blocker (use binding events, e.g.dataReceived)- No JSDoc on parameters ➜ cosmetic (TS rewrite handles it)
1d. View scan (per view)
For each <legacy>/webapp/view/<X>.view.xml:
Read: <legacy>/webapp/view/<X>.view.xml
Flag:
- Inline event handlers (
press="onSomething") referencing methods that don't exist ➜ blocker (will throw) <core:Fragment fragmentName="...">without async ➜ cleanup- Deprecated controls (
sap.ui.commons.*) ➜ blocker sap.m.SplitApproot ➜ blocker (translate to FCL per smart-defaults)- Hardcoded strings instead of i18n keys ➜ cleanup
- Path-based formatters (
formatter: 'window.com.demo.X.statusText') ➜ blocker (convert tocore:requireof formatter module +formatter: '.formatter.statusText') enabled="{= ${Status} === 'D' }"(expression binding) ➜ keep but adapt to V4 key (noStatus➜OverallStatusetc., depending on the V4 model)
1e. Formatter scan
For <legacy>/webapp/model/formatter.js:
jQuery.sap.declare(...)+window.com.demo...global namespace ➜ blocker (rewrite as ES module withexport function)sap.ui.core.format.DateFormat.getDateInstance(...)instantiated per call ➜ cleanup (memoize once at module top-level)- Per-call format object instantiation ➜ cleanup (instantiate once)
- Status / priority mapping switches ➜ keep but type as
string | undefined➜string
1f. Build the findings report
Output a structured summary to the user:
Discovery — legacy app: <legacy>
Manifest version: 1.40.0 (target 1.60+)
UI5 version: 1.84.x (target 1.147.2)
Controllers: 3 (App, Master, Detail)
Views: 5 (App, Master, Detail, Welcome, NotFound)
Layout: sap.m.SplitApp (target sap.f.FlexibleColumnLayout)
Theme: sap_belize (target sap_horizon)
OData: V2 hardcoded in Component.init (target V4 via manifest dataSources)
Blockers (<n>):
- Component.js: hardcoded service URL + manual ODataModel construction
- Component.js: jQuery.sap.require(...)
- formatter.js: window.com.* global namespace
- Master.controller.js: getPath() regex parsing of V2 entity key
- Detail.controller.js: oModel.callFunction("/ApproveProject", ...) for V2 function-import
- Detail.controller.js: setTimeout(..., 500) for counter refresh
- *.view.xml: window.com.* formatter paths
- App.view.xml: SplitApp root
- ...
Cleanups (<n>):
- Master.controller.js: `var that = this;` pattern (4×)
- All controllers: `sap.ui.core.UIComponent.getRouterFor(this)` direct calls
- ...
Cosmetic (<n>):
- Missing JSDoc across controllers
- ...
Phase 2 — Design plan + user approval
Print the migration plan in this exact format and STOP for ok / edit / question:
Plan — modernize <legacy> ➜ <target>:
UI5 version: 1.147.2 SAPUI5 (TypeScript)
Types: @sapui5/types@1.147.2
Namespace: <source_namespace>.modern
Theme: sap_horizon
Layout: sap.f.FlexibleColumnLayout (translated from SplitApp)
OData: V4 — <v4_service_url>
Proxy: ui5-middleware-simpleproxy → <sap_baseuri>
(auth via .env: UI5_MIDDLEWARE_SIMPLE_PROXY_{USERNAME,PASSWORD})
Naming overrides: - No Hungarian prefixes (TS types replace the hint)
- "main" instead of "master" for controller / view / route / i18n keys
(legacy Master.controller.js ➜ Main.controller.ts, etc.)
Files to generate in <target>/webapp:
Component.ts
manifest.json (v1.60.0)
index.html (ComponentSupport bootstrap, async, inline height fix)
controller/BaseController.ts
controller/App.controller.ts
controller/Main.controller.ts ← renamed from Master per naming overrides
controller/Detail.controller.ts
view/App.view.xml (FCL root)
view/Main.view.xml ← renamed from Master
view/Detail.view.xml
view/Welcome.view.xml
view/NotFound.view.xml
i18n/i18n.properties (translated keys: masterX → mainX) + i18n_en.properties
css/style.css (copied from legacy if non-empty)
model/models.ts (device-model helper only)
model/formatter.ts (consolidated; ES module export)
Files at <target>/ root:
package.json (with @ui5/cli, typescript, ui5-tooling-transpile, ui5-middleware-livereload,
ui5-middleware-simpleproxy, @sapui5/types)
ui5.yaml (specVersion 4.0; transpile + livereload + simpleproxy middleware)
tsconfig.json (target es2023, module es2022, strict, allowJs)
.env.example
.gitignore
V2 ➜ V4 binding migrations (generic — adapt to your service's entity names):
/<EntitySet> ➜ /<Entity> (drop "Set" suffix)
/<EntitySet>('K') ➜ /<Entity>(<Key>='K') (named-key style)
expand: '<Nav>' ➜ $expand=_<Nav> (V4 RAP prefixes assocs with _)
oModel.callFunction(...) ➜ model.bindContext("/<Action>(...)").execute()
fieldName remapping ➜ inspect $metadata; RAP often renames fields between V2/V4
Blockers being fixed: <count>
Cleanups applied: <count>
Cosmetic skipped: <count> (separate prettier pass if desired)
Tests in this skill: none (OPA5/QUnit follow-up)
Acceptance: ui5-linter clean + manifest validation clean + tsc clean + npm start
renders Master list
Type `ok` to proceed, `edit` to revise, or ask any question.
Wait for ok before mutating anything in <target>/.
Phase 3 — Scaffold the modern TS app
3a. Wipe target if non-empty
If the user confirmed wipe-and-rewrite:
Bash: rm -rf <target>/* <target>/.[!.]* # safely empty <target>/ while keeping the folder
3b. Scaffold via UI5 MCP
Call create_ui5_app directly into <target>/ (NOT into a sub-folder):
mcp__SAPUI5_MCP_Server__create_ui5_app(
appNamespace = "<source_namespace>.modern",
basePath = "<absolute path to target>",
createAppDirectory = false,
framework = "SAPUI5",
frameworkVersion = "1.147.2",
typescript = true,
initializeGitRepository = false,
runNpmInstall = true
)
oDataV4Urlis intentionally omitted here — the V4 service is behind a proxy with credentials, so URL validation will fail. The data source is added manually in Phase 4.
3c. Verify the structure
Bash: ls -la <target>/ && ls <target>/webapp/
Expected at root: package.json, ui5.yaml, tsconfig.json, webapp/ with at minimum
Component.ts, manifest.json, view/App.view.xml, controller/App.controller.ts,
index.html, i18n/i18n.properties.
If create_ui5_app produces JS files instead of TS, fail loud — do NOT silently fall back to
manual scaffolding.
3d. Confirm dependencies match UI5 MCP guidelines
Read: <target>/package.json
Cross-check against get_typescript_conversion_guidelines output. The expected dev-deps include
at minimum:
@ui5/clitypescriptui5-tooling-transpileui5-middleware-livereload@sapui5/typesmatching framework version
Add anything missing (e.g. add ui5-middleware-simpleproxy for OData proxying). Update versions
only if they're below the floor the guidelines specify; never downgrade.
Then run npm install again if the dep list changed.
Also confirm "ts-typecheck": "tsc --noEmit" exists in scripts (UI5 MCP guideline). Add if
missing.
3e. Warning — the scaffold itself uses Hungarian notation
The UI5 MCP scaffold templates (Component.ts, BaseController.ts, the default
*.controller.ts, models.ts) ship with Hungarian-prefixed parameter and local-variable
names (sName, oModel, oParameters, etc.). The Naming overrides section above applies to
the scaffold too — rename them as you read each scaffolded file, not just when porting from
the legacy controllers.
The fastest workflow: scaffold first, then do one batch grep+rename pass over the
scaffolded webapp/ for the half-dozen common prefixes (oModel, sName, oEvent,
oParameters, etc.) BEFORE writing any new per-view controllers. This way the BaseController
you're about to extend is already in modern style.
Phase 4 — Configure manifest.json + ui5.yaml + proxy
4a. Translate manifest.json
Read <target>/webapp/manifest.json, then merge in the legacy specifics:
-
Set
sap.app.id=<source_namespace>.modern. -
Set
sap.app.title/sap.app.descriptionfromi18n(already templated as{{appTitle}}). -
Copy
sap.app.iconsfrom legacy if non-empty. -
Add
sap.app.dataSourceswith the V4 service URL the user names (or, if uncertain, runmcp__sap-docs__searchfor the V4 binding pattern your backend uses; SRVD-direct on ABAP on-prem is typically/sap/opu/odata4/sap/<service_binding>/srvd/sap/<service_binding>/0001/):"dataSources": { "mainService": { "uri": "<v4_service_url>", "type": "OData", "settings": { "odataVersion": "4.0", "localUri": "localService/metadata.xml" } } } -
Set
sap.ui5.dependencies.minUI5Version="1.147.0"; libs:sap.ui.core,sap.m,sap.f,sap.ui.layout. -
Set
sap.ui5.models[""]:"": { "type": "sap.ui.model.odata.v4.ODataModel", "dataSource": "mainService", "settings": { "operationMode": "Server", "autoExpandSelect": true, "earlyRequests": true } } -
Set
sap.ui5.rootViewto{ "viewName": "<ns>.view.App", "type": "XML", "id": "app" }. -
Routing — every route MUST have a
layoutproperty (Trap 1) and every target MUST havetype: "View"+ usename/path/level(NOTviewName/viewPath/viewLevel) (Trap 5):"routing": { "config": { "routerClass": "sap.f.routing.Router", "type": "View", // ← REQUIRED in manifest v2 (Trap 5) "viewType": "XML", "path": "<ns>.view", // ← NOT "viewPath" "async": true, "controlId": "flexibleColumnLayout", "controlAggregation": "beginColumnPages", "bypassed": { "target": "notFound" } }, "routes": [ { "pattern": "", "name": "main", "target": ["main", "welcome"], "layout": "TwoColumnsMidExpanded" // ← REQUIRED (Trap 1) }, { "pattern": "<EntityRoute>/{<keyParam>}", "name": "detail", "target": ["main", "detail"], "layout": "TwoColumnsMidExpanded" // ← REQUIRED (Trap 1) } ], "targets": { "main": { "type": "View", "id": "main", "name": "Main", "level": 1, "controlAggregation": "beginColumnPages" }, "welcome": { "type": "View", "id": "welcome", "name": "Welcome", "level": 2, "controlAggregation": "midColumnPages" }, "detail": { "type": "View", "id": "detail", "name": "Detail", "level": 2, "controlAggregation": "midColumnPages" }, "notFound": { "type": "View", "id": "notFound", "name": "NotFound", "level": 3, "controlAggregation": "midColumnPages" } } }Note:
type: "View"appears both onconfigAND on each target. The config-level default should propagate, but per-target redundancy is belt+braces against UI5-version differences in how the default is resolved. -
sap.ui5.contentDensities={ "compact": true, "cozy": true }(declarative — fine). -
Drop
supportedThemes(sap_horizon is the default; no need to pin).
Write the merged manifest:
Write: <target>/webapp/manifest.json
Validate:
mcp__SAPUI5_MCP_Server__run_manifest_validation(manifestPath="<absolute path>/webapp/manifest.json")
Fix anything it flags before moving on.
4b. ui5.yaml — add proxy + ensure transpile middleware
Open <target>/ui5.yaml. It already has ui5-tooling-transpile-task and
ui5-tooling-transpile-middleware after Phase 3 (verify). Add the simpleproxy and livereload:
specVersion: "4.0"
metadata:
name: <source_namespace>.modern
type: application
framework:
name: SAPUI5
version: "1.147.2"
libraries:
- name: sap.m
- name: sap.ui.core
- name: sap.f
- name: sap.ui.layout
- name: themelib_sap_horizon
builder:
customTasks:
- name: ui5-tooling-transpile-task
afterTask: replaceVersion
server:
customMiddleware:
- name: ui5-tooling-transpile-middleware
afterMiddleware: compression
- name: ui5-middleware-livereload
afterMiddleware: compression
- name: ui5-middleware-simpleproxy
afterMiddleware: compression
mountPath: /sap
configuration:
baseUri: "<sap_baseuri>/sap" # e.g. https://abap-host:50001/sap or https://my-cf-host
strictSSL: false # only if upstream uses a self-signed cert (dev trials)
query:
sap-client: "<client>" # e.g. "001"; omit if your service doesn't need it
Config-key trap: the key is
strictSSL: false— notskipCertificateCheckorignoreCertErrors. Those names exist for other proxy middlewares (fiori-tools-proxyusesignoreCertErrors), butui5-middleware-simpleproxysilently ignores unknown keys, so a wrong key fails the HTTPS handshake without any error message. Verified against the middleware's README and confirmed working in the demo workspace.
Add ui5-middleware-simpleproxy to package.json's ui5.dependencies so ui5 tooling
auto-loads it:
"ui5": { "dependencies": ["ui5-middleware-simpleproxy"] }
4c. .env scaffolding
Write: <target>/.env.example
UI5_MIDDLEWARE_SIMPLE_PROXY_USERNAME=
UI5_MIDDLEWARE_SIMPLE_PROXY_PASSWORD=
Ask the user once (interactive) to copy values into <target>/.env. Don't commit .env.
4d. index.html — ComponentSupport bootstrap + inline height (verify after scaffold)
The scaffolded index.html should already use ComponentSupport. Fix the height handling per
Trap 2 above — the component <div> MUST have style="height: 100%" inline:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{appTitle}}</title>
<style>html,body,#content { height: 100%; margin: 0; }</style>
<script
id="sap-ui-bootstrap"
src="resources/sap-ui-core.js"
data-sap-ui-theme="sap_horizon"
data-sap-ui-resource-roots='{ "<source_namespace>.modern": "./" }'
data-sap-ui-on-init="module:sap/ui/core/ComponentSupport"
data-sap-ui-compat-version="edge"
data-sap-ui-async="true"
data-sap-ui-frame-options="trusted">
</script>
</head>
<body class="sapUiBody" id="content">
<div
data-sap-ui-component
data-name="<source_namespace>.modern"
data-id="container"
data-height="100%"
style="height: 100%"></div>
</body>
</html>
Notes:
- The
style="height: 100%"is mandatory — a CSS selector against[data-sap-ui-component]would seem cleaner but does NOT work because ComponentSupport strips that attribute during processing (Trap 2). data-height="100%"alone is not enough — it's aComponentContainersetting that resolves against the parent's height, which is why we also need the inline style on the wrapping div.- No inline
<script>other than the bootstrap (CSP rule, UI5 guideline §1).
Phase 5 — BaseController + Component.ts + App.view.xml
5a. BaseController.ts
Write: <target>/webapp/controller/BaseController.ts
import Controller from "sap/ui/core/mvc/Controller";
import UIComponent from "sap/ui/core/UIComponent";
import Router from "sap/f/routing/Router";
import Model from "sap/ui/model/Model";
import ResourceModel from "sap/ui/model/resource/ResourceModel";
import ResourceBundle from "sap/base/i18n/ResourceBundle";
import History from "sap/ui/core/routing/History";
/**
* @namespace <source_namespace>.modern.controller
*/
export default class BaseController extends Controller {
public getRouter(): Router {
return UIComponent.getRouterFor(this) as Router;
}
public getModel<T extends Model = Model>(name?: string): T {
return this.getView()!.getModel(name) as T;
}
public setModel(model: Model, name?: string): void {
this.getView()!.setModel(model, name);
}
public async getResourceBundle(): Promise<ResourceBundle> {
const i18n = this.getOwnerComponent()!.getModel("i18n") as ResourceModel;
return (await i18n.getResourceBundle()) as ResourceBundle;
}
public onNavBack(): void {
const previousHash = History.getInstance().getPreviousHash();
if (previousHash !== undefined) {
window.history.go(-1);
} else {
this.getRouter().navTo("master", {}, true);
}
}
}
5b. Component.ts
The template gives you something like this; ensure:
import UIComponent from "sap/ui/core/UIComponent";
import Device from "sap/ui/Device";
import JSONModel from "sap/ui/model/json/JSONModel";
/**
* @namespace <source_namespace>.modern
*/
export default class Component extends UIComponent {
public static metadata = {
manifest: "json",
interfaces: ["sap.ui.core.IAsyncContentCreation"]
};
public init(): void {
super.init();
const deviceModel = new JSONModel(Device);
deviceModel.setDefaultBindingMode("OneWay");
this.setModel(deviceModel, "device");
this.getRouter().initialize();
}
public getContentDensityClass(): string {
return Device.support.touch ? "sapUiSizeCozy" : "sapUiSizeCompact";
}
}
(Carry the getContentDensityClass over from the legacy component since App.controller
uses it.)
5c. App.view.xml (FCL root)
<mvc:View
xmlns:mvc="sap.ui.core.mvc"
xmlns="sap.f"
controllerName="<source_namespace>.modern.controller.App"
displayBlock="true"
height="100%">
<FlexibleColumnLayout id="flexibleColumnLayout"
backgroundDesign="Solid"
layout="OneColumn"/>
</mvc:View>
5d. App.controller.ts
import BaseController from "./BaseController";
import Component from "../Component";
/**
* @namespace <source_namespace>.modern.controller
*/
export default class App extends BaseController {
public onInit(): void {
const oOwner = this.getOwnerComponent() as Component;
this.getView()!.addStyleClass(oOwner.getContentDensityClass());
}
}
Phase 6 — Per-view conversion
For each legacy <View>.view.xml + <View>.controller.js, generate the modern equivalent.
Process in order: Main (was Master) ➜ Detail ➜ Welcome ➜ NotFound.
Reminder before writing any controller: apply the naming overrides from the top of this skill — no Hungarian prefixes (
const list = ..., notconst oList = ...); renameMaster.controller.js➜Main.controller.ts; use specific event types (Trap 3), neverEventfromsap/ui/base/Event.
For every controller, follow the 5-step TS conversion from
get_typescript_conversion_guidelines:
Class.extend()➜class extends ...with@namespaceJSDoc immediately preceding it.sap.ui.define([...], function(...))➜ ESimport+export default class.- Add type annotations to method parameters / class properties; use specific event types like
Button$PressEvent, never bareEventfromsap/ui/base/Event. - Cast return values of generic getters:
this.byId("x") as Table,this.getView()!.getModel() as ODataModel,event.getSource() as ColumnListItem. - Fix remaining type errors. Prefer real types over
any/unknown as ....
6a. View translation pattern
-
<SplitApp>root ➜ replaced byApp.view.xml(FCL) — already done in 5c. -
Master goes into FCL
beginColumnPagesvia routing; Detail goes intomidColumnPages. -
Keep
<Page>wrappers inside each view — they're fine. -
Replace
controllerName="<source_namespace>.<X>"➜controllerName="<source_namespace>.modern.controller.<X>". -
For formatters: legacy uses
formatter: 'window.com.demo.../statusText'(global path). Modern usescore:require+ relative formatter:<List core:require="{ formatter: '<source_namespace>/modern/model/formatter' }" ...> <ObjectListItem title="{Title}" number="{ path: 'OverallStatus', formatter: 'formatter.statusText' }" numberState="{ path: 'OverallStatus', formatter: 'formatter.statusState' }" .../> </List>Note the namespace path uses
/(slash notation) insidecore:require. The legacy "dot" property name still works in the formatter binding becauseformatter.statusTextis resolved relative to thecore:requiremap. -
For V2 ➜ V4 entity/path translation, see 6c below.
-
Drop
sap.ui.commons.*references. -
Drop deprecated
numberUnit,firstStatus,responsive,condensed,backgroundDesignif the linter flags them (they may or may not be deprecated depending on the control).
6b. Controller translation pattern (the 5 steps in detail)
For each <X>.controller.js:
Step 1: Class syntax
Before:
sap.ui.define(["sap/ui/core/mvc/Controller"], function (Controller) {
"use strict";
return Controller.extend("com.demo.X.controller.Master", {
onInit: function() { /* ... */ }
});
});
After (NB the @namespace annotation — it is required):
import Controller from "sap/ui/core/mvc/Controller";
/**
* @namespace com.demo.X.modern.controller
*/
export default class Master extends Controller {
public onInit(): void { /* ... */ }
}
(In practice you extend BaseController, not Controller directly — see 6d.)
Step 2: ES imports
Replace every sap.ui.define/sap.ui.require with ES import. Replace dynamic
sap.ui.require(["sap/m/MessageBox"], cb) with import("sap/m/MessageBox").then(...) — never
jQuery.sap.require.
Step 3: Typed event handlers (Trap 3 again — please read)
Before:
onPress: function (oEvent) {
var oItem = oEvent.getParameter("listItem");
var oCtx = oItem.getBindingContext();
}
After (note: no Hungarian; specific event type):
import { List$SelectionChangeEvent } from "sap/m/List";
import ColumnListItem from "sap/m/ColumnListItem";
public onPress(event: List$SelectionChangeEvent): void {
const item = event.getParameter("listItem") as ColumnListItem;
const ctx = item.getBindingContext();
}
Do NOT fall back to import Event from "sap/ui/base/Event" because the generic type
forces as casts on every getParameter / getParameters call. If a specific event type
doesn't seem to exist, search for it first:
mcp__SAPUI5_MCP_Server__get_api_reference(
projectDir="<target>",
query="sap.m.SearchField#liveChange"
)
For OData V4 context-aware events, use sap.ui.model.odata.v4.Context:
import V4Context from "sap/ui/model/odata/v4/Context";
const ctx = item.getBindingContext() as V4Context;
Step 4: Casts for generic getters
import ODataModel from "sap/ui/model/odata/v4/ODataModel";
const model = this.getOwnerComponent()!.getModel() as ODataModel;
import Table from "sap/m/Table";
const tasksTable = this.byId("tasksTable") as Table;
(Note: variable names are model / tasksTable, NOT oModel / oTable.)
Step 5: V2 ➜ V4 binding migrations
This is the largest non-mechanical chunk. Three patterns to know:
(i) Entity key in path
V2 path: /<EntitySet>('K') — single-quoted string key, Set suffix.
V4 path: /<Entity>(<KeyField>='K') — no Set suffix, named-key style.
If the V4 service is draft-enabled (most RAP-managed scenarios are), the key is
composite: /<Entity>(<KeyField>='K',IsActiveEntity=true). Reading active rows is the
default for a read-only freestyle TS app, so IsActiveEntity=true is usually right.
Reverse-derivation from a binding context — read the property, don't parse the path:
// V2: var sKey = oCtx.getPath().replace(/^\/Set\('/, "").replace(/'\)$/, "");
// V4: just read the property
const key = ctx.getProperty("<KeyField>") as string;
If you don't know whether the service is draft-enabled, search:
mcp__sap-docs__search(query="Draft Handling with the OData V4 Model")
(ii) Expand
V2: parameters: { expand: "<Nav>" } (in bindElement).
V4: pass via parameters: { $expand: "_<Nav>" } (note the underscore — RAP V4 services typically
prefix association names with _) OR rely on autoExpandSelect: true in the manifest model
config and let UI5 figure it out from the view bindings.
Recommended: rely on autoExpandSelect: true + path-based bindings (items="{_<Nav>}").
Don't hand-author $expand unless you have a specific reason. To confirm the navigation name
for your service, fetch its $metadata and look for <NavigationProperty Name="_X">.
(iii) Function-imports ➜ actions
V2:
oModel.callFunction("/<Function>", {
method: "POST",
urlParameters: { <Key>: sKey },
success: function(oData) { /* ... */ },
error: function(oErr) { /* ... */ }
});
V4 (bound action — the typical RAP pattern):
import V4Context from "sap/ui/model/odata/v4/Context";
import ODataModel from "sap/ui/model/odata/v4/ODataModel";
const ctx = this.getView()!.getBindingContext() as V4Context;
const model = ctx.getModel() as ODataModel;
// Bound action: invoke relative to the entity context
const operation = model.bindContext("<Action.FQN>(...)", ctx);
try {
await operation.invoke("$auto"); // newer V4 API; older: .execute()
MessageToast.show("Action succeeded.");
ctx.refresh(); // pick up state changes
} catch (err) {
MessageBox.error((err as Error).message);
}
The fully-qualified action name (<Action.FQN>) is service-specific. For RAP V4 it looks
like com.sap.gateway.srvd.<service_name>.v0001.<action_name>. To find it for your service,
inspect $metadata and look for <Action Name="X" IsBound="true"> — the parent <Schema Namespace>
attribute plus .X is the FQN. Use mcp__sap-docs__search(query="OData V4 Operations action invocation UI5")
if uncertain about the API shape.
Step 6: Move private fields to class properties
Before (legacy):
onInit: function () {
this._sProjectId = undefined; // implicit, later
}
After:
export default class Detail extends BaseController {
private projectId?: string; // no Hungarian; plain field name
public onInit(): void { /* ... */ }
}
6b.1 V4 path-relative binding lives in the XML view, not the controller
When a parent-row selection should refresh a child-table binding (e.g. "select a task → time entries reload"), the V4 idiomatic pattern is:
-
Declare the items binding in the XML view, relative to the parent context's navigation association (
_<Nav>):<Table id="<childTable>" items="{ path: '_<Nav>', parameters: { $filter: 'IsActiveEntity eq true' } }"> <columns> <Column><Text text="{i18n>colA}" /></Column> <!-- ... --> </columns> <items> <ColumnListItem> <cells> <Text text="{<FieldA>}" /> <!-- ... --> </cells> </ColumnListItem> </items> </Table> -
In the controller, set the binding context when the parent row is selected — UI5 picks up the
_<Nav>association relative to the new context:const childTable = this.byId("<childTable>") as Table; childTable.setBindingContext(parentContext);
SAP Clean Core ATC Classification
Inventory a package of custom code and bucket every Z/Y object into Clean Core Levels A–D based on the SAP APIs it uses — the "is this cloud-ready?" audit.
This is different from migrate-custom-code: that skill fixes one object's ATC findings; this one produces a package-wide classification report with per-object levels, used to plan a clean-core / BTP migration. It combines ARC-1 (ATC + source access) with mcp-sap-docs (released-API classification data from SAP/abap-atc-cr-cv-s4hc).
Clean Core Levels (what they mean)
| Level | Meaning | Cloud-ready? |
|---|---|---|
| A | Uses only released SAP APIs | ✅ Yes — move as-is to ABAP Cloud / BTP |
| B | Uses classic APIs (on-premise-only, documented) | 🟡 Works on on-prem S/4HANA; needs rewrite for cloud |
| C | Uses internal/stable SAP objects (not customer-released) | 🔴 Supported today but no API guarantee |
| D | Uses objects with no API status (deep internals, undocumented) | 🔴 High migration risk, may break on upgrade |
Source: SAP/abap-atc-cr-cv-s4hc — SAP's official machine-readable release state list.
These are the extensibility levels (SAP Note 3578329) — which SAP APIs your code calls. SAP defines a separate A–D scale for integration technologies in Note 3690029 (RFC, IDoc, SEGW OData, file transfer …), which "complements, but does not overlap with" this one. Same letters, different axis: never merge the two into one score. For the integration axis use the Integration Interfaces section of sap-migration-dossier.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Target system type | public_cloud | Clean-core audits almost always target cloud readiness |
| ATC variant | ABAP_CLOUD_READINESS if available, else the system default | Cloud readiness is the point of the exercise; verify the name with atc_variants first |
| Include in scope | Z*, Y*, plus any /namespace/* the user names | Customer code only; skip SAP-shipped |
| Report detail | Summary table + level-breakdown + top violations | Actionable overview; drill-down on request |
Input
The user provides a package (preferred) or a comma-separated object list, plus optional target system type.
- Package (e.g.,
Z_FI_CUSTOM): audit every custom object in it - Object list (e.g.,
ZCL_POSTING, ZR_SALES_REPORT): audit only the named ones - Target system type:
public_cloud(default) |btp|private_cloud|on_premise
If neither package nor object list is given, ask which to use. Do NOT audit "everything" — that's never what the user wants.
Step 1: Enumerate Custom Objects
1a. Package path
SAPRead(type="DEVC", name="<package>")
Filter results to keep only PROG | CLAS | INTF | FUGR | FUNC | DDLS | BDEF | SRVD | TABL with names starting Z, Y, or a customer namespace. Skip subpackages (audit them separately) unless the user says "recursive".
1b. Object-list path
For each name, resolve the type:
SAPSearch(query="<name>")
Use the first exact match.
Step 2: Extract SAP API References per Object
For each custom object, collect the list of SAP-shipped objects it references.
2a. Use SAPContext for dependency extraction
SAPContext(type="<type>", name="<object_name>", depth=1)
SAPContext returns a dependency list. Keep only dependencies whose names do NOT start with Z/Y/customer-namespace — those are SAP references. Record each as (objectType, objectName).
SAPContext supports CLAS, INTF, PROG, FUNC, DDLS (on-prem) and CLAS, INTF, DDLS (BTP). For other types (FUGR, BDEF, SRVD, TABL), fall back to reading the source with SAPRead and extracting SAP class / interface / function references with a regex scan over lines (e.g., CL_*, IF_*, SAP*, CALL FUNCTION '...'). Mark these references as "static-scan" in the report so the user knows confidence is lower than AST-derived deps.
2b. Also run ATC for cloud readiness
SAPDiagnose(action="atc", type="<type>", name="<object_name>", variant="ABAP_CLOUD_READINESS")
If ABAP_CLOUD_READINESS doesn't exist on the system ARC-1 rejects the call rather than silently running DEFAULT — list the real names with SAPDiagnose(action="atc_variants") and pick one, or omit variant to bind the system's configured default (systemCheckVariant), and note the choice in the report. On-premise systems often ship S4HANA_READINESS_<release> (e.g. S4HANA_READINESS_2023) or SAP_CLOUD_PLATFORM_DEFAULT instead of ABAP_CLOUD_READINESS. ATC findings complement the API classification — a released API can still be used incorrectly.
ATC skips
$TMP/ local objects (verified live on S/4HANA 2023). A check run against a$TMPobject resolves to an empty object set and returns zero findings — that's "not checked", not "clean". Package-wide classification only works on transportable packages. If a package is local/$TMP, note in the report that ATC results are unavailable and fall back to the mcp-sap-docs API classification alone. A finding count of 0 on code you expect to be flagged is almost always the$TMPtrap, not clean code.
Step 3: Classify Each SAP Reference via mcp-sap-docs
For each unique SAP object the custom code references:
sap_get_object_details(object_type="<type>", object_name="<name>", system_type="<target>", target_clean_core_level="A")
This returns:
cleanCoreLevel— A, B, C, or D. This is the extensibility axis (Note 3578329); when feeding asap-migration-dossiercard, map it toextensibilityLevelso it cannot be confused with an integration levelstate— released | deprecated | classicAPI | stable | notToBeReleased | noAPIcomplianceStatus—compliant|non_compliantvs. the target levelsuccessorObjects— replacement recommendations if deprecated
Cache results by (object_type, object_name) — the same SAP class is often referenced from many Z-objects.
If an object isn't found in the dataset (found: false), classify as D (unknown / no API) and flag it as requiring manual review.
Step 4: Roll Up to Per-Object Level
Each custom object's level is the highest (worst) level among its SAP references:
| If any reference is … | Object level |
|---|---|
| D | D |
| C (and no D) | C |
| B (and no C/D) | B |
| All A | A |
Record per object:
- Object level (A/B/C/D)
- Reference breakdown (counts per level)
- Top 3 worst references with their successors (if any)
- ATC cloud-readiness findings count (Priority 1/2/3)
Step 5: Emit the Report
5a. Headline summary
Clean Core Audit — <package_or_list>
Target system: <target> ATC variant: <variant>
Objects audited: 42
Level A: 12 (29%) — ready for ABAP Cloud as-is
Level B: 18 (43%) — on-prem only; rewrite for cloud
Level C: 8 (19%) — uses internal APIs; plan replacement
Level D: 4 (9%) — high risk; manual review required
5b. Per-level tables
For each level (start with D, work down — worst first):
Level D — High Risk (4 objects)
Object Non-compliant refs Top violation ATC P1
ZCL_MIGRATION_HELPER 8 CL_SALV_TREE_WRAPPER 3
ZR_OLD_POSTING 12 SAPLSMTR_NAVIGATION 5
...
5c. Replacement suggestions (Level B/C/D only)
For the top 10 most-referenced deprecated APIs, show {deprecated → successor} pairs with counts:
CL_GUI_ALV_GRID (used in 18 Z-objects) → CL_SALV_TABLE (A)
CL_IXML (used in 12 Z-objects) → XML transformations (A)
...
5d. Follow-up Options
Offer next steps:
- "Want per-object detail for Level D objects?" (drill into the 4 riskiest)
- "Want to migrate one of these objects now?" (→ migrate-custom-code)
- "Want to see which Z-objects are even USED?" (→ sap-unused-code — no point migrating dead code)
- "Want to document the Level A objects as reference examples?" (→ sap-object-documenter)
- "Want a reviewed dossier with saved evidence, customer questions, and visualizations?" (→ sap-migration-dossier)
Error Handling
| Error | Cause | Fix |
|---|---|---|
sap_get_object_details returns found: false | SAP object not in the release state dataset | Classify as D, flag for manual review; dataset covers S/4HANA only |
ABAP_CLOUD_READINESS variant not found | System doesn't have it configured (hard error, not a silent fallback) | List names via SAPDiagnose(action="atc_variants") and pick the closest, or omit variant for the system default; note in the report that findings are less cloud-specific |
| SAPContext unsupported for object type | E.g., dynamic programs, generated code | Fall back to regex scan of source for CL_*, IF_*, SAP* patterns |
| Empty package | Typo or package is only a structure package | Verify via SAPSearch; ask user to pick a child package |
| mcp-sap-docs not connected | Missing MCP server | Skill degrades to ATC-only classification; warn user |
Caveats
What this skill is NOT
- Not a migration tool — it classifies risk; use migrate-custom-code to actually fix.
- Not a replacement for SAP's Custom Code Migration app — that tool has more depth (runtime usage analysis, simplification DB, transport impact). This skill is a fast, LLM-friendly approximation.
- Accuracy depends on mcp-sap-docs dataset freshness — the SAP/abap-atc-cr-cv-s4hc repo is updated per S/4HANA release.
BTP vs On-Premise
- BTP audit (
system_type=btp): Level B becomes non-compliant — BTP only accepts Level A. Stricter than public_cloud. - On-premise audit (
system_type=on_premise): Level A+B are both compliant. Use this when the goal is "does my custom code survive the next S/4HANA upgrade?" rather than "can I run this in the cloud?".
When to Use This Skill
- Planning a move from ECC → S/4HANA Cloud
- Planning a move from ECC → ABAP Cloud on BTP
- Quarterly custom-code health check
- Before a major release upgrade (to flag high-risk objects early)
- Scoping a custom-code retirement project (combine with sap-unused-code)
SAP Migration Dossier
Build a migration planning artifact, not a one-object fix workflow. Use this skill to combine the existing ARC-1 migration skills into a scoped dossier that is easy to start and can become more formal only when the user asks.
Default to a concise chat report. Offer files, review cards, HTML, CSV/JSON, and graphs as optional follow-ups; do not ask the user to design a reporting system up front.
Read references/auditor-patterns.md only when the user asks for persistent artifacts, human review, imported extracts, deep ECC enhancement extraction, integrity hashes, HTML dashboards, or graph output.
Use SAP Docs MCP when available, especially for Clean Core/API status, successor APIs, release-specific syntax, and migration guidance. If SAP Docs MCP is not connected, still run the dossier with ARC-1 evidence and list "SAP Docs MCP unavailable" as an evidence gap.
Default Path
If the scope is clear, start immediately:
- Resolve the scope.
- Package:
SAPRead(type="DEVC", name="<package>") - Prefix/namespace:
SAPSearchper relevant type (PROG,CLAS,FUGR,FUNC,DDLS,BDEF,SRVD,TABL) - Object list: resolve ambiguous names with
SAPSearch - Local extract: parse the file and state that evidence is imported, not live ARC-1
- Package:
- Build a small inventory: object, type, package, description, LOC when available, last change/version when available.
- Add migration signals:
- ATC:
SAPDiagnose(action="atc", type="<type>", name="<name>") - Clean-core/API risk: reuse
sap-clean-core-atclogic - SAP Docs MCP: enrich SAP API references with
sap_get_object_details; usesearch/fetchfor the top ATC themes or replacement guidance - Usage/retirement: reuse
sap-unused-codeonly if SCMON/SUSG data is available - Dependencies/where-used:
SAPContextorSAPNavigate(action="references")
- ATC:
- Return a concise report with:
- headline counts
- highest-risk objects
- likely retirement candidates
- standard modification / enhancement hotspots
- top ATC/Clean Core themes
- clear evidence gaps
- suggested next action
Ask only when required:
- If no scope is provided, ask for a package, namespace/prefix, or object list.
- If the scope is very large, ask whether to narrow it or save a file-based dossier.
- If the user wants customer-facing decisions, ask whether to use a human-reviewed flow.
Integration Interfaces (Clean Core Integration)
Run this section when the user asks about interfaces, integration, RFC/IDoc/OData, "clean core integration", or which interfaces block a cloud move. Skip it otherwise — the default path stays about custom code.
This is a different axis from sap-clean-core-atc. That skill rates extensibility (SAP Note
3578329, which APIs your code calls). This section rates integration technologies (SAP Note
3690029, how systems talk to this one). Same A–D letters, different axis — SAP's own wording is that
the integration note "complements, but does not overlap with" the extensibility guidance.
Scope first
Reuse the scope resolved in the Default Path — do not hard-code Z%. Build the name filter from
what the user actually asked for: their prefixes (Z*, Y*), registered namespaces (/NS/*), the
object list, or TADIR.DEVCLASS for a package. A Z%-only filter silently drops Y* and every
namespaced object.
The EDIPO* tables (IDoc ports), EDP13 (partner profiles) and RFCDES (destinations) are
system-wide configuration — they have no package or namespace to scope by. Ask before reading
them, report them as landscape context rather than as part of the scoped inventory, and skip them
entirely if the user declined deep evidence.
Evidence (all read-only)
Default to SAPRead(type="TABLE_QUERY") — data scope, structured where, no user-written SQL.
Always pass columns: omitting it emits SELECT *, which on configuration tables pulls fields
the dossier has no business reading.
| Ask | Call | columns |
|---|---|---|
| Interface objects in scope | TADIR, where PGMID = R3TR + OBJECT IN (…) + scope filter | OBJECT, OBJ_NAME, DEVCLASS |
| RFC-enabled custom FMs | TFDIR, where FMODE = 'R' + scope filter (see below) | FUNCNAME, PNAME |
| Custom IDoc basic types | EDBAS, scope filter on IDOCTYP | IDOCTYP, RELEASED |
| IDoc → port binding | EDP13 (outbound partner profiles) | MESTYP, IDOCTYP, RCVPOR |
| Port type per port | EDIPORT — the summary table for every port type; PORTTYP is domain EDI_PORTYP | PORT, PORTTYP |
| Destination behind an XML-HTTP port | EDIPOXH (LOGDES names the destination) | PORT, LOGDES |
| Outbound destinations | RFCDES — see the RFCTYPE codes below | RFCDEST, RFCTYPE only |
| Release contract state | SAPRead(type="API_STATE", name="<obj>", objectType="<type>") | — |
Never select RFCDES.RFCOPTIONS or RFCOPTION1…RFCOPTIONV. Those hold the packed connection
string including logon data; the dossier needs the destination name and type and nothing else.
The OBJECT IN (…) list is IWPR IWSV IWSG IWMO SRVD SRVB EVTB EVTO IDOC SICF HTTP.
Code tables (read from the system's own domains, not hard-coded assumptions):
EDIPORT.PORTTYP (domain EDI_PORTYP) | RFCDES.RFCTYPE |
|---|---|
0 CPI-C · 1 transactional RFC · 2 SAPcomm | 3 RFC to ABAP system (TCP/IP) · W RFC via WebSockets |
3 File · 6 XML File | H HTTP to ABAP system · G HTTP to external server |
4 Internet · 5 ABAP programming interface · 7 XML HTTP | T external program · I same-database · L reference · A application |
Do not treat H as the only HTTP destination — outbound integrations to non-SAP endpoints are
type G, which is exactly the case that matters most here.
One query per prefix. TABLE_QUERY ANDs every where entry, so two LIKE conditions on the
same field match nothing — run Z%, Y% and each namespace separately and union client-side.
Results are capped at 10,000 rows: a partition returning exactly 10,000 must be reported as
truncated, not counted as complete. The type census is a count over the rows you fetched.
Scoping TFDIR. A function module's name does not encode its package, so FUNCNAME LIKE only
works for a name-prefix scope. For a package dossier, resolve the package's FUGR objects first
and match TFDIR.PNAME against them before checking FMODE. Build that program name correctly:
the namespace comes first, so function group /NS/FOO has main program /NS/SAPLFOO — not
SAPL/NS/FOO. Only a non-namespaced group ZFOO gives SAPLZFOO. Getting this backwards silently
returns zero rows for every namespaced group.
Only if the user chose deep evidence and free SQL is enabled, SAPQuery can do the census in one
grouped statement: SELECT object, COUNT( * ) AS cnt FROM tadir WHERE pgmid = 'R3TR' AND obj_name LIKE 'Z%' GROUP BY object ORDER BY cnt DESCENDING — substituting the resolved scope for 'Z%'.
This is an optimization, never a requirement.
The two gates are independent and neither implies the other — SAPQuery needs sql scope and
SAP_ALLOW_FREE_SQL (the tool is not even registered without it); TABLE_QUERY needs data scope
and SAP_ALLOW_DATA_PREVIEW. Instances exist with free SQL on and data preview off, and vice versa.
If neither is available there is no table-based fallback: tadir_lookup does not help, because
source="db"/"both" escalate to sql scope themselves and it resolves exact names rather than
discovering objects by type. Do this instead — SAPRead(type="DEVC") for each package in scope and
an ordinary SAPSearch object search per type, both best-effort — then mark the TADIR census,
legacy SEGW types, and all RFC/IDoc/destination coverage as unavailable. Do not guess.
One gotcha: SAPRead(type="DEVC") omits legacy SEGW types, so use TADIR for those (or
tadir_lookup, which needs sql scope and exact names). And supported contracts are per object
type (an SRVD exposes C0 only), so never report a single system-wide "share at C2".
Levels (SAP Note 3690029)
Abridged to what an ABAP system exposes. The note also covers BW extractors, SLT, Delta Share and data products — out of ARC-1's reach, so list those as evidence gaps rather than omitting them.
| Technology | Level | ARC-1 evidence |
|---|---|---|
| Eventing via RAP (AMQP/MQTT) | A | TADIR EVTB / EVTO; SAPRead(type="EVTB") |
| OData via RAP service binding; CDS via service binding | A | TADIR SRVB + SRVD |
| HTTP(S) | A | TADIR SICF / HTTP (custom ICF nodes) |
| Web services via SOA Manager | A | not ADT-visible — confirm in SOAMANAGER |
| OData via SAP Gateway Service Builder (SEGW) | B | TADIR IWPR IWSV IWSG IWMO |
| BAPI via RFC; RFC (CPI-C); WebSocket RFC | B | TFDIR.FMODE = 'R'; RFCDES.RFCTYPE = '3' |
| IDoc via HTTPS | B | EDP13 → EDIPORT.PORTTYP = 7 plus TLS confirmed on its destination |
| IDoc via RFC | C | EDP13 → EDIPORT.PORTTYP = 1 |
| ABAP proxy via XI | C | not covered here — no ADT evidence; check SPROXY / SXMB config |
| Flat file | D | SAPSearch(searchType="source_code") for OPEN DATASET |
| FTP | D | source_code search for FTP_CONNECT / FTP_COMMAND |
| SFTP, JDBC/ODBC | D | not ABAP-detectable — external tooling; ask, do not infer |
| RFC (ODP) | Forbidden | prohibited by the API policy (SAP Note 3255746) — flag on sight |
IDoc levels need the port, and the port needs the partner profile. EDBAS lists basic types and
EDIPORT lists ports, but neither links them — the outbound partner profile (EDP13) carries the
RCVPOR that binds a message/basic type to its receiver port. Read the type from
EDIPORT.PORTTYP, not from EDIPO.PORTTYP (verified empty on a live system that had a working
port) and not by guessing which EDIPO* table holds the row — EDIPOF is the ABAP programming
interface, not a file port. Without the full EDP13 → EDIPORT join, report IDocs as B/C
indeterminate; never count them into a level.
PORTTYP = 7 proves XML-over-HTTP, not HTTPS. The port only names a destination
(EDIPOXH.LOGDES); TLS is configured on that destination — commonly an RFCTYPE = 'G' entry — and
its SSL setting lives inside the RFCDES connection blob this skill refuses to read. So treat
XML-HTTP ports as candidate Level B and ask the user to confirm SSL in SM59 for that destination.
Do not infer TLS from the port, and do not parse RFCOPTIONS to find out.
source_code search needs SAP_BASIS 7.51+. On older ECC systems it is unavailable, so a clean
Level-D result there means "not searched", not "not present" — record it as an evidence gap.
The note rates the technology, and says the level for a given scenario is use-case dependent. Report the level as SAP's default for that technology, not as a verdict on the interface.
Output
Count interfaces, not artifacts. One integration is usually several objects: a RAP service is an
SRVD and an SRVB; an IDoc scenario is a basic type and a partner profile and a port; an
RFC interface is a function module and possibly a destination. Collapse each into one interface
record — { id, technology, level, evidence[] } — and let the level distribution count those
records. Report raw artifact counts separately and label them as such; never add the two together.
Then add: the integration-technology level distribution (count of interface records per level),
the modernization candidates ranked B→A and C→B, and any Forbidden hit first. Do not label the
distribution an upgrade-stability metric — Note 3690029 deliberately excludes upgrade stability from
the level model because it depends on the underlying ABAP object's release state. Report that
separately from API_STATE and the Business Accelerator Hub. The common finding is SEGW/Gateway V2
(B) alongside RAP V4 (A) — hand those to migrate-segw-to-rap. The other standard move is
IDoc via RFC (C) → RAP business events (A).
When To Escalate
Use optional modes only when the user asks or the scope makes chat output impractical.
| User asks for | Do this |
|---|---|
| "save it", "share it", "dossier", "client report" | Create docs/migration-dossiers/<scope>/<date>/ with report.md and optional inventory.csv |
| "HTML", "PDF", "dashboard" | Generate a self-contained report.html; mention it can be printed to PDF |
| "reviewed", "consultant validation", "not AI-only" | Create draft cards and include only validated/corrected cards in the final report |
| "graph", "visualize", "dependency map" | Generate a bounded Mermaid graph for the top risk/high-fanout objects |
| "deep ECC", "user exits", "BAdIs", "standard modifications" | Use deep evidence from references/auditor-patterns.md; only use SAPQuery when allowed |
| "interfaces", "integration", "RFC/IDoc/OData inventory", "clean core integration" | Run the Integration Interfaces section |
| "successor API", "released API", "what replaces this" | Use SAP Docs MCP sap_get_object_details, then search/fetch for guidance if needed |
| "will this syntax work on release X" | Use SAP Docs MCP abap_feature_matrix plus search with the right ABAP flavor |
| "fix this" | Switch to migrate-custom-code for selected findings; this skill should not mass-remediate |
Output Shape
For chat output, keep it short:
Migration Dossier - <scope>
Scope: <n> objects, <types>, <packages>
Evidence: ATC=<variant/default>, docs=<SAP Docs MCP/unavailable>, usage=<SCMON/SUSG/unavailable>, clean-core=<source>, dependencies=<source>
Summary:
- <1-3 lines>
Priority objects:
| Object | Why it matters | Suggested action |
Retirement candidates:
| Object | Evidence | Caveat |
Main risks:
- <ATC/Clean Core/standard modification themes>
Evidence gaps:
- <missing usage data, skipped objects, dynamic calls, unavailable variants>
Next step:
- <one recommendation>
For file output, keep the default artifact set small:
docs/migration-dossiers/<scope>/<date>/
report.md
inventory.csv
methodology.md
Add report.html, cards.jsonl, reviews.jsonl, graph.mmd, or dashboard.html only when requested.
Review Rules
Use a human review gate only for customer-facing or decision-grade reports.
Statuses:
ai_draft | validated | corrected | skipped | ai_error
Classifications:
REMOVE | KEEP | ADAPT | COVERED_BY_STANDARD | UNDETERMINED
Keep these separate from the decision:
extensibilityLevel: A | B | C | D | unknown # Note 3578329 — which SAP APIs the code calls
integrationLevel: A | B | C | D | FORBIDDEN | indeterminate # Note 3690029 — interface technology
usageStatus: USED | LIKELY_UNUSED | UNUSED | INDETERMINATE
The two levels are independent axes and must never be merged into a single cleanCoreLevel. Most
cards carry only one of them: code objects get extensibilityLevel, interface records get
integrationLevel. indeterminate is the correct value for an IDoc whose port could not be
resolved — do not round it to B or C.
Final reviewed reports must exclude ai_draft cards unless explicitly labeled as drafts.
Safety
- Do not run unscoped system-wide extraction.
- Do not use
SAPQueryunless free SQL is enabled and the user chose deep evidence. - Do not treat zero ATC findings as clean if the object is
$TMPor ATC skipped it. - Do not delete, update, activate, or transport objects from this skill.
- Do not publish AI-only assessments as final decisions unless explicitly labeled draft.
- State evidence gaps plainly instead of filling them with assumptions.
SAP Object Documenter
Produce stable, package-scoped documentation for custom ABAP objects — classifies each by style (Classic / Modern / Mixed), summarizes purpose and dependencies, and outputs Markdown suitable for a repo wiki or onboarding doc.
This skill complements explain-abap-code which targets a single object interactively. Use this one when you want written docs for many objects at once — e.g., to seed a docs/ folder during onboarding, or to generate knowledge-transfer material before a team handoff.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Include | Z*, Y*, customer-namespace | Customer code only |
| Depth | 1 (direct dependencies only) | Keep docs readable; don't drown in transitive graph |
| Style classification | Yes | Free signal — just ask SAPLint |
| Per-object section length | ~30–60 lines Markdown | Enough to be useful, not so long it's unread |
| Output format | Markdown file(s) | Portable, fits any wiki |
Input
The user provides one of:
- Package (e.g.,
Z_SALES_EXTENSIONS) — document every custom object in it - Object list — comma-separated (e.g.,
ZCL_SALES_HANDLER, ZR_POSTING_JOB) - Type + prefix — e.g., "document all Z* classes" → runs
SAPSearch(query="Z*", objectType="CLAS")
And optionally:
- Output path — default:
docs/custom-code/<package_or_group>.md - One file or one-per-object — default: one file with per-object sections, unless >30 objects in which case one-per-object
If the scope would produce >100 objects, stop and ask the user to narrow it — documentation nobody reads is worse than no documentation.
Step 1: Enumerate Scope
1a. Package path
SAPRead(type="DEVC", name="<package>")
1b. Object-list path
Resolve each:
SAPSearch(query="<name>")
Filter to document-worthy types: CLAS, INTF, FUGR, PROG, DDLS, BDEF, SRVD, TABL. Skip generated proxies, transport objects, and test include classes.
Step 2: For Each Object — Read Source + Metadata
Run these in parallel for each object:
SAPRead(type="<type>", name="<name>") # Source
SAPContext(type="<type>", name="<name>", depth=1) # Dependencies (CLAS/INTF/PROG/FUNC/DDLS only; BTP: CLAS/INTF/DDLS)
For object types SAPContext doesn't support (FUGR, BDEF, SRVD, TABL, DOMA, DTEL), skip the dependency call and list the "obvious" callers/dependencies by regex-scanning the source for CL_*, IF_*, SAP* and CALL FUNCTION '...'. Note the degraded confidence in the "Dependencies" section.
For classes, also:
SAPRead(type="CLAS", name="<name>", method="*") # Method listing with signatures
For CDS views, also:
SAPRead(type="DDLS", name="<name>", include="elements") # Field list
Step 3: Classify ABAP Style (Classes + Programs only)
SAPLint(action="lint", name="<name>")
(Pass source=<source> instead of name if you already have the source in memory — avoids a second fetch.)
Interpret the lint findings:
| Signals of Modern ABAP | Signals of Classic ABAP |
|---|---|
Uses CDS, RAP, inline declarations, NEW, REDUCE, CORRESPONDING | Uses FORM/ENDFORM, TABLES statements, OCCURS |
No SELECT *, has ORDER BY, bulk operations | Line-by-line SELECT SINGLE in loops, SELECT * |
| Classes with test classes, uses interfaces for DI | Function modules with global state |
No MOVE-CORRESPONDING, uses CORRESPONDING OF | Heavy PERFORM chains |
Classify as:
- Modern — mostly modern patterns, cloud-ready style
- Classic — mostly classic patterns, pre-7.40 feel
- Mixed — both present (often: modern wrapper around classic guts)
If SAPLint fails or object isn't lintable (e.g., CDS view, table), skip this section.
Step 4: (Optional) Business-Context Lookup via mcp-sap-docs
For objects whose name or structure references an SAP app component (FI, SD, MM, etc.), enrich with component context:
search("<component_code> application component")
Example: ZCL_FI_GL_POSTING → search "FI-GL general ledger" to get the SAP application-component description for the doc header.
Skip this step if the object name gives no hint.
Step 5: Write the Markdown
5a. One-file structure (≤30 objects)
# <Package or group name> — Custom Code Documentation
_Generated <date> via sap-object-documenter skill on system <SID>._
## Overview
| Object | Type | Style | Purpose (1 line) |
|---|---|---|---|
| ZCL_SALES_HANDLER | CLAS | Modern | Behavior implementation for sales order RAP service |
| ZR_OLD_POSTING | PROG | Classic | Nightly batch for legacy FI posting |
| ...
## Objects
### ZCL_SALES_HANDLER
- **Type:** CLAS
- **Package:** Z_SALES_EXTENSIONS
- **Style:** Modern (uses RAP, inline decls, no SELECT *)
- **Purpose:** Handle validations and determinations for the Sales Order RAP business object.
**Public API**
- `validate_credit_limit( i_order )` — checks customer credit limit before save
- `determine_currency( c_order )` — defaults currency from sales org
**Dependencies**
- ZI_SALESORDER (CDS — root entity)
- CL_SALV_TABLE (A — released ALV class)
- ZCL_CREDIT_SERVICE (Z — custom credit service wrapper)
**Notes**
- No direct DB access; routes everything through the RAP entity.
- Tests: `ZCL_SALES_HANDLER_UT` (present, 8 test methods).
---
### ZR_OLD_POSTING
...
5b. One-file-per-object structure (>30 objects)
Create docs/custom-code/<package>/README.md with the overview table (linking to each file) plus one <object_name>.md per object with the same sections as above.
5c. Header per object (canonical fields)
- **Type:** <TADIR type>
- **Package:** <package>
- **Style:** Modern | Classic | Mixed | n/a
- **Purpose:** <one-sentence summary>
- **Last change:** <SAPRead VERSIONS — most recent timestamp + user>
- **Current transport:** <SAPTransport action="history" — current lock request, or "unlocked"; candidates are assignment choices, not history>
The "Last change" + "Current transport" lines come from ARC-1's revision and current-assignment APIs.
Complete transport history is not available from the legacy history action.
Step 6: Write to Disk + Report
Use the local file system (Write tool) to emit the Markdown file(s). Return a short summary:
Wrote 42 object docs to docs/custom-code/Z_SALES_EXTENSIONS/
12 Modern | 18 Classic | 8 Mixed | 4 n/a (CDS/tables)
Longest objects (may need deeper docs):
ZCL_SALES_HANDLER (847 lines, 14 methods)
ZR_OLD_POSTING (1,204 lines)
...
Follow-up Options
- "Want to expand any of these into deeper explanations?" (→ explain-abap-code)
- "Want to check clean-core readiness for this package?" (→ sap-clean-core-atc)
- "Want to prune the dead ones first?" (→ sap-unused-code)
- "Want to package documentation, usage, ATC, and review cards into a migration dossier?" (→ sap-migration-dossier)
Error Handling
| Error | Cause | Fix |
|---|---|---|
| Object not found | Wrong name or deleted | Log and skip; continue with rest |
| SAPContext fails | Unsupported type | Manually list imports via regex scan of source |
| SAPLint fails | No source (table, CDS), unsupported syntax | Skip style classification for that object |
| Source is empty | Generated proxy or stub | Note "no source available" in doc, still emit other metadata |
| Output path exists | File collision | Add timestamp suffix or ask user |
| >100 objects in scope | Doc would be unreadable | Stop and ask user to narrow scope |
Caveats
What this skill does NOT do
- No code generation — pure read + summarize.
- No English translation of business logic — the "Purpose" line is derived from naming, class header comments, and test-class names. If those are missing, it says so.
- Not a substitute for good code comments — the output is only as good as the source naming.
- No cross-object consolidation — each object is documented independently. Package-level architecture description is out of scope.
When to Use This Skill
- Onboarding new developers to a custom-code package
- Before a consulting handoff — capture institutional knowledge as docs
- Pre-migration documentation (snapshot what exists before rewriting)
- Compliance / audit trail (some orgs require per-object documentation)
- Seeding a knowledge base / repo wiki
When NOT to Use This Skill
- For a single object — use explain-abap-code, faster and interactive.
- For SAP-shipped code — this is Z/Y-only; for SAP objects, use mcp-sap-docs directly.
- When code quality analysis is the goal — use migrate-custom-code.
SAP Transport Overview (system-wide)
A basis-/lead-oriented register of every open transport in the system: who owns what, how large each request is, and where the risks are — without ever pulling source or diffs. It's deliberately breadth-first and token-cheap, built on one call:
SAPTransport(action="list", summary=true, user="*", status="D")— every modifiable request, all users, withobjects[]omitted and anobjectCountkept. (On a busy system the full object-laden list is ~25K tokens; summary cuts it to a few KB — see ARC-1 PR #448.)
This is the breadth companion to sap-transport-review (which is depth — diffs of one transport's objects). Overview answers "what's open and risky across the landscape"; review answers "what exactly changed in this one." Don't diff here.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Users | all (user="*") | Basis cares about the whole system, not one developer |
| Status | modifiable (status="D") | Open/unreleased work; pass status="R" for released, "*" for both |
| Payload | summary=true | Inventory needs counts + headers, never source — keeps a 100-request list cheap |
| Diffs | never | That's sap-transport-review's job; this skill stays breadth-only |
| Grouping | by owner | The basis mental model: "whose requests, how many, how big" |
Input
Optional narrowing — apply if given, else default to the whole system:
- Owner / user — one developer's open requests.
- Status —
D(default),R(released),*(all). - Description / size / target filter — e.g. "matching 'migration'", "more than 20 entries", or "without a target". The current transport payload has no age or object-package field, so do not offer age/package filtering without a separate authoritative data source.
Scope guard: the system-wide list can be hundreds of requests. Always start with summary=true.
If it's still large, aggregate (counts per owner, top-N by objectCount) and offer to filter — never
expand every request's object list unprompted.
Step 1: The register (cheap, always)
SAPTransport(action="list", summary=true, user="*", status="D")
Returns one row per request: id, description, owner, status, target/targetDesc,
objectCount (+ per-task counts). That alone answers "what's open and how big" for the whole system.
Step 2: Expand only what matters (still no diffs)
For requests the user flags (or the suspicious ones from Step 3), pull the full object list:
SAPTransport(action="get", id="<id>")
This lists CTS entries (pgmid, type, name, wbtype, locked) — the contents, not source or
package metadata. Only get the handful in focus; do not get the whole system.
Step 3: Risk / health flags (the basis value)
These are what an overview is for. Derive from the data already gathered:
- Confirmed exact overlap — after explicitly expanding the in-scope requests, the same exact CTS
key (
pgmid,type,name) occurs in two manifests. This can create import-order risk. Raw-key intersection is conservative: it can miss conceptual overlaps represented once asR3TRand once asLIMU/language subobjects, so label the result "exact CTS-key overlap", not exhaustive conflict detection. - Empty requests (
objectCount0) — cleanup candidates (delete or release). - Explicitly locked objects (
locked: truefromget) — may block other developers. On older releasestm:lock_statuscan be absent, solocked: falsedoes not prove that an entry is unlocked. - No target (
targetempty) — a local request that cannot be transported onward (often a mistake for work meant to ship).
SAPTransport(action="history", type=…, name=…) is current assignment status, despite the legacy
action name: relatedTransports contains at most the current lock request, while
candidateTransports are requests the object could be assigned to. Candidates do not contain the
object and are not conflict/history evidence. Full historical membership requires E071/E070 access;
the standard ADT endpoints used here do not provide it.
Do not infer $TMP from a transport manifest: CTS entries do not expose package, and local-package
objects normally are not transport contents. Resolve package separately before making such a claim.
Step 4: Report
# Open transports — <SID> (<N> requests, <M> objects, <K> owners)
## By owner
| Owner | Requests | Objects | Notable |
|---|---|---|---|
| MARIAN | 6 | 41 | 1 empty, 1 local request |
| ANNA | 2 | 8 | |
## Register
| Request | Owner | Description | Objects | Target | Flags |
|---|---|---|---|---|---|
| A4HK900123 | MARIAN | Sales order RAP | 12 | LOCAL | ⚠ no target — won't ship |
| A4HK900200 | ANNA | Pricing fix | 3 | C11 | ⚠ ZCL_PRICE also in A4HK900123 |
## Needs attention
- ⚠ Exact CTS key R3TR/CLAS/ZCL_PRICE is in 2 expanded requests (A4HK900123, A4HK900200) → possible import-order conflict; sequence or consolidate.
- ⚠ A4HK900155 (MARIAN) is empty → delete or release.
- ⚠ A4HK900123 has no target → local request; confirm it is not intended for downstream import.
Write to disk only if asked; otherwise return inline.
Error Handling
| Error | Cause | Fix |
|---|---|---|
list returns very many requests | Busy system | Keep summary=true; aggregate per owner + top-N by size; offer to filter |
user="*" returns only my requests | Backend ignored the unfiltered query / scope limits | Confirm the SAP user may see others' requests (S_TRANSPRT); some systems restrict cross-user listing |
get slow across many requests | Expanding too much | Only expand the flagged/in-focus requests, never the whole system |
history returns many candidates | Candidates are assignment choices, not containing requests | Do not use them as history/overlap evidence; compare explicitly expanded manifests |
| Need released requests too | Default is D only | Re-run list with status="R" or status="*" |
When to use this skill
- Basis / release manager: "what's open across the system, and what's risky to import?"
- Team lead: "what is everyone working on right now?" / backlog and cleanup review.
- Pre-import / pre-go-live: find object overlaps and local-only requests before a transport wave.
When NOT to use this skill
- What exactly changed in a request (source diffs) → sap-transport-review.
- One object's complete history ("which transports touched ZCL_X") → not available from the standard ADT history action; use an authorized E071/E070 data workflow or an external CTS report.
- One object's current lock/assignment status →
SAPTransport(action="history", type=…, name=…). - Cross-system (is DEV ahead of QAS) → out of scope: ARC-1 binds one system per instance; run the CLI against each system and compare.
Follow-up Options
- "Review the actual changes in one of these?" → sap-transport-review.
- "Release the ready ones?" →
SAPTransport(action="release")/release_recursive. - "Clean up the empty ones?" →
SAPTransport(action="delete").
SAP Transport / Change Review
Answer "what actually changed?" for a transport or for your in-flight (unactivated) work, as a reviewable report: a per-object unified diff plus risk flags — not a wall of full source.
It leans on two token-cheap ARC-1 primitives so a review of a 30-object transport costs a handful of small diffs instead of 60 full-source reads:
SAPTransport(action="list", summary=true)— scan many open transports cheaply (objects omitted,objectCountkept), then drill into one.SAPRead(action="diff", from=…, to=…)— server-side unified diff per object; the response is just the hunks.
Complements explain-abap-code (deep single-object understanding) and sap-object-documenter (written docs for a package). This skill is about delta — what moved between two points in time — for code review, hand-off, or a pre-release gate.
Pick the mode (who's asking)
| You are… | Scope | What the skill does |
|---|---|---|
| Reviewing a transport (senior dev / approver) | one transport id | Diff every safely resolved source object, label the version coverage, and add impact/quality checks only when requested or risk-triggered. The chat / whole-transport twin of Eclipse ADT 3.6's "Object Changes" tab (same source-diff coverage boundary). |
| Checking your own recent work (dev) | your modifiable transports | "What have I changed since my last release?" — diff each object's last-released version → current. Light: skip impact/ATC unless asked. |
For a system-wide inventory of every open transport (basis: who has what open, how big, conflicts — no diffs) that's a different job → sap-transport-overview.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Transport scope | current user, modifiable (status="D") | The work in progress, not released history |
| Overview first | summary=true when listing | Cheap scan before pulling any object list in full |
| Diff direction (in-flight) | from="active", to="inactive" | Exact for pending, unactivated source only; it does not reconstruct changes already activated in an open request |
| Diffable types | PROG, CLAS, INTF, FUNC, FUGR, INCL, DDLS, DCLS, BDEF, SRVD, DDLX, TABL | The plain-text source types action="diff" supports |
| Object-diff cap | ~40 | Above that, summarize counts and ask which to expand |
| Impact | On for changed CDS/RAP objects in a risk-focused review; otherwise opt-in | Focus the extra reads where dependency risk exists |
| ATC | Opt-in (+atc) or clearly risk-triggered; bounded to changed objects | ATC is workload-producing and must not fan out silently across a large request |
Input
The user provides one of:
- A transport id (e.g.
A4HK900123) — review everything in that request. - "my pending changes" / "before I activate" — review unactivated drafts (active → inactive).
- An object list or package — review those objects' pending changes.
- Nothing specific ("what changed") — list the user's modifiable transports (summary) and ask which one, or default to pending drafts.
Optional: +impact (who consumes the changed CDS/RAP), +atc (new quality findings), output path for a Markdown file.
Scope guard: if the selected set exceeds ~40 diffable objects, show the object table with +/-
counts only and ask which objects (or which task) to expand into full diffs. A review nobody reads is
worse than no review.
Step 1: Resolve scope
- Transport id given →
SAPTransport(action="get", id="<id>")→ thetasks[].objects[]list. - "what changed" / pick a transport →
SAPTransport(action="list", summary=true)→ a cheap table (id,description,owner,status,objectCount). Present it, let the user pick, thengetthat one. - Pending changes / package → enumerate the objects the user touched (the transport's object list, or the objects in the named package). No transport id needed for the diff itself.
Step 2: Normalize CTS entries, then classify
SAPTransport get returns CTS identities, not guaranteed SAPRead inputs. Each entry has
pgmid, CTS type, name, and wbtype; real transports may also contain subobjects such as
LIMU/METH, LIMU/REPS, language entries, and package/metadata entries.
Before diffing:
- Flatten
tasks[].objects[], but keep the task id and original CTS key for the report. - Treat supported
R3TRentries (R3TR/CLAS,R3TR/DDLS, …) as direct repository objects and deduplicate exact repeats. - Never pass
pgmid(LIMU,LANG), a CTS subtype (METH,REPS), orwbtype(CLAS/OM,PROG/I, …) toSAPRead(type=…). - Fold a subobject into a direct parent entry only when the parent is unambiguous. If the response
exposes only the subobject, report it as
parent resolution unavailablerather than guessing a class/include name. This is a coverage limitation, not evidence that nothing changed. - Count both raw CTS entries and unique resolved repository objects; do not present entry count as a unique-object count.
Then split the resolved repository objects into:
- Diffable (source types above) → these get a real diff in Step 3.
- Metadata-only (SRVB, G4BA, SUSH, DOMA, DTEL, MSAG, VIEW, ENHO, AUTH, DEVC, server-driven, …) →
action="diff"returns "not supported" (their read is parsed metadata/XML, not plain-text source). This is exactly the boundary SAP's own Eclipse ADT 3.6 "Object Changes" has — it prints "Feature not supported for object …" for these same types (e.g. SRVB). Don't try to diff them. For a thorough review, still read the object's metadata (e.g.SAPRead(type="SRVB", name=…)) so the report names what the object is and that it's in the change set — just without a source diff.
Step 3: Diff each object — pick from/to by intent
Run these in parallel (each returns only hunks):
SAPRead(type="<type>", name="<name>", action="diff", from="<from>", to="<to>")
Choose the sides by what the user is reviewing:
| Intent | from → to | Notes |
|---|---|---|
| Pending draft ("what I'm about to activate") | active → inactive | Exact pending-source diff. No draft means "no pending source", not "the open transport made no changes". |
| Since the latest released snapshot | <latest released revision id> → active (or inactive if still draft) | Captures all changes since that release; it may combine multiple open requests and must be labelled that way. Confirm revision ordering/timestamps rather than assuming feed order. |
| Released transport ("what did this TR change") | <revision immediately before TR> → <revision tagged with TR> | Compare the transport's own released snapshot, not today's active source. If the matching snapshot/predecessor is ambiguous or absent, report the baseline gap. |
| Specific revisions | <id|uri> → <id|uri|active> | From a VERSIONS response. |
Snapshot-sparsity reality (important): ABAP cuts a version snapshot only when a transport is released. So for an open/unreleased transport, objects usually have just the active version (+ maybe an inactive draft) — there is no "before" revision to diff against. Handle it honestly:
- For each resolved object, query
SAPRead(type="VERSIONS", name=…, objectType=…)where supported. - For a released request, locate the revision tagged with that request and its immediate predecessor.
If either cannot be established, do not substitute current
activesource for an old transport. - For an open request, use
active→inactiveonly for the pending portion. A prior released revision →activecomparison is useful, but label it "since released snapshot" because it can include other open requests. - If there is no inactive delta and no trustworthy pair of snapshots, report
baseline unavailable. Do not call it an add unless independent object metadata proves creation in this request.
The report must state its coverage: pending draft, released snapshot, since released snapshot (may span requests), or baseline unavailable.
Step 4 (optional): impact + quality — only when asked or the change is risky
- Impact (a changed
DDLS/BDEF/SRVDcan break consumers):SAPContext(action="impact", type="DDLS", name="<view>")→ projection views, BDEFs, service defs/bindings, ABAP consumers that depend on it. - Quality: when the user requests
+atc, or risk justifies it, runSAPDiagnose(action="atc", ...)only for the bounded changed set. UseSAPLint(action="lint", name=…)for a cheaper local pass. - Pre-release validity: use the read-only
SAPDiagnose action="syntax"check for unactivated work.SAPActivatemutates system state; run it only when the user explicitly asks to activate.
Step 5: Write the report
# Change review — <transport id or "pending drafts"> on <SID>
_<owner> · <status> · <description>_
_Coverage: <pending draft | released snapshot | since released snapshot | baseline unavailable>_
## Summary
| Object | Type | Change | +/− | Flags |
|---|---|---|---|---|
| ZCL_ORDER | CLAS | changed | +12 −3 | |
| ZI_ORDER | DDLS | changed | +4 −0 | impacts 3 consumers |
| ZNEW_REPORT | PROG | unknown | — | baseline unavailable |
| ZSTATUS | DOMA | changed | — | metadata — no source diff |
| <CTS subobject> | LIMU/METH | unresolved | — | parent resolution unavailable |
## Diffs
### ZCL_ORDER (CLAS) active → inactive (+12 −3)
```diff
<the unified-diff hunks from SAPRead action="diff">
…one block per diffable object…
Risk flags
- ⚠ ZI_ORDER (DDLS) has 3 downstream consumers — re-activation order matters (see impact).
- ⚠ ZCL_BP appears in two explicitly expanded request manifests; current lock holder is A4HK900123.
- ⚠ A4HK900123 has no target — this is a local request and cannot be imported onward.
Verdict
<2–3 lines: what this change set does, what to review first, what's risky / not yet activated.>
Write to disk (default `docs/reviews/transport-<id>-<date>.md`) only if asked; otherwise return inline.
## Error Handling
| Error | Cause | Fix |
|---|---|---|
| `action="diff"` → "not supported for type X" | Metadata type (DOMA/DTEL/MSAG/SRVB/VIEW/…) | Expected — list it as "metadata — no source diff", don't diff |
| "No differences between active and inactive" | No unactivated draft for that object | Report "no pending source"; do not infer that the open request made no activated changes |
| "Revision-id diff is not available for type X" | FUGR/DDLX have no revisions feed | Use `active`/`inactive` or a full `/sap/bc/adt/` URI instead of a bare id |
| VERSIONS returns 1 revision | Snapshot only cut on release (sparsity) | Use active→inactive only for a real pending draft; otherwise report `baseline unavailable` |
| Transport entry is `LIMU/*`, `LANG/*`, or only has a slash `wbtype` | CTS identity is not a `SAPRead` type | Fold into an unambiguous parent entry or report `parent resolution unavailable`; never guess |
| Transport `get` 404 | Wrong id / already deleted | Re-list with `summary=true` and confirm the id |
| >40 objects in scope | Review too large to read | Show the `+/-` table, ask which task/objects to expand |
## When to use this skill
- Pre-release / pre-activation gate — "show me everything I'm about to ship."
- Code review of a colleague's transport without leaving the chat — the headless / pasteable / whole-transport-at-once counterpart to Eclipse ADT 3.6's "Object Changes" tab (same per-object diffs, same coverage boundary).
- Hand-off / audit — a written delta of a change set.
- "What changed after my last request / since my last release?" (since-last-release mode).
- "I've been editing for an hour — what have I actually changed?" (pending-drafts mode).
## When NOT to use this skill
- **System-wide inventory of every open transport** (basis: who has what open, sizes, conflicts — no diffs) → [sap-transport-overview](../sap-transport-overview/SKILL.md). This skill is depth-on-one-transport; that one is breadth-across-the-system.
- **Understanding one object deeply** → [explain-abap-code](../explain-abap-code/SKILL.md).
- **Documenting a whole package** (not a delta) → [sap-object-documenter](../sap-object-documenter/SKILL.md).
- **Across multiple systems** (DEV vs QAS source compare) → out of scope here: ARC-1 binds to one system
per instance. Do a cross-system review by running the ARC-1 CLI against each system (`arc1-cli call
SAPRead … --url <sys>`) and diffing the two outputs — a separate orchestration, not this skill.
## Follow-up Options
- "Activate / release this once it looks right?" → `SAPActivate`, then `SAPTransport(action="release")`.
- "Who breaks if I change this CDS?" → `SAPContext(action="impact")` (or re-run with `+impact`).
- "Document these objects properly?" → [sap-object-documenter](../sap-object-documenter/SKILL.md).
- "Clean-core readiness of the changed objects?" → [sap-clean-core-atc](../sap-clean-core-atc/SKILL.md).
SAP Unused Code Discovery
Find Z/Y custom objects that are never called at runtime — the prerequisite for any credible custom-code retirement project. Combines runtime usage data from SAP's call monitor (SCMON) with static where-used analysis to classify each object as UNUSED / LIKELY_UNUSED / USED / INDETERMINATE.
⚠ Required: scope and intent
This skill refuses to run without a filter. A "list all unused code" report across an ECC system returns tens of thousands of rows and is useless. The user must provide at least one of:
- Package (e.g.,
Z_FI_CUSTOM) — analyze only objects in this package - Namespace prefix (e.g.,
Z_SALES_*,/ACME/*) — only objects matching the pattern - Object list — comma-separated names to check
- Intent statement — e.g., "find Z reports in FI-GL that haven't run in 90 days" — narrow by purpose
If none is given, ask. Example clarifying questions:
Which package or namespace do you want to audit? E.g., "the Z_REPORTING package", "all Z* starting with Z_FI_", or "these 15 reports I'm planning to delete".
Why this is harder than it looks (read before proposing a plan)
SAP has two relevant monitoring systems. Understand which you're working with:
| System | What it is | Where data lives | Latency | Data lifetime |
|---|---|---|---|---|
| SCMON (ABAP Call Monitor) | Raw per-call counters | SCMON_DATA + SCMON_PROG + SCMON_SUB + SCMON_RDATA tables | Real-time while active | ~7 days rolling |
| SUSG (Usage Statistics Generator) | Daily aggregation over SCMON | SUSG_DATA + SUSG_PROG + SUSG_RDATA + SUSG_SUB + SUSG_ADMIN tables (or CDS views SUSG_I_DATA, SUSG_I_RDATA, SUSG_I_ODATA) | Depends on batch schedule (default ~02:30 daily) | Months/years |
Key constraint: SCMON auto-deactivates when record threshold is hit (SCMON_CONF_SET_MAX_NUM_SLICES). SUSG refuses to aggregate if SCMON was inactive during the window. On dev/test systems this breaks the pipeline constantly.
Three Options (pick based on system state)
Option A (preferred) — Direct SCMON table join via ARC-1
Works immediately on any system where SCMON has ever been active, regardless of whether SUSG aggregation ran.
-- "Which programs actually ran?"
SELECT p~PROGNAME, p~OBJECT, p~OBJ_NAME, SUM( d~COUNTER ) AS EXECS
FROM SCMON_DATA AS d INNER JOIN SCMON_PROG AS p ON d~TRIGID = p~PROGID
WHERE <filter>
GROUP BY p~PROGNAME, p~OBJECT, p~OBJ_NAME
ORDER BY EXECS DESCENDING
-- "Which transactions/reports triggered anything?"
SELECT s~ROOTNAME, s~ROOTTYPE, SUM( d~COUNTER ) AS EXECS
FROM SCMON_DATA AS d INNER JOIN SCMON_SUB AS s ON d~SUBID = s~SUBID
GROUP BY s~ROOTNAME, s~ROOTTYPE
Column caveat (SAP naming is inverted):
SCMON_DATA.TRIGID→SCMON_PROG.PROGID(the executed program, despite the name)SCMON_DATA.SUBID→SCMON_SUB.SUBID(the trigger root, transaction/report that initiated)
Pros: No batch wait, no slice rotation dance, runs today. Cons: Limited retention window (~7 days); useless for "has this run in the last 6 months" questions.
Option B — Aggregated SUSG via CDS views
Use when the customer has SUSG properly scheduled (production systems usually do).
-- Same question, longer window
SELECT PROGNAME, OBJ_TYPE, OBJ_NAME, SUM( COUNTER ) AS EXECS, MAX( LAST_USED ) AS LAST_SEEN
FROM SUSG_I_DATA
WHERE <filter>
GROUP BY PROGNAME, OBJ_TYPE, OBJ_NAME
Pre-joined CDS view: SUSG_I_DATA, SUSG_I_RDATA, SUSG_I_ODATA. All have @AccessControl.authorizationCheck: #NOT_REQUIRED.
Pros: Longer history (months), pre-joined (simpler SQL), officially supported data. Cons: Requires SUSG batch to have run (0 rows in SUSG until it does); nothing works if SCMON was deactivated during the window.
Option C — Manual SUSG XML export (fallback only)
If the customer has already run transaction SUSG and exported the 5 XML files (ADMIN0001.xml, PROG0001.xml, DATA*.xml, RDATA*.xml, SUB0001.xml), the skill can parse those locally. This is the Kiro path and should be the last resort — it requires human action in SAP GUI and offline file handoff.
This skill does not bundle an XML parser. If the user insists on Option C, tell them to use Kiro's parse-susg.py or write a local Python script; ARC-1 won't do it.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Option selection | Probe SCMON activity first; use A if live data exists, else B | Most systems have one or the other |
| Output classification | UNUSED / LIKELY_UNUSED / USED / INDETERMINATE | Kiro's 4-way classification; useful for prioritization |
| Where-used check | Yes, for non-runtime-seen objects | Static references are a real signal |
| Reporting granularity | Per-object with counts; top-20 + summary | Full list available on request |
Prerequisites
Check these up front. If missing, stop and tell the user.
SAP_ALLOW_FREE_SQL=trueon the ARC-1 server (otherwiseSAPQueryis blocked — it runs FreeSQL). Ask admin if needed.- User has
S_TABU_NAMauthorization onSCMON_DATA,SCMON_PROG,SCMON_SUB,SCMON_RDATA(or the SUSG equivalents for Option B). - SCMON has been active at some point (Option A) OR SUSG aggregation has run (Option B). Probe with:
SAPQuery(sql="SELECT COUNT(*) AS CNT FROM SCMON_DATA")
SAPQuery(sql="SELECT COUNT(*) AS CNT FROM SUSG_I_DATA")
Zero rows in both → data collection hasn't happened. Point the user to the next section and stop.
If the customer has no SCMON/SUSG data yet
Tell them:
- SAP GUI: transaction
SCMON→ activate the monitor → let it run for N days (7 is a common minimum) - Transaction
SCMONLshows slice state;SCMONDshows raw data - For permanent data: schedule
SCMON_COLLECTas a daily job, thenSUSG_COLLECT_FROM_SCMONafter it - Re-run this skill once data is flowing
Step 1: Probe which option to use
Run the two COUNT queries above. Decision table:
| SCMON_DATA count | SUSG_I_DATA count | Use |
|---|---|---|
| > 0 | > 0 | A (fresher data, real-time) — but mention B is also available for longer history |
| > 0 | 0 | A (SUSG hasn't aggregated yet) |
| 0 | > 0 | B (SCMON expired; SUSG has history) |
| 0 | 0 | Stop. Tell user to activate SCMON; don't guess. |
Step 2: Enumerate the scope
Based on user's filter input:
2a. Package
SAPRead(type="DEVC", name="<package>")
Keep only objects of runtime types (PROG, CLAS, FUGR, FUNC) with Z/Y prefix. (Tables, CDS views, interfaces aren't "called at runtime" in a way SCMON/SUSG captures directly.)
2b. Namespace / prefix
SAPSearch takes a single objectType filter — call it once per runtime type and union the results:
SAPSearch(query="<prefix>*", objectType="PROG")
SAPSearch(query="<prefix>*", objectType="CLAS")
SAPSearch(query="<prefix>*", objectType="FUGR")
2c. Object list
Use names as given.
Call this set S (the candidate list).
Step 3: Query runtime usage
Option A (SCMON direct join)
Build a WHERE clause from set S. SAP FreeSQL has query length limits, so chunk if |S| > 100.
SELECT p~PROGNAME, p~OBJECT, p~OBJ_NAME, SUM( d~COUNTER ) AS EXECS
FROM SCMON_DATA AS d INNER JOIN SCMON_PROG AS p ON d~TRIGID = p~PROGID
WHERE p~OBJ_NAME IN ( 'ZCL_FOO', 'ZR_BAR', ... ) -- or p~OBJ_NAME LIKE 'Z_FI_%'
GROUP BY p~PROGNAME, p~OBJECT, p~OBJ_NAME
Also check trigger-side (some Z-objects run only as transactions/RFCs, never as inner callees):
SELECT s~ROOTNAME, s~ROOTTYPE, SUM( d~COUNTER ) AS EXECS
FROM SCMON_DATA AS d INNER JOIN SCMON_SUB AS s ON d~SUBID = s~SUBID
WHERE s~ROOTNAME IN ( ... )
Union the results. Build set U (runtime-used objects with counts).
Option B (SUSG)
SELECT PROGNAME, OBJ_TYPE, OBJ_NAME, SUM( COUNTER ) AS EXECS, MAX( LAST_USED ) AS LAST_SEEN
FROM SUSG_I_DATA
WHERE <scope filter>
GROUP BY PROGNAME, OBJ_TYPE, OBJ_NAME
Build set U with additional LAST_SEEN timestamp.
Step 4: Static where-used for objects not in U
For each object in S but not in U:
SAPNavigate(action="references", type="<type>", name="<name>")
(references is ARC-1's where-used action — it calls SAP's where-used API under the hood.)
Build set W (statically referenced objects — someone calls them in source, even if no one ran them in the observed window).
Step 5: Classify
Apply first-match-wins:
| Object in … | Classification | Meaning |
|---|---|---|
| U (runtime executed ≥ 1 time) | USED | Runs in production; keep |
| W (referenced in source, not in U) | LIKELY_UNUSED | Static callers exist but nothing exercised it in the observed window |
| Neither U nor W | UNUSED | Strong deletion candidate |
| S but object doesn't exist on system (e.g., SAPSearch couldn't resolve it) | INDETERMINATE | Manual review |
Step 6: Emit the report
6a. Headline
Unused Code Audit — <scope>
Data source: SCMON (2,843 rows, window: 2026-04-12 → 2026-04-19) ← Option A
— or —
Data source: SUSG (Aggregated 2026-01-01 → 2026-04-19, 128 days) ← Option B
Scope: 42 objects
USED: 18 (43%) — safe to keep
LIKELY_UNUSED: 12 (29%) — still has static callers; investigate
UNUSED: 10 (24%) — deletion candidates
INDETERMINATE: 2 (5%) — manual review
6b. UNUSED table (the deletion candidates)
Object Type Package Last change (TR)
ZR_OLD_FI_POSTING PROG Z_FI_CUSTOM 2024-02-15 (MARIAN / A4HK900042)
ZCL_LEGACY_HELPER CLAS Z_FI_CUSTOM 2023-11-03 (MARIAN / A4HK900031)
...
"Last change" comes from SAPRead(type="VERSIONS"). Old + unused = safest to delete.
6c. LIKELY_UNUSED table with caller hints
For each LIKELY_UNUSED object, show who references it:
ZCL_OLD_SALES_UTILS (CLAS)
Called by: ZR_SALES_JOB (PROG — also UNUSED — cascade delete)
ZCL_ACTIVE_HANDLER (CLAS — USED at runtime) ← blocks deletion
A LIKELY_UNUSED object whose callers are all UNUSED is transitively deletable. One active caller blocks deletion.
6d. Follow-up options
- "Want to see the static reference graph as a tree?" (→ chained
SAPNavigate where-used) - "Want to clean-core-check the USED objects before worrying about unused ones?" (→ sap-clean-core-atc)
- "Want documentation for the USED objects?" (→ sap-object-documenter)
- "Want to turn this into a reviewed S/4HANA migration dossier with HTML/CSV/graph outputs?" (→ sap-migration-dossier)
- "Want to start deleting UNUSED objects?" → Manual: this skill does not delete anything; the user does it via
SAPWriteor a transport
Error Handling
| Symptom | Root cause | Fix |
|---|---|---|
SCMON_DATA count = 0, SUSG_I_DATA count = 0 | Monitoring never activated | Stop; instruct user to activate SCMON (Step above) |
SCMON has data but all SLICEID=1 and SUSG is 0 | Slice hasn't rotated; SUSG can't aggregate open slices | Use Option A (direct), skip SUSG; or run SCMON_COLLECT_ALL via SA38 then SUSG_COLLECT_FROM_SCMON |
SUSG_LOG shows "SCMON not active" | SCMON auto-deactivated (record threshold hit) | Raise threshold via SCMON_CONF_SET_MAX_NUM_SLICES, reactivate SCMON, accept you lost one aggregation cycle |
SAP_ALLOW_FREE_SQL=false | Admin policy | Either get it relaxed, or fall back to SAPRead(type="TABLE_CONTENTS", name="SCMON_DATA", maxRows=…) (also blocked by SAP_ALLOW_DATA_PREVIEW=false; no joins either way) — badly degrades the report |
403 on SCMON_* / SUSG_* tables | Missing S_TABU_NAM auth | User needs auth assignment; document tables in request |
| Scope returns > 500 candidates | User's filter too broad | Refuse; ask user to narrow (a 500-object deletion list is not actionable) |
Caveats
What runtime data does NOT tell you
- Coverage gap: a report that runs every year-end won't appear in a week's worth of SCMON data. Always consider the observation window vs. the object's expected frequency.
- Dead-code-detection ≠ code elimination: an UNUSED object may be emergency/DR code, exam-period-only, or called by a scheduled job not active during the window. Cross-check with business owners before deletion.
- Dynamic calls:
CALL FUNCTION IN BACKGROUND,SUBMITwith dynamic program names, or CALL METHOD via RTTI may not attribute to the right PROGNAME in SCMON. Some false UNUSEDs are unavoidable.
What this skill does NOT do
- No deletion. Report only. Deletion must be a human decision, ideally via transport and CTS.
- No cross-system consolidation (DEV + QAS + PRD usage). That requires exports from each system; this skill reads one system at a time.
- No replacement suggestions for deprecated-but-used code. For that, use sap-clean-core-atc.
- No XML import (Option C). If the customer has SUSG XML dumps and nothing else, they need an offline parser.
When to Use This Skill
- Scoping a custom-code retirement project
- Before a migration — don't migrate what you don't use
- Post-project cleanup — removing code written for a feature that was rolled back
- License/compliance reviews requiring a dead-code inventory
- Combine with sap-clean-core-atc: migrate USED Level-A code, audit USED Level-C/D code, delete UNUSED code entirely
Setup ABAP Mirror
Create a local abapGit-style mirror of an SAP package or object set. Reads are authoritative from the SAP system; local files give you IDE context, git diff, and fast searching without round-tripping every time.
This skill works today with ARC-1's existing SAPRead + DEVC primitives. When dedicated abapGit export tooling lands in ARC-1, the skill can be simplified — the file layout it produces is the target format either way.
Smart Defaults (apply silently, do NOT ask)
| Setting | Default | Rationale |
|---|---|---|
| Mirror root | ./mirror/<SID>/src/<package>/ | Groups by system to support multi-system work |
| File naming | abapGit conventions | Standard; future-proof |
| Recurse sub-packages | Yes | Matches abapGit behaviour |
| Include test classes | Yes | Tests belong with the class |
| Include metadata XML | Skip for now | ARC-1 does not yet emit abapGit-format XML; source-only is useful and safe |
Input
One of the following scopes:
- Single object —
name+type(e.g.,ZCL_TRAVEL_HANDLER,CLAS) - Object list — array of
{ type, name }pairs - Package —
packagename; pulls everything inside
Optionally:
- Mirror root (default:
./mirror/<SID>/src/<package>/) - Skip test classes (default: include them)
Prerequisites
Before running, ensure system-info.md exists. If it doesn't:
→ Run the bootstrap-system-context skill first
The mirror header references SID, system type, and release from system-info.md.
Step 1: Resolve Scope Into An Object List
1a. For a package scope
SAPRead(type="DEVC", name="<PACKAGE>")
Returns [{ type, name, description, uri }, ...] where type is slash-form (CLAS/OC, DDLS/DF, PROG/P, DEVC/K, etc.).
For each DEVC/K entry (sub-package): recurse — call SAPRead(type="DEVC", name=<sub>) and append its contents.
Normalize slash-form types to the ARC-1 SAPRead short codes:
| Slash form | SAPRead type | abapGit extension |
|---|---|---|
CLAS/OC | CLAS | .clas.abap (+ .clas.testclasses.abap) |
INTF/OI | INTF | .intf.abap |
PROG/P | PROG | .prog.abap |
FUGR/F | FUGR | .fugr.abap (expanded includes) |
FUNC/FF | FUNC | .func.abap |
DDLS/DF | DDLS | .ddls.asddls |
DCLS/DL | DCLS | .dcls.asdcls |
DDLX/EX | DDLX | .ddlx.asddlxs |
BDEF/BO | BDEF | .bdef.asbdef |
SRVD/SRV | SRVD | .srvd.asrvd |
SRVB/SVB | SRVB | .srvb.xml |
TABL/DT | TABL | .tabl.xml |
STRU/DS | STRU | .stru.xml |
DOMA/DD | DOMA | .doma.xml |
DTEL/DE | DTEL | .dtel.xml |
MSAG/N | MSAG | .msag.xml |
ENHO/EO | ENHO | .enho.xml |
Skip types not in this table; log them in a skipped.md in the mirror root.
1b. For a single object or object list
Skip enumeration; proceed directly with the provided list.
Step 2: Read Each Object
For every resolved { type, name }:
SAPRead(type="<type>", name="<name>")
For classes, also fetch test classes (unless skipped):
SAPRead(type="CLAS", name="<name>", include="testclasses")
For function groups (on-prem only), expand includes:
SAPRead(type="FUGR", name="<name>", expand_includes=true)
For DDLS, CLAS (structured), DCLS, DDLX — the plain source form is sufficient for mirroring; richer structured forms are for reading, not storage.
Catch and continue on per-object errors — log failures in skipped.md with the error class (not-found / forbidden / not-released / connectivity) and move on.
Step 3: Write Files In abapGit Layout
Directory structure:
mirror/<SID>/
README.md ← written in Step 4
system-info.md ← copied or symlinked from bootstrap-system-context
src/
<package_lower>/
zcl_foo.clas.abap
zcl_foo.clas.testclasses.abap
zif_foo.intf.abap
z_report.prog.abap
zi_view.ddls.asddls
zi_view_dcl.dcls.asdcls
zc_view.ddlx.asddlxs
zi_travel.bdef.asbdef
ztable.tabl.xml
zdomain.doma.xml
zdtel.dtel.xml
<subpackage_lower>/
...
skipped.md ← per-object errors and unsupported types
Rules:
- Object names in filenames are lowercased.
- Package names in path segments are lowercased.
- Source files are written verbatim from SAP — do not reformat.
- Overwrite existing files without prompting (SAP is the source of truth).
Step 4: Write mirror//README.md
# Mirror: <SID>
_Generated: <ISO timestamp>_ · _Source: ARC-1_
This directory is a **read-only mirror** of selected ABAP objects from **<SID>**. The SAP system is the source of truth — edits here will NOT be pushed back automatically. To deploy local changes, use `SAPWrite` or a dedicated abapGit export/deploy tool.
See [system-info.md](./system-info.md) for system identity and feature availability.
## Scope
- Mode: <single / list / package>
- <If package: **Package**: ZPKG — recursed into N sub-packages>
- <If list: **Objects**: M explicit>
- Objects mirrored: <count by type>
- Objects skipped: see [skipped.md](./skipped.md)
## Layout
- `src/<package>/` — abapGit-style object files
- `skipped.md` — objects that failed to read or aren't supported yet
## Refreshing
Re-run the `setup-abap-mirror` skill with the same scope. Files are overwritten.
Step 5: Summarize To The User
Report in 4-6 lines:
- SID mirrored, scope (single/list/package)
- Object counts by type (e.g.,
5 CLAS, 12 DDLS, 3 BDEF) - Skipped/failed count with pointer to
skipped.md - Mirror root path
Error Handling
| Error | Cause | Fix |
|---|---|---|
| DEVC read returns 404 | Package does not exist | Ask user to verify the package name via SAPSearch |
| Per-object read fails | Auth / not-released / not-found | Log in skipped.md, continue with the rest |
| Sub-package recursion loops | Circular reference (rare) | Track visited package names; skip duplicates |
FUGR expand_includes fails | On-prem feature, endpoint unavailable | Fall back to expand_includes=false; log as partial |
| Source body empty | Generated proxy or inactive object | Write empty file with a comment header; log in skipped.md |
system-info.md missing | Skill dependency | Run bootstrap-system-context first, then retry |
Notes
What This Skill Does NOT Do
- No deploy — local edits are not pushed back. Use
SAPWriteor a future abapGit deploy action. - No metadata XML in abapGit format — ARC-1 currently returns source text; XML-based object metadata (TABL definitions, DOMA fixed values, class attributes) is emitted as JSON or XML from SAP's native form, not the abapGit
object.xmlconvention. That's enough for reading andgit diff, not enough for a full abapGit pull-push round trip. - No concurrency — object reads are sequential to stay within SAP work-process budgets.
When To Use This Skill
- Onboarding a new team member to an existing codebase
- Preparing for a migration where you need to grep locally across many objects
- Snapshotting a system before a support package upgrade
- Feeding local context into an AI assistant that cannot call MCP tools for every read
When NOT To Use This Skill
- For single ad-hoc reads — just call
SAPReaddirectly - When you need a full abapGit round-trip (mirror + deploy back) — wait for native abapGit support
- On production systems where SAP read load is a concern — large package mirrors issue hundreds of requests
BTP vs On-Premise
- BTP: fewer object types will appear in DEVC listings (no PROG, INCL, FUGR). The normalization table above handles this — unsupported types are just absent.
- On-prem: the full type range applies; legacy types not in the table are logged in
skipped.mdand can be added to ARC-1 over time.
Future-Proofing
This skill produces abapGit-compatible layout today using existing primitives. When ARC-1 gains a dedicated abapGit export action, the internals change but the output directory remains recognizable to any abapGit-aware tool.
MCP servers 1
Sponsors
Details
- Marketplace
- arc-mcp/arc-1
- Author
- Marian Zeis
- Category
- Developer Tools
- License
- MIT
- Keywords
- sap, abap, adt, s4hana, btp, rap, cds, fiori