<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Onur Yılmaz on Medium]]></title>
        <description><![CDATA[Stories by Onur Yılmaz on Medium]]></description>
        <link>https://medium.com/@onuryz.itu?source=rss-98880ec83529------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*FZTCBO0N6TcC_dUQ</url>
            <title>Stories by Onur Yılmaz on Medium</title>
            <link>https://medium.com/@onuryz.itu?source=rss-98880ec83529------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 14:54:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@onuryz.itu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Offline-First Sync: Last Write Wins Resurrects Deleted Records and Trusts the Wrong Clock]]></title>
            <link>https://medium.com/@onuryz.itu/offline-first-sync-last-write-wins-resurrects-deleted-records-and-trusts-the-wrong-clock-2e6c9061fbe9?source=rss-98880ec83529------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e6c9061fbe9</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[offline-first]]></category>
            <dc:creator><![CDATA[Onur Yılmaz]]></dc:creator>
            <pubDate>Mon, 14 Sep 2026 12:27:32 GMT</pubDate>
            <atom:updated>2026-09-14T12:27:32.640Z</atom:updated>
            <content:encoded><![CDATA[<p>You delete something on your phone. A week later you open the app on your tablet, which has been offline the whole time, and it comes back. Not a stale copy on screen — the record is genuinely alive again, on the server, on both devices.</p><p>This is the most common offline-first bug I know of, and I found it in my own code. Two things need to be said up front, because they change how you should read the rest of this: the sync service where this lived <strong>has no callers yet</strong> — it was written ahead of the screens that will use it, so no user ever hit the resurrection. And the fixes below are <strong>verified with unit tests, not with two real devices</strong>. That verification is still open. I am writing this as “caught before wiring”, not as “incident resolved”.</p><h3>The rule everyone writes first</h3><p>An offline-first app needs a tie-break: the same record exists locally and remotely, both may have changed, one has to win. Almost everyone writes the same first version — last write wins, decided on a timestamp:</p><pre>// Update: record exists on both sides — take remote if it is newer<br>const remoteUpdated = dto.updatedAt ?? dto.createdAt ?? new Date(0);<br>const remoteDate = remoteUpdated instanceof Date<br>  ? remoteUpdated<br>  : (remoteUpdated as any).toDate?.() ?? new Date(0);<br>if (remoteDate &gt; localItem.updatedAt) {<br>  Object.assign(localItem, dtoToClothingItem(dto, userId));<br>}</pre><p>It reads as obviously correct. It has two silent failure modes, and this post is about both of them.</p><h3>Bug 1: the delete that does not survive a merge</h3><p>The sync pass has three branches: records that exist only locally get uploaded, records that exist only remotely get downloaded, records that exist on both sides go through the rule above. Deletion was a hard delete:</p><pre>async deleteClothingItem(id: string, userId: string): Promise&lt;void&gt; {<br>  await deleteDoc(doc(db, &#39;users&#39;, userId, &#39;clothingItems&#39;, id));<br>},</pre><p>Now follow a second device that still has a stale copy. It fetches the collection. The record is not there. From the merge’s point of view “not on remote” has exactly one meaning: <em>this is a local-only record, upload it.</em> The delete is undone by the upload branch, and the record is back on the server, from where the first device will happily download it again.</p><p>The merge never had the information it needed. A missing document cannot distinguish “never synced” from “deleted”. So stop removing the document — mark it:</p><pre>async deleteClothingItem(id: string, userId: string): Promise&lt;void&gt; {<br>  const ref = doc(db, &#39;users&#39;, userId, &#39;clothingItems&#39;, id);<br>  await setDoc(<br>    ref,<br>    { deletedAt: serverTimestamp(), updatedAt: serverTimestamp() },<br>    { merge: true }<br>  );<br>},</pre><p>A tombstone. The id stays on remote, so the upload branch never fires for it, and the rest follows mechanically (simplified — unrelated fields and the outfit collection omitted):</p><pre>const remoteIds = new Set(remoteDTOs.map((d) =&gt; d.id).filter(Boolean));<br>const remoteTombstones = new Set(<br>  remoteDTOs.filter((d) =&gt; d.id &amp;&amp; d.deletedAt).map((d) =&gt; d.id)<br>);<br>// upload: local-only records. A tombstone doc is still in remoteIds,<br>// so a record deleted on another device never reaches this branch.<br>for (const item of localItems) {<br>  if (!remoteIds.has(item.firestoreId)) { /* upload */ }<br>}<br>// download: never pull a tombstone<br>for (const dto of remoteDTOs) {<br>  if (!dto.id || localIds.has(dto.id) || dto.deletedAt) continue;<br>  merged.push(dtoToClothingItem(dto, userId));<br>}<br>// and drop it from local<br>if (remoteTombstones.size) {<br>  merged = merged.filter((i) =&gt; !remoteTombstones.has(i.firestoreId));<br>}</pre><p>Note serverTimestamp() on the delete. Even here I did not want the deletion time coming from the device.</p><h3>Bug 2: the clock belongs to the user</h3><p>Back to remoteDate &gt; localItem.updatedAt. That localItem.updatedAt was written by the device, from Date.now(). The device clock is not infrastructure — it is a user-facing setting, it drifts, it jumps across time zones, and on a phone it can simply be wrong.</p><p>Set a device forward and updatedAt goes forward with it. From then on remoteDate &gt; localItem.updatedAt is false for every genuine remote update, at any magnitude, until the world catches up. One phone with a bad clock blocks its own sync indefinitely, and the code reports nothing: no error, no conflict, just a record that quietly stops changing.</p><p>I had a fix for this sitting in an old branch: a clock-skew cap. Clamp the timestamps into a sane window so a wild clock cannot dominate the comparison. It was written, it looked reasonable, and merging it would have been the easy call.</p><p>Then I measured what it actually did — and it was a no-op <strong>for the direction it was supposed to defend</strong>. The clamp floored the <em>remote</em> side of the comparison. The problem lives on the <em>local</em> side: the future-dated local stamp still won, at any magnitude. Against a forward-set device clock the cap changed nothing at all.</p><p>So I deleted it instead of shipping it. The reasoning is in the PR body, and it is the part of this whole story I would defend hardest:</p><blockquote><em>Shipping a defence that does not defend would close the signal.</em></blockquote><p>A half-fix that looks like a fix is worse than no fix. It gets a checkbox, it closes the issue, it makes the next person reading the code believe the surface is covered, and the real bug now has camouflage. “Better than nothing” is a claim about the code; “hides the signal” is a claim about everyone who reads the code afterwards. The second one costs more.</p><h3>The clock-free rule</h3><p>The real fix is not a better clock. It is removing the clock from the comparison.</p><p>Every local record carries a <strong>local-only</strong> field — the server updatedAt it last saw for that record. It is never written back to the DTO; it only ever holds a value the server produced. The rule compares remote&#39;s current stamp against that one:</p><pre>export function remoteChangedSinceSeen(<br>  remoteUpdatedAt: Date | undefined,<br>  seen: Date | undefined<br>): boolean {<br>  if (!remoteUpdatedAt) return false; // no stamp on remote → nothing to decide on, keep local<br>  if (!seen) return true;             // never seen → remote is authoritative<br>  return remoteUpdatedAt.getTime() !== seen.getTime();<br>}</pre><p>Different stamp → remote changed since we last synced → remote wins. Equal → nothing new on remote → local is kept, including an edit made entirely offline. Notice it is !==, not &gt;. Ordering is what needs a clock; <em>identity</em> does not. A different stamp is a different write, even if it sorts earlier — which can happen across a server-side retry or a restore, and in that case I want the remote state regardless of which way it sorts.</p><p>Both server stamps in the comparison come from the same clock: Firestore’s. No device clock enters it at any point. So the tests can be blunt about it:</p><pre>it(&#39;a future-dated LOCAL clock cannot block a remote update (the old &quot;remote wins if newer&quot; bug)&#39;, async () =&gt; {<br>  const farFuture = new Date(&#39;2030-01-01T00:00:00Z&#39;);<br>  fetchClothingItems.mockResolvedValue([remoteItem({ updatedAt: ts(T2) as unknown as Date })]);<br>  // local was last synced when remote said T1; device clock then jumped to 2030<br>  const local = localItem({ updatedAt: farFuture, remoteUpdatedAt: T1 });<br>  const merged = await syncService.syncClothingItems(&#39;u&#39;, [local]);<br>  expect(merged[0].name).toBe(&#39;remote-name&#39;);<br>  expect(merged[0].remoteUpdatedAt?.getTime()).toBe(T2.getTime());<br>});<br>it(&#39;a device clock shifted by a whole hour changes nothing — the rule never reads Date.now()&#39;, async () =&gt; {<br>  vi.useFakeTimers();<br>  vi.setSystemTime(new Date(&#39;2026-09-02T11:00:00Z&#39;)); // +1h vs &quot;true&quot; now<br>  fetchClothingItems.mockResolvedValue([remoteItem({ updatedAt: ts(T2) as unknown as Date })]);<br>  const merged = await syncService.syncClothingItems(&#39;u&#39;, [localItem({ remoteUpdatedAt: T1 })]);<br>  expect(merged[0].name).toBe(&#39;remote-name&#39;);<br>  vi.useRealTimers();<br>});</pre><p>The 2030 test is the old bug written down as an executable statement. The +1h test is the stronger one: it moves the whole system clock and asserts the outcome does not move. That is the property I actually want — not &quot;the rule handles skew well&quot; but &quot;the rule never asks&quot;.</p><h3>The follow-up nobody would have noticed</h3><p>The rule shipped, and the next review found a hole in it: after a successful upload, the record had <strong>no</strong> server stamp at all. Nothing had read one back. So on the <em>next</em> sync, seen was undefined, the rule fell to &quot;never seen → remote is authoritative&quot;, and any edit made between the upload and that next sync was silently overwritten by the copy the server already had.</p><p>The fix is a read-back, and the interesting part is where it is <em>not</em>:</p><pre>await firestoreService.saveClothingItem(dto, userId);<br>// keep the stamp the server wrote; one extra read, only on the sync path<br>item.remoteUpdatedAt = await firestoreService.readClothingItemUpdatedAt(userId, item.firestoreId);<br>item.lastSyncedAt = new Date();</pre><p>The obvious move is to make the shared saveClothingItem return the stamp. That would have put an extra getDoc on every save in the app — the live UI call sites, where a user is watching a spinner. They do not need the stamp; only the merge does. So the read-back is a separate function that only sync calls, and the shared save stays Promise&lt;void&gt; with its single round-trip.</p><p>And when the read-back itself fails:</p><pre>async function readBackUpdatedAt(ref): Promise&lt;Date | undefined&gt; {<br>  try {<br>    const snap = await getDoc(ref);<br>    const v = snap.data()?.updatedAt;<br>    return v instanceof Date ? v : v?.toDate?.() ?? undefined;<br>  } catch {<br>    return undefined;<br>  }<br>}</pre><p>undefined means &quot;never seen&quot;, which means remote wins next time. Losing one local edit is the recoverable failure; keeping a local record that silently diverges from the server forever is not. There is a test asserting exactly that fallback, because a safe side you did not test is a safe side you assumed.</p><h3>What this does not do</h3><ul><li><strong>No tombstone purge.</strong> Deleted ids accumulate in the collection forever. A purge needs a retention window long enough that no device can still be offline holding a stale copy, and I have not picked that number.</li><li><strong>No multi-device verification.</strong> Everything above is covered by unit tests against a mocked Firestore boundary. Two real devices, one of them offline for days, with a real clock set wrong, is a different test and it has not been run. I would not call this “fixed” — I would call it “the failure is now written down as a test that fails on the old code”.</li><li><strong>The service is still dormant.</strong> It has no callers outside its own test file. That is why none of this was ever a user-facing incident, and also why nobody should read this as battle-tested.</li><li><strong>The rule only decides who wins, not how to merge.</strong> Whole-record replacement, no field-level merge. If both sides changed different fields of the same record, one set of changes is lost. Field-level merge is a much bigger design, and for this data shape it is not worth it yet.</li></ul><h3>The takeaway</h3><p>If your conflict rule reads a device clock, the rule is administered by whoever holds the device. That is the whole thing. Compare server stamps against server stamps and the entire class of skew bugs stops existing — not handled, not tolerated, not clamped: absent.</p><p>And when you measure a defence and find it does not defend, delete it. A half-fix does not just fail to help; it takes the signal down with it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e6c9061fbe9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ADT Over the Wire]]></title>
            <link>https://medium.com/@onuryz.itu/adt-over-the-wire-a2677bbda61b?source=rss-98880ec83529------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2677bbda61b</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[sap]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[abap]]></category>
            <dc:creator><![CDATA[Onur Yılmaz]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 08:50:15 GMT</pubDate>
            <atom:updated>2026-08-18T08:50:15.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NHMpZ83mFvaW61JEdvg_kA.png" /></figure><h3>What actually happens on the HTTP connection when an AI agent reads, edits, activates and transports ABAP objects in a live SAP system — the session handshake, the lock protocol, and the guardrails that sit in front of both.</h3><h3>Why ADT REST, not RFC</h3><p>Most attempts to drive SAP from the outside reach for RFC: a library from the NW RFC SDK, a function module allow-list, a service user, and a pile of glue that has to be maintained per release. It works, but every ABAP-repository operation you want — read a class, check syntax, activate — has to be hand-built on top of function modules that were never meant to be a development API.</p><p>ABAP Development Tools takes a different route. When a developer edits ABAP in Eclipse, Eclipse is not talking RFC — it is issuing plain HTTP requests against an ICF service tree rooted at /sap/bc/adt. Source retrieval, syntax checks, locks, activation, ATC runs, transports, the debugger: all of it is REST-shaped, XML-bodied HTTP that ships with the system.</p><p>That makes it the natural substrate for an agent. Everything the tooling does is something a developer with the same user could already do, subject to the same authorization objects, the same CTS rules, the same lock table. There is no privileged side channel — only a different client at the other end of the socket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEEY71XImSue7wdz2MQVhg.png" /></figure><p><em>The agent never sees a socket. It sees tool calls; the MCP server owns the credentials, the session, and the policy that decides whether a call is allowed to mutate anything.</em></p><h3>The connection profile</h3><p>A system is a small JSON object: a host with an explicit scheme, a client, a logon language, a user, and a password that is normally an indirection into the environment rather than a literal.</p><pre>~/.sap-adt-mcp/config.json<br><br>{<br>  &quot;defaultSystem&quot;: &quot;DEV&quot;,<br>  &quot;readOnly&quot;: false,<br>  &quot;systems&quot;: {<br>    &quot;DEV&quot;: {<br>      &quot;host&quot;: &quot;https://sap-dev.example.com:44300&quot;,<br>      &quot;client&quot;: &quot;100&quot;,<br>      &quot;language&quot;: &quot;EN&quot;,<br>      &quot;user&quot;: &quot;DEVELOPER&quot;,<br>      &quot;password&quot;: &quot;env:SAP_DEV_PASSWORD&quot;,<br>      &quot;rejectUnauthorized&quot;: false<br>    },<br>    &quot;PRD&quot;: {<br>      &quot;host&quot;: &quot;https://sap-prd.example.com:44300&quot;,<br>      &quot;client&quot;: &quot;300&quot;,<br>      &quot;user&quot;: &quot;READONLY&quot;,<br>      &quot;password&quot;: &quot;env:SAP_PRD_PASSWORD&quot;,<br>      &quot;readOnly&quot;: true<br>    }<br>  }<br>}</pre><p>Three details in that file do real work.</p><p><strong>The host is validated at load, not at call time.</strong> A host written without a scheme produces an unparseable URL on every single request, surfacing as a cryptic error once per tool call, far from the cause. Parsing it once at startup turns that into a single, actionable failure.</p><p><strong>Client and language are injected, not typed.</strong> Every outbound URL gets sap-client and sap-language appended unless the caller already set them. No tool has to remember, and no tool can accidentally land in client 000.</p><p><strong>readOnly is per system and monotonic.</strong> A global readOnly: true cannot be relaxed by a system profile — the system-level flag can only add restriction. Production is a read-only profile with a read-only user; the flag is defence in depth on top of the SAP authorization that already says no.</p><p>Everything else is transport plumbing: a 30-second default timeout enforced with an AbortController, and an opt-out for certificate validation that exists because internal SAP hosts are so often fronted by a self-signed certificate — set per system, never globally implied.</p><h3>Session, CSRF and cookies</h3><p>A write to ADT is not one request. Before the first mutation there is a handshake, and if you skip it the backend answers 403 with a header that tells you exactly what you forgot.</p><p>ICF protects unsafe methods with a CSRF token. The client asks for one by sending a harmless GET with X-CSRF-Token: Fetch; the response carries the token in the same header, plus the session cookies that bind it.</p><pre>GET /sap/bc/adt/discovery?sap-client=100&amp;sap-language=EN<br>Authorization: Basic REVWRUxPUEVSOioqKioqKg==<br>Accept: application/atomsvc+xml<br>X-CSRF-Token: Fetch<br><br>HTTP/1.1 200 OK<br>x-csrf-token: nZ8mQ1r7Vx2kLpQ9dW0aBg==<br>set-cookie: SAP_SESSIONID_S4H_100=Xf3l...; path=/; HttpOnly<br>set-cookie: sap-usercontext=sap-client=100; path=/</pre><p>From then on every POST / PUT / DELETE carries X-CSRF-Token and the accumulated Cookie header. Tokens do expire — when the session is recycled the backend answers 403 with x-csrf-token: required, which is unambiguous enough to handle automatically: drop the cached token, re-run the handshake, replay the request once. Exactly once; a retry loop against an authentication failure is how you lock a user out.</p><p>Two subtleties are worth stating plainly, because they are the two things people get wrong when they build this themselves.</p><h3>Cookies must be keyed by name</h3><p>SAP hands out several cookies on the same connection, and naive jars that key on (name, domain, path) tuples hit collisions when the same session cookie is re-issued with a different path — the well-known CookieConflictError in the Python ecosystem. A flat, name-keyed map takes the last value seen and never conflicts.</p><h3>Locks need a stateful session</h3><p>ADT is stateless by default: each request may be served by a different work process, and a lock taken in one is meaningless in the next. Sending X-sap-adt-sessiontype: stateful pins the session, which is what makes a lock handle survive from the LOCK call to the PUT that uses it. Every request in the write sequence carries it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0kA9v9kZBge2bLO-Y0c1zQ.png" /></figure><p><em>Green is a read, amber a mutation, red the backend refusing one. The 403 path is not an error to report upward — it is a documented part of the protocol, and it is handled once.</em></p><h3>Naming things: object URI vs source URI</h3><p>An agent asks for &quot;class ZCL_ORDER&quot;. ADT wants two different URLs, and using the wrong one is the single most common way this integration fails.</p><p>Every repository object has an <strong>object URI</strong> — the resource itself, used for metadata and for lock/unlock — and a <strong>source URI</strong>, the editable document hanging beneath it. They are not interchangeable. You lock the object; you GET and PUT the source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qL1Z32oTxt-zVBYB5GruEw.png" /></figure><p><em>The mapping layer is the part of the integration that carries the most SAP-specific knowledge, and the part most worth centralising: one table, consulted by every tool.</em></p><pre>OBJECT              OBJECT URI                                  SOURCE DOCUMENT<br>Program   PROG      /programs/programs/{name}                   …/source/main<br>Include   INCL      /programs/includes/{name}                   …/source/main?context=…<br>Class     CLAS      /oo/classes/{name}                          …/source/main, …/includes/{part}<br>Interface INTF      /oo/interfaces/{name}                       …/source/main<br>Function  FUGR/FF   /functions/groups/{group}/fmodules/{name}   …/source/main<br>CDS view  DDLS      /ddic/ddl/sources/{name}                    …/source/main<br>Table     TABL      /ddic/tables/{name}                         …/source/main<br>Data el.  DTEL      /ddic/dataelements/{name}                   XML metadata — no source</pre><p>Two cases in that table deserve their own sentence, because they are where naive implementations return &quot;unsupported object type&quot; to a perfectly ordinary request.</p><p><strong>A function module is addressed under its group</strong> — but nobody has the group at hand. SE37, the short dump, the where-used list all show the module name alone. The fix is a repository-search lookup that resolves group from name, insisting on an exact name match so a prefix hit can never silently substitute a different module.</p><p><strong>Some types have no source resource at all.</strong> Adobe Forms are the clean example: the ADT discovery document lists 403 collections and not one of them covers SFP. Repository search does know the object and returns it under the generic workbench bridge, which serves object properties but 404s on /source/main. The honest answer to &quot;give me the source of this form&quot; is a structured no — properties, plus a statement that ADT publishes no source for the type and it is edited in SAP GUI — not a stack trace.</p><blockquote><em>A limit of the platform should be reported as a fact about the platform. An agent can route around &quot;ADT serves no source for this type&quot;; it cannot route around &quot;Error: undefined&quot;.</em></blockquote><h3>The read path</h3><p>Reads are the easy half: a GET, an XML or plain-text body, and a parser. The interesting engineering is in what surrounds them.</p><pre>GET  /sap/bc/adt/oo/classes/zcl_order/source/main?sap-client=100<br>     Accept: text/plain<br>     200 OK  →  CLASS zcl_order DEFINITION PUBLIC FINAL CREATE PUBLIC. …<br><br>GET  /sap/bc/adt/repository/informationsystem/search?operation=quickSearch&amp;query=ZCL_ORDER*<br>POST /sap/bc/adt/repository/informationsystem/usageReferences   ← where-used<br>POST /sap/bc/adt/repository/nodestructure                       ← package tree<br>POST /sap/bc/adt/datapreview/freestyle?rowNumber=100            ← OpenSQL SELECT</pre><h3>Reads that arrive as POST</h3><p>Search, where-used, package structure and data preview all POST a request document and get a result document back. They mutate nothing. This matters enormously for the safety model below: a policy that says &quot;POST means write&quot; would break half the read surface, so the gate needs a precise allow-list rather than a method check.</p><h3>Large objects and the context budget</h3><p>A 6,000-line function group does not belong in an LLM&#39;s context window, and it does not fit through the per-call I/O cap anyway. Three escape hatches, in increasing order of usefulness:</p><ul><li><strong>Line ranges</strong> — firstLine/lastLine paginate the document.</li><li><strong>Method slicing</strong> — ask for one method body out of a class.</li><li><strong>File hand-off</strong> — outputFile makes the MCP process write the source straight to disk. The agent edits the file, then writes it back by path. The full text never travels through the model at all.</li></ul><h3>Data preview is SELECT-only, twice</h3><p>Table contents come from the same freestyle OpenSQL endpoint SE16 alternatives use. The backend enforces SELECT-only itself; the client re-checks anyway — statement must start with SELECT, no chained statement after a semicolon — so an obvious mistake fails locally instead of burning a round trip. Belt and braces, cheaply.</p><h3>The write path: LOCK → PUT → UNLOCK</h3><p>This is the sequence that separates a real integration from a demo. Get it wrong and you leave objects locked in a production-adjacent system, which is the kind of mistake people remember.</p><p>ADT will not let you PUT source you have not locked. The lock is taken on the <em>object</em> URI with _action=LOCK, returns a handle inside an ABAP XML envelope, and that handle is then a required query parameter on the PUT.</p><pre>① acquire<br>POST /sap/bc/adt/programs/programs/zdemo_report?_action=LOCK&amp;accessMode=MODIFY&amp;corrNr=S4HK900123<br>X-sap-adt-sessiontype: stateful<br>Accept: application/vnd.sap.as+xml;dataname=com.sap.adt.lock.Result<br><br>200 OK   &lt;LOCK_HANDLE&gt;wF9K2sQ0…&lt;/LOCK_HANDLE&gt;<br><br>② replace the source — atomically, in full<br>PUT /sap/bc/adt/programs/programs/zdemo_report/source/main?lockHandle=wF9K2sQ0…&amp;corrNr=S4HK900123<br>Content-Type: text/plain; charset=utf-8<br>X-sap-adt-sessiontype: stateful<br><br>REPORT zdemo_report.<br>…the entire include, every line of it…<br><br>③ release — in a finally block, always<br>POST /sap/bc/adt/programs/programs/zdemo_report?_action=UNLOCK&amp;lockHandle=wF9K2sQ0…</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MpVFDjU-UWRNa-AWMpix0Q.png" /></figure><p><em>The unlock lives in a finally. A handler that returns early on a PUT error and skips the release leaves the object locked for the next developer, who will find out from SE11 rather than from you.</em></p><h3>PUT replaces the whole include</h3><p>There is no patch semantic. A PUT of the source document <em>is</em> the new document; send half of it and the other half is gone. That is a genuinely dangerous shape to hand an LLM, which is perfectly capable of returning “the method I changed” when asked for a file.</p><p>So the write is guarded before it leaves the process: the first non-blank, non-comment line of the payload must begin with a recognised top-level ABAP construct — REPORT, CLASS, FUNCTION-POOL, TYPES, DATA, and so on. A payload starting mid-method is refused with 422 and an explanation, not sent. The guard is overridable with an explicit acknowledgement flag, because occasionally the caller really does mean it.</p><h3>Transports ride along</h3><p>corrNr on the LOCK and on the PUT is the transport request. A whitespace-only value is worse than none — it reaches CTS as corrNr=%20 and returns a 500 — so blank query values are dropped centrally, at the one place that builds URLs, rather than in each of the dozen tools that can pass a transport.</p><h3>Locks can also be held across calls</h3><p>For sources too large for a single tool call, the lock is taken explicitly, the source is streamed in chunks into a server-side buffer (10-minute TTL, 4 MB cap), and the final call commits: concatenate, run the same partial-source guard, PUT, and let the caller release the lock. The buffer lives in the MCP process, never in the model.</p><blockquote><em>An object left locked is invisible to the agent and very visible to the team. Every path out of the write handler — success, ADT error, thrown exception, timeout — has to reach the same unlock.</em></blockquote><h3>Activation, and why includes are special</h3><p>Written source is inactive source. Activation is its own endpoint, taking a list of object references — which means one call can activate a whole change set, and the backend can resolve the dependency order itself.</p><pre>POST /sap/bc/adt/activation?method=activate&amp;preauditRequested=true<br>Content-Type: application/xml</pre><pre>&lt;adtcore:objectReferences xmlns:adtcore=&quot;http://www.sap.com/adt/core&quot;&gt;<br>  &lt;adtcore:objectReference<br>      adtcore:uri=&quot;/sap/bc/adt/programs/includes/zincl_forms?context=%2Fsap%2Fbc%2Fadt%2Fprograms%2Fprograms%2Fzmain&quot;<br>      adtcore:name=&quot;ZINCL_FORMS&quot;/&gt;<br>&lt;/adtcore:objectReferences&gt;</pre><p>An include has no independent existence — it compiles only inside a main program. Ask ADT to activate one without saying which main program, and if the include is used by more than one you get a 500: “REPS X is used in multiple master programs”. The activation service is not being obtuse; it genuinely cannot pick.</p><p>The resolution is to look the main programs up first and then decide:</p><ul><li><strong>Exactly one candidate</strong> → attach it as ?context= and proceed. The caller never learns this happened.</li><li><strong>Several candidates</strong> → return them by name and ask which one. A guess here compiles the include against the wrong program.</li></ul><p>The same lookup serves syntax checks, where the symptom is quieter and therefore worse: an include checked without context comes back status=&quot;notProcessed&quot;, which reads like a clean bill of health if you are not looking closely.</p><p>One more flag exists for a specifically multi-developer failure. When an object’s components are locked in a separate task under the same transport, CTS answers 403; isProcessRedoneOOSourceVerOnly=true asks SAP to re-activate only the redone OO source versions, which is the documented way out.</p><h3>Creating objects and feeding CTS</h3><p>Creation is a POST to a per-type collection with a per-type versioned media type and a per-type XML body. There is no generic “create object” call — the shapes differ because the objects differ.</p><pre>POST /sap/bc/adt/oo/classes?corrNr=S4HK900123<br>Content-Type: application/vnd.sap.adt.oo.classes.v3+xml</pre><pre>&lt;class:abapClass xmlns:class=&quot;http://www.sap.com/adt/oo/classes&quot;<br>    xmlns:adtcore=&quot;http://www.sap.com/adt/core&quot;<br>    adtcore:name=&quot;ZCL_ORDER&quot; adtcore:type=&quot;CLAS/OC&quot;<br>    adtcore:description=&quot;Order handling&quot; adtcore:responsible=&quot;DEVELOPER&quot;<br>    class:final=&quot;true&quot; class:visibility=&quot;public&quot; class:category=&quot;generalObjectType&quot;&gt;<br>  &lt;adtcore:packageRef adtcore:name=&quot;ZORDERS&quot;/&gt;<br>&lt;/class:abapClass&gt;</pre><p>Programs use v2 media types, classes v3, interfaces v2 — the version is part of the contract.</p><p>Note adtcore:packageRef: the package is not a query parameter but part of the document, and it is the thing that decides whether the object is local ($TMP, no transport) or transportable. If it is transportable, corrNr must name a modifiable request or CTS refuses the create.</p><p>Which is why transport handling is a first-class part of the surface rather than an afterthought:</p><ul><li><strong>List my requests</strong> — GET /cts/transportrequests (read)</li><li><strong>Inspect one</strong> — GET /cts/transportrequests/{id} (read)</li><li><strong>Create a request</strong> — POST /cts/transportrequests (write)</li><li><strong>Release it</strong> — POST /cts/transportrequests/{id}/newreleasejobs (write)</li></ul><p>Release is a job, not a synchronous action — the endpoint name says so. The agent gets a job, not a verdict, and has to go back and look.</p><h3>Verification: POSTs that change nothing</h3><p>The most valuable thing about driving SAP through ADT is not that an agent can write code. It is that the agent can find out, in the same session, whether the code it wrote is any good.</p><pre>POST /sap/bc/adt/checkruns?reporters=abapCheckRun          ← syntax check<br>Content-Type: application/vnd.sap.adt.checkobjects+xml<br>&lt;chkrun:checkObjectList&gt;&lt;chkrun:checkObject adtcore:uri=&quot;…/source/main&quot;/&gt;&lt;/chkrun:checkObjectList&gt;</pre><pre>POST /sap/bc/adt/abapunit/testruns                         ← ABAP Unit<br>Content-Type: application/vnd.sap.adt.abapunit.testruns.config.v1+xml</pre><pre>POST /sap/bc/adt/atc/worklists  →  /sap/bc/adt/atc/runs    ← ATC, two steps</pre><p>All three are POSTs. None of them touches the repository: the check run is transient, the test run executes existing code, the ATC worklist is a temporary result container. A useful mental model is that ADT uses POST for “run a computation and give me the document back”, not only for “change something”.</p><p>That distinction is not cosmetic — it is precisely the line the read-only gate has to draw, and drawing it by HTTP method alone gets it wrong in both directions.</p><p>The practical consequence is a real loop: write source → syntax check → activate → run the unit tests → run ATC over the package → read the findings → fix. Each step is one call, and the failure output is structured enough to act on. That loop, not the source editing, is what makes an agent useful in an ABAP system.</p><h3>The safety model</h3><p>An LLM with a live connection to a development system is exactly as alarming as it sounds, and the honest answer is layered: SAP’s own authorization concept is the last line and the strongest one, but the client has obligations too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hHJaKk2xtSqJzHCQm_hpOw.png" /></figure><h3>Normalise first, gate second</h3><p>If the read-only check runs on the raw string, a path can be smuggled through it. A path like /sap/bc/adt/checkruns/../programs/programs/zprod/source/main starts with an allow-listed prefix, so a naive startsWith lets it through — and then the URL constructor collapses the ../ and the request lands on a program source. Resolving the path <em>before</em> the policy check closes that, and it is the reason the resolved path (not the caller&#39;s) is what gets audited too.</p><h3>Headers the caller cannot set</h3><p>There is an escape-hatch tool that issues an arbitrary ADT request — indispensable for the long tail of endpoints, and an obvious hole if unconstrained. Three headers are therefore reserved: Authorization, Cookie, X-CSRF-Token. A caller-supplied value for any of them is dropped, not merged. Without that, anything able to influence the model’s tool arguments — a prompt injection sitting in an ABAP comment, say — could impersonate another SAP user or forge a session. The client’s own internal headers travel on a separate channel that bypasses the filter, because the CSRF handshake obviously has to set X-CSRF-Token.</p><h3>Every write is written down</h3><p>The first question anyone asks about AI with write access is <em>what exactly did it change?</em> One append-only JSONL line per unsafe request answers it — including the writes that were refused.</p><pre>~/.sap-adt-mcp/audit.log</pre><pre>{&quot;ts&quot;:&quot;2026-08-17T09:14:02.118Z&quot;,&quot;tool&quot;:&quot;adt_set_source&quot;,&quot;host&quot;:&quot;https://sap-dev…&quot;,&quot;sapUser&quot;:&quot;DEVELOPER&quot;,<br> &quot;method&quot;:&quot;PUT&quot;,&quot;path&quot;:&quot;/sap/bc/adt/programs/programs/zdemo_report/source/main&quot;,&quot;status&quot;:200,&quot;ok&quot;:true,<br> &quot;transport&quot;:&quot;S4HK900123&quot;}</pre><pre>{&quot;ts&quot;:&quot;2026-08-17T09:31:47.902Z&quot;,&quot;tool&quot;:&quot;adt_delete_object&quot;,&quot;host&quot;:&quot;https://sap-prd…&quot;,&quot;sapUser&quot;:&quot;READONLY&quot;,<br> &quot;method&quot;:&quot;POST&quot;,&quot;path&quot;:&quot;/sap/bc/adt/programs/programs/zlegacy&quot;,&quot;outcome&quot;:&quot;blocked-read-only&quot;}</pre><p>Reads are not logged — the file answers “what changed”, not “what was seen”. The log is local. Nothing leaves the machine, and the tool name is carried into the client layer through an AsyncLocalStorage context so a three-request sequence (lock, PUT, unlock) is still attributed to the one tool call that caused it.</p><blockquote><em>The client-side gate stops mistakes. It does not stop a determined actor — anyone with the config file has the password and can bypass every guard here by using curl. The real boundary is the SAP user: its authorization objects, its client, its role. Point the agent at a production system with a developer’s credentials and no client-side flag will save you.</em></blockquote><h3>Reading ADT errors</h3><p>ADT failures arrive as XML with more in them than the message text — and the message text is frequently the least useful part.</p><pre>HTTP/1.1 403 Forbidden<br>Content-Type: application/xml</pre><pre>&lt;exc:exception xmlns:exc=&quot;http://www.sap.com/abapxml/types/communication&quot;&gt;<br>  &lt;namespace id=&quot;com.sap.adt&quot;/&gt;<br>  &lt;type id=&quot;ExceptionResourceNoAccess&quot;/&gt;<br>  &lt;message lang=&quot;EN&quot;&gt;Object is locked by another request&lt;/message&gt;<br>  &lt;properties&gt;<br>    &lt;entry key=&quot;T100KEY-ID&quot;&gt;SLOCK&lt;/entry&gt;<br>    &lt;entry key=&quot;T100KEY-NO&quot;&gt;038&lt;/entry&gt;<br>    &lt;entry key=&quot;T100KEY-V1&quot;&gt;S4HK900117&lt;/entry&gt;   ← the blocking transport<br>    &lt;entry key=&quot;LONGTEXT&quot;&gt;&lt;![CDATA[…full diagnostics…]]&gt;&lt;/entry&gt;<br>  &lt;/properties&gt;<br>&lt;/exc:exception&gt;</pre><p>Discarding properties — as the obvious implementation does — throws away the only actionable content. On CTS and lock errors it carries the blocking request, the owner, and the suggested resolution. Surfacing it turns &quot;locked by another request&quot; into &quot;locked by S4HK900117&quot;, which an agent can then look up and reason about.</p><p>A short field guide to the failures that look like tool bugs and are not:</p><ul><li><strong>406 — looks like a broken endpoint.</strong> It’s the wrong Accept header. Version history is an Atom feed and serves application/atom+xml;type=feed and nothing else.</li><li><strong>400 — looks like a malformed request.</strong> It’s an unsupported parameter value. ?version= understands active and inactive; a version number is not a thing here.</li><li><strong>500 — looks like a server crash.</strong> It’s ambiguity the backend cannot resolve — an include with several master programs.</li><li><strong>403 — looks like missing authorization.</strong> Often just an expired CSRF token; check the x-csrf-token response header before blaming a role.</li><li><strong>An HTML body — looks like the wrong URL.</strong> It’s an SSO or web-dispatcher login page. Basic auth cannot pass it — that system needs a different auth path entirely.</li></ul><p>That last one is the current wall. Basic auth reaches on-premise systems; S/4HANA Cloud Public Edition and BTP ABAP environments sit behind SAML, and the ADT surface there needs bearer tokens or captured session cookies, a stateful session type, and a CSRF token fetched from /compatibility/graph rather than /discovery. Same protocol, different front door.</p><h3>What this buys an agent</h3><p>Add it up and the shape of the thing becomes clear. The protocol work — session, URIs, locks, activation contexts, error envelopes — is not interesting in itself. It is interesting because of what sits on top of it once it is reliable.</p><p>An agent that can read a class, follow its where-used list, query the table it writes to, check the syntax of a proposed change, activate it, run the unit tests, run ATC over the package and read the findings, is not autocompleting ABAP. It is doing the loop an ABAP developer does, with the system itself as the source of truth instead of a training-set memory of what SAP looked like in some release.</p><p>The parts worth stealing if you build your own:</p><ul><li>Resolve paths <em>before</em> you apply policy to them.</li><li>Put the unlock in a finally, and test the failure path, not the happy one.</li><li>Treat PUT as destructive-by-default and guard the payload shape, because the caller is a language model.</li><li>Never let a caller set Authorization, Cookie or X-CSRF-Token.</li><li>Log every write locally, including the refused ones.</li><li>When the platform genuinely cannot do something, say so in structured form. “Unsupported” is not an answer; “ADT publishes no source resource for this type, edit it in SAP GUI” is.</li></ul><p>And keep production read-only. Twice — once in the config, once in the SAP user.</p><p><em>Details in this article are drawn from the implementation of sap-adt-mcp (MIT), an MCP server that exposes roughly 58 ADT tools to any MCP-compatible client. Wire traces are illustrative: hosts, handles, tokens and transport IDs are fabricated.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2677bbda61b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Added AI-Powered Natural Language Parsing to My iOS App with Firebase Cloud Functions]]></title>
            <link>https://medium.com/@onuryz.itu/how-i-added-ai-powered-natural-language-parsing-to-my-ios-app-with-firebase-cloud-functions-09f7682abfa7?source=rss-98880ec83529------2</link>
            <guid isPermaLink="false">https://medium.com/p/09f7682abfa7</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Onur Yılmaz]]></dc:creator>
            <pubDate>Mon, 16 Mar 2026 16:37:13 GMT</pubDate>
            <atom:updated>2026-03-16T16:37:13.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*burtudvAml6jTVHs4fz6VQ.png" /></figure><p><em>Building an intelligent event creation experience for Dayping — where “Tarkan concert Friday 8pm” becomes a fully structured event.</em></p><p>If you’ve ever used a calendar app, you know the drill: tap “New Event,” fill in the title, pick a date, pick a time, select a category, add a location. It works, but it’s tedious. I wanted something better for Dayping, my event countdown app.</p><p>What if users could just type what they’re thinking?</p><blockquote>“Tarkan concert Friday 8pm Kuruçeşme Arena”</blockquote><p>And the app would figure out the rest — date, time, location, category, even the event type. That’s exactly what I built for Dayping v1.4.00, and in this post, I’ll walk you through the architecture, the challenges, and the lessons learned.</p><h3>The Architecture</h3><p>The system has three layers:</p><p><strong>1. iOS Client (SwiftUI)</strong><br>The user types a free-form string into a text field. On submit, the app sends this string to a Firebase Cloud Function along with the user’s timezone and current date as context.</p><p><strong>2. Firebase Cloud Function (TypeScript)</strong><br>This is where the magic happens. The Cloud Function receives the raw text, constructs a prompt, calls an LLM API, and parses the structured response back to the client.</p><p><strong>3. LLM API</strong><br>The actual language model that interprets the natural language input and returns structured data.</p><p>Here’s a simplified flow:</p><pre>User Input → iOS App → Cloud Function → LLM API → Structured JSON → iOS App → Firestore</pre><p>Why a Cloud Function instead of calling the LLM directly from the client? Three reasons: API key security, prompt versioning without app updates, and cost control through server-side rate limiting.</p><h3>The Cloud Function: parseEventWithAI</h3><p>The core function takes the user’s text and wraps it in a carefully crafted prompt. The prompt instructs the model to extract:</p><ul><li><strong>title</strong> — The event name</li><li><strong>date</strong> — ISO 8601 format</li><li><strong>time</strong> — 24-hour format (optional)</li><li><strong>location</strong> — Venue or place name (optional)</li><li><strong>category</strong> — One of our predefined categories (concert, cinema, theatre, vacation, wedding, birthday, sports, comedy, custom)</li><li><strong>confidence</strong> — How confident the model is in its parsing (0–1)</li></ul><p>The response comes back as JSON, which we validate before sending to the client.</p><pre>// Simplified structure<br>interface ParsedEvent {<br>  title: string;<br>  date: string; // ISO 8601<br>  time?: string; // HH:mm<br>  location?: string;<br>  category: EventCategory;<br>  confidence: number;<br>}</pre><h3>The Hard Part: Turkish Date Expressions</h3><p>English date parsing is relatively straightforward. “Next Friday” is unambiguous. “March 20th” is clear.</p><p>Turkish? Not so much.</p><p>Consider these expressions:</p><ul><li><strong>“Bu cuma”</strong> (This Friday) — Is it the coming Friday, or Friday of the current week? If today is Saturday, does “bu cuma” mean yesterday or next Friday?</li><li><strong>“Gelecek hafta salı”</strong> (Next week Tuesday) — In Turkish, “gelecek hafta” can mean “the week after this one” or simply “the coming week,” depending on who you ask.</li><li><strong>“Önümüzdeki ay”</strong> (The upcoming month) — Starting from the 1st? Or exactly 30 days from now?</li><li><strong>“Haftaya”</strong> (Next week) — This is a colloquial shorthand. “Haftaya pazartesi” means Monday of next week, but “haftaya” alone is vague.</li><li><strong>“Ayın 15&#39;i”</strong> (The 15th of the month) — Current month or next month if the 15th has passed?</li></ul><p>Each of these required careful prompt engineering to handle correctly. The key insight was providing the <strong>current date and day of the week</strong> as context in every request, and being explicit about the rules:</p><blockquote>“If today is Saturday and the user says ‘bu cuma’ (this Friday), interpret it as the NEXT Friday, not the past one. People don’t create countdowns for past events.”</blockquote><p>This single rule — <strong>people don’t count down to the past</strong> — resolved most of the ambiguity. It’s a domain-specific insight that a general-purpose date parser would miss.</p><h3>Category Detection: More Than Keywords</h3><p>Detecting the event category isn’t just keyword matching. “Tarkan” should map to “concert” even though the word “concert” might not appear in the input. The model needs cultural context.</p><p>Some examples that required tuning:</p><ul><li><strong>“Tarkan Harbiye”</strong> → concert (artist + venue = concert)</li><li><strong>“Interstellar IMAX”</strong> → cinema (movie title + format)</li><li><strong>“Beşiktaş-Galatasaray”</strong> → sports (two team names = match)</li><li><strong>“Cem Yılmaz”</strong> → comedy (comedian name, not concert)</li><li><strong>“Antalya 3 gece”</strong> → vacation (destination + duration)</li></ul><p>For Turkish users, the model needs to know that Harbiye, Kuruçeşme, and Volkswagen Arena are concert venues, that Beşiktaş and Galatasaray are football clubs, and that Cem Yılmaz is a comedian. This cultural knowledge is baked into the LLM, which is one of the advantages of using a large model over a rule-based parser.</p><h3>Category-Based Custom Fields</h3><p>Once the category is detected, Dayping shows category-specific fields. This was a v1.4.00 feature that pairs beautifully with AI parsing:</p><ul><li><strong>Concert:</strong> Artist, venue, seat info, ticket URL</li><li><strong>Cinema:</strong> Movie title, theatre, showtime</li><li><strong>Vacation:</strong> Destination, flight info, hotel</li><li><strong>Wedding:</strong> Venue, dress code</li><li><strong>Sports:</strong> Teams, stadium, seat</li></ul><p>The AI parsing pre-fills the category, and the custom fields appear automatically. The user just confirms and adds details.</p><h3>Confidence Scoring and Fallback</h3><p>Not every input is parseable. “asdfghjk” shouldn’t create an event. Neither should “maybe sometime next month possibly.”</p><p>The confidence score handles this. Below 0.5, the app shows the raw text as the title and asks the user to fill in the details manually. Between 0.5 and 0.8, it shows the parsed result but highlights uncertain fields. Above 0.8, it auto-fills everything.</p><pre>switch confidence {<br>case 0.8...1.0:<br>    // Auto-fill all fields, user just confirms<br>    applyAllParsedFields()<br>case 0.5..&lt;0.8:<br>    // Show parsed result with &quot;review&quot; indicators<br>    applyParsedFieldsWithReview()<br>default:<br>    // Fall back to manual entry with title pre-filled<br>    showManualEntryWithTitle(parsedEvent.title)<br>}</pre><h3>Performance Considerations</h3><p>Calling an LLM API adds latency. Here’s how I kept the UX snappy:</p><p><strong>1. Optimistic UI</strong> — The event card appears immediately with a loading indicator on the AI-parsed fields. The user sees something happen instantly.</p><p><strong>2. Caching common patterns</strong> — “New Year’s Eve” always maps to December 31. No need to call the API for well-known events.</p><p><strong>3. Timeout with fallback</strong> — If the API doesn’t respond within 5 seconds, fall back to manual entry. Don’t block the user.</p><p><strong>4. Batch context</strong> — Send timezone, locale, and current date in one payload. Don’t make multiple round trips.</p><h3>Lessons Learned</h3><p><strong>1. Domain context beats general intelligence.</strong> A general date parser fails on “bu cuma” ambiguity. But knowing that “people create countdowns for future events” resolves it instantly. Always inject domain knowledge into your prompts.</p><p><strong>2. Turkish NLP is underserved.</strong> Most NLP tools are English-first. If you’re building for Turkish users, expect to do more custom work. The good news: LLMs handle Turkish surprisingly well if you prompt them correctly.</p><p><strong>3. Confidence scores are essential.</strong> Don’t trust the model blindly. Give users a way to correct mistakes, and make the correction flow frictionless.</p><p><strong>4. Cloud Functions are the right abstraction.</strong> Keeping the LLM call server-side lets you iterate on prompts without shipping app updates. I’ve tweaked the prompt 15+ times since launch without touching the iOS code.</p><p><strong>5. Users love it.</strong> The NPS bump from AI event creation was significant. Users who discover it use it for 80%+ of their event creation. The friction reduction is real.</p><h3>What’s Next</h3><p>I’m exploring:</p><ul><li><strong>Multi-event parsing</strong> — “Tarkan concert Friday and Beşiktaş match Sunday” creating two events at once</li><li><strong>Recurring events</strong> — “Yoga every Wednesday 7pm”</li><li><strong>Context from past events</strong> — If you’ve been to Kuruçeşme Arena before, auto-fill the location details</li></ul><p>Building AI features for a consumer app is a different challenge than building AI for AI’s sake. The model doesn’t need to be perfect — it needs to be <em>useful enough</em> that users prefer it over the alternative. And for event creation in Dayping, we’re there.</p><p><em>Dayping is a free event countdown app for iOS.</em></p><p><em>I’m building Dayping in public. Follow me on X </em><a href="https://x.com/onuryz00"><em>@onuryz00</em></a><em> for updates.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=09f7682abfa7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[End-to-End SAP Automation with ADT REST Services and AI: A Modern Alternative to GUI Scripting]]></title>
            <link>https://medium.com/@onuryz.itu/end-to-end-sap-automation-with-adt-rest-services-and-ai-a-modern-alternative-to-gui-scripting-343ea86064ea?source=rss-98880ec83529------2</link>
            <guid isPermaLink="false">https://medium.com/p/343ea86064ea</guid>
            <category><![CDATA[sap]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Onur Yılmaz]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 13:29:24 GMT</pubDate>
            <atom:updated>2026-03-09T13:29:24.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8o28qWcWtHFRMpXD1-KwCQ.png" /></figure><p><em>Why REST-based ADT Services Are the Future of SAP–AI Integration</em></p><h3>Introduction</h3><p>SAP GUI Scripting has been the go-to approach for automating repetitive SAP tasks for years. While it works, it comes with significant limitations: it depends on screen element IDs that break with UI changes, requires a running SAP GUI instance on Windows, and operates at the speed of the GUI renderer — making it fundamentally fragile, platform-locked, and slow.</p><p>There is a better way. <strong>ABAP Development Tools (ADT)</strong> exposes a comprehensive set of <strong>REST APIs</strong> over HTTP(S) at the /sap/bc/adt/ endpoint. These are the same APIs that power Eclipse ADT under the hood. By leveraging these services directly, AI agents can interact with SAP systems <strong>headlessly, cross-platform, and at API speed</strong> — no GUI required.</p><p>This article presents a complete guide to building AI-powered SAP automation using ADT REST services with Python, covering everything from connection setup to customizing, reporting, transport management, and ATC checks.</p><h3>1. GUI Scripting vs. ADT REST Services: Why It Matters</h3><p><strong>Protocol</strong> GUI Scripting → COM automation, Windows only. ADT REST → HTTP/S, works on any platform.</p><p><strong>Speed</strong> GUI Scripting → UI render speed, seconds per screen. ADT REST → API speed, milliseconds per call.</p><p><strong>Stability</strong> GUI Scripting → Breaks with UI/theme changes. ADT REST → Stable, contract-based endpoints.</p><p><strong>Parallelism</strong> GUI Scripting → Single session, sequential execution. ADT REST → Multi-threaded, concurrent requests.</p><p><strong>Headless Execution</strong> GUI Scripting → No, needs a visible SAP GUI window. ADT REST → Yes, pure HTTP calls.</p><p><strong>AI-Friendly</strong> GUI Scripting → No, requires screen-by-screen navigation. ADT REST → Yes, structured JSON/XML input and output.</p><p><strong>CI/CD Ready</strong> GUI Scripting → No. ADT REST → Yes, runs in containers and pipelines.</p><p>The core argument is simple: <strong>AI agents should communicate with SAP through structured APIs, not by simulating mouse clicks on a GUI.</strong> ADT REST services provide exactly this capability.</p><h3>2. Architecture Overview</h3><p>The architecture is straightforward. On the left side, your <strong>AI Agent</strong> (Python, MCP Server, Claude, LangChain) sends HTTPS requests with Basic Auth to the SAP system. On the right side, the <strong>SAP ABAP Backend</strong> (S/4HANA or ECC) serves the /sap/bc/adt/* endpoints through the ICF handler and returns XML or JSON responses.</p><p>The AI layer can be Claude Tool Use, GPT function calling, LangChain agents, or a standalone MCP server. The SAP layer requires SICF service activation, the ADT framework, and proper authorization objects.</p><blockquote>💡 I recommend adding a simple diagram image here when publishing on Medium. Use draw.io or Excalidraw to create a clean visual of this flow.</blockquote><h3>3. Prerequisites</h3><h3>3.1 SAP Backend Configuration</h3><p><strong>SICF Service Activation</strong> — The following services must be active in transaction SICF:</p><p><strong>/sap/bc/adt</strong> — Core ADT framework (min. 7.31 SP04) <strong>/sap/bc/adt/discovery</strong> — Service discovery via Atom feed (min. 7.31 SP04) <strong>/sap/bc/adt/datapreview</strong> — Table data preview, SE16N alternative (min. 7.40 SP05) <strong>/sap/bc/adt/cts</strong> — Transport request management (min. 7.40 SP02) <strong>/sap/bc/adt/ddic</strong> — Data Dictionary access (min. 7.40 SP02) <strong>/sap/bc/adt/atc</strong> — ABAP Test Cockpit (min. 7.50+) <strong>/sap/bc/adt/oo</strong> — Classes and interfaces (min. 7.31 SP04) <strong>/sap/bc/adt/programs</strong> — Programs and includes (min. 7.31 SP04) <strong>/sap/bc/adt/functions</strong> — Function groups and modules (min. 7.31 SP04) <strong>/sap/bc/adt/repository</strong> — Repository search (min. 7.31 SP04)</p><p><strong>Authorization Objects:</strong></p><ul><li>S_ADT_RES — Required for all ADT API access</li><li>S_DEVELOP — For object read/write operations</li><li>S_CTS_ADMI — For transport management</li><li>S_TRANSPRT — For transport release</li></ul><p><strong>Authentication:</strong> ADT REST APIs support <strong>Basic Authentication</strong> over HTTPS. Form-based authentication is not supported. Ensure your ICF configuration is set accordingly. For production scenarios, consider <strong>X.509 certificate-based authentication</strong> or <strong>SAP OAuth 2.0</strong>.</p><h3>3.2 Client Environment</h3><pre># Python 3.10+<br>pip install requests httpx openpyxl lxml</pre><pre># For AI integration<br>pip install anthropic langchain openai</pre><pre># For MCP-based integration<br>pip install mcp</pre><h3>4. Connection Layer: adt_client.py</h3><p>The foundation of any ADT automation is a robust HTTP client that handles authentication, session management, and CSRF token handling.</p><pre>&quot;&quot;&quot;<br>ADT REST Client — Stateful session manager for SAP ADT APIs.<br>Handles authentication, CSRF tokens, and connection pooling.<br>&quot;&quot;&quot;</pre><pre>import requests<br>from dataclasses import dataclass<br>from typing import Optional, Dict, Any<br>from urllib.parse import urljoin<br>import logging<br>import xml.etree.ElementTree as ET</pre><pre>log = logging.getLogger(__name__)<br></pre><pre>@dataclass<br>class ADTConfig:<br>    base_url: str          # e.g. &quot;https://sap-host:44300&quot;<br>    client: str            # e.g. &quot;100&quot;<br>    user: str<br>    password: str<br>    language: str = &quot;EN&quot;<br>    verify_ssl: bool = True<br></pre><pre>class ADTClient:<br>    &quot;&quot;&quot;Stateful ADT REST client with automatic CSRF handling.&quot;&quot;&quot;</pre><pre>    CSRF_HEADER = &quot;x-csrf-token&quot;<br>    CSRF_FETCH = &quot;Fetch&quot;</pre><pre>    def __init__(self, config: ADTConfig):<br>        self.config = config<br>        self.session = requests.Session()<br>        self.session.auth = (config.user, config.password)<br>        self.session.verify = config.verify_ssl<br>        self.session.headers.update({<br>            &quot;Accept&quot;: &quot;application/xml&quot;,<br>            &quot;Accept-Language&quot;: config.language,<br>            &quot;sap-client&quot;: config.client,<br>        })<br>        self._csrf_token: Optional[str] = None</pre><pre>    def _url(https://medium.com/self,%20path:%20str) -&gt; str:<br>        return urljoin(<br>            self.config.base_url, f&quot;/sap/bc/adt/{path}&quot;<br>        )</pre><pre>    def fetch_csrf_token(self) -&gt; str:<br>        &quot;&quot;&quot;Fetch CSRF token — required before any<br>        write operation.&quot;&quot;&quot;<br>        resp = self.session.get(<br>            self._url(https://medium.com/&quot;discovery&quot;),<br>            headers={self.CSRF_HEADER: self.CSRF_FETCH},<br>        )<br>        resp.raise_for_status()<br>        self._csrf_token = resp.headers.get(<br>            self.CSRF_HEADER<br>        )<br>        log.info(&quot;CSRF token acquired&quot;)<br>        return self._csrf_token</pre><pre>    def get(self, path: str, **kwargs) -&gt; requests.Response:<br>        &quot;&quot;&quot;GET request to ADT endpoint.&quot;&quot;&quot;<br>        resp = self.session.get(self._url(https://medium.com/path), **kwargs)<br>        resp.raise_for_status()<br>        return resp</pre><pre>    def post(self, path: str, **kwargs) -&gt; requests.Response:<br>        &quot;&quot;&quot;POST request with CSRF token handling.&quot;&quot;&quot;<br>        if not self._csrf_token:<br>            self.fetch_csrf_token()<br>        headers = kwargs.pop(&quot;headers&quot;, {})<br>        headers[self.CSRF_HEADER] = self._csrf_token<br>        resp = self.session.post(<br>            self._url(https://medium.com/path), headers=headers, **kwargs<br>        )<br>        # Token expired — refetch and retry once<br>        if resp.status_code == 403:<br>            self.fetch_csrf_token()<br>            headers[self.CSRF_HEADER] = self._csrf_token<br>            resp = self.session.post(<br>                self._url(https://medium.com/path), headers=headers, **kwargs<br>            )<br>        resp.raise_for_status()<br>        return resp</pre><pre>    def put(self, path: str, **kwargs) -&gt; requests.Response:<br>        &quot;&quot;&quot;PUT request with CSRF token handling.&quot;&quot;&quot;<br>        if not self._csrf_token:<br>            self.fetch_csrf_token()<br>        headers = kwargs.pop(&quot;headers&quot;, {})<br>        headers[self.CSRF_HEADER] = self._csrf_token<br>        resp = self.session.put(<br>            self._url(https://medium.com/path), headers=headers, **kwargs<br>        )<br>        if resp.status_code == 403:<br>            self.fetch_csrf_token()<br>            headers[self.CSRF_HEADER] = self._csrf_token<br>            resp = self.session.put(<br>                self._url(https://medium.com/path), headers=headers, **kwargs<br>            )<br>        resp.raise_for_status()<br>        return resp</pre><pre>    def ping(self) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Test connection by hitting the discovery<br>        endpoint.&quot;&quot;&quot;<br>        resp = self.get(&quot;discovery&quot;)<br>        log.info(<br>            &quot;ADT connection successful — HTTP %s&quot;,<br>            resp.status_code<br>        )<br>        return {<br>            &quot;status&quot;: resp.status_code,<br>            &quot;content_type&quot;: resp.headers.get(<br>                &quot;content-type&quot;<br>            ),<br>        }</pre><h3>Key Design Decisions</h3><p><strong>CSRF Token Handling:</strong> ADT endpoints require a CSRF token for all write operations (POST, PUT, DELETE). The token is fetched from the /sap/bc/adt/discovery endpoint and automatically refreshed on 403 responses.</p><p><strong>Stateful Sessions:</strong> ADT uses stateful HTTP sessions. The requests.Session object maintains cookies and connection pooling across calls, which is critical for operations like object locking.</p><p><strong>SAP Client Header:</strong> The sap-client header specifies the SAP client number — equivalent to the client field on the login screen.</p><h3>5. Service Discovery</h3><p>Before calling any endpoint, you can query the discovery service to see what’s available on your system:</p><pre>def discover_services(client: ADTClient) -&gt; list:<br>    &quot;&quot;&quot;Parse the ADT Atom feed to list available<br>    services.&quot;&quot;&quot;<br>    resp = client.get(&quot;discovery&quot;)<br>    root = ET.fromstring(resp.content)</pre><pre>    ns = {<br>        &quot;app&quot;: &quot;http://www.w3.org/2007/app&quot;,<br>        &quot;atom&quot;: &quot;http://www.w3.org/2005/Atom&quot;,<br>    }</pre><pre>    services = []<br>    for collection in root.findall(<br>        &quot;.//app:collection&quot;, ns<br>    ):<br>        href = collection.attrib.get(&quot;href&quot;, &quot;&quot;)<br>        title_el = collection.find(&quot;atom:title&quot;, ns)<br>        title = (<br>            title_el.text if title_el is not None<br>            else &quot;&quot;<br>        )<br>        services.append({<br>            &quot;href&quot;: href, &quot;title&quot;: title<br>        })</pre><pre>    return services</pre><p>This is the programmatic equivalent of checking SICF — it tells you exactly which ADT services are activated on the target system.</p><h3>6. Table Data Reading (SE16N Alternative)</h3><p>The /sap/bc/adt/datapreview/ endpoint replaces the need for SE16N transaction automation entirely.</p><pre>def read_table(<br>    client: ADTClient,<br>    table_name: str,<br>    max_rows: int = 100,<br>) -&gt; list[dict]:<br>    &quot;&quot;&quot;<br>    Read table data via ADT Data Preview API.<br>    Equivalent to SE16N but over REST.<br>    &quot;&quot;&quot;<br>    body = f&quot;&quot;&quot;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>    &lt;dataPreview:tableSettings<br>      xmlns:dataPreview=<br>        &quot;http://www.sap.com/adt/dataPreview&quot;&gt;<br>      &lt;dataPreview:column&gt;*&lt;/dataPreview:column&gt;<br>      &lt;dataPreview:maxRows&gt;<br>        {max_rows}<br>      &lt;/dataPreview:maxRows&gt;<br>    &lt;/dataPreview:tableSettings&gt;&quot;&quot;&quot;</pre><pre>    resp = client.post(<br>        f&quot;datapreview/{table_name.upper()}&quot;,<br>        data=body,<br>        headers={&quot;Content-Type&quot;: &quot;application/xml&quot;},<br>    )</pre><pre>    # Parse the XML response into a list of dicts<br>    root = ET.fromstring(resp.content)<br>    columns = []<br>    rows = []</pre><pre>    ns = &quot;http://www.sap.com/adt/dataPreview&quot;<br>    for col in root.iter(f&quot;{{{ns}}}column&quot;):<br>        columns.append(col.attrib.get(&quot;name&quot;, &quot;&quot;))</pre><pre>    for row in root.iter(f&quot;{{{ns}}}row&quot;):<br>        record = {}<br>        for i, val in enumerate(row):<br>            if i &lt; len(columns):<br>                record[columns[i]] = val.text or &quot;&quot;<br>        rows.append(record)</pre><pre>    return rows</pre><p>Usage example:</p><pre>config = ADTConfig(<br>    base_url=&quot;https://sap-server:44300&quot;,<br>    client=&quot;100&quot;,<br>    user=&quot;DEVELOPER&quot;,<br>    password=&quot;***&quot;,<br>)<br>client = ADTClient(config)<br>sales_orders = read_table(client, &quot;VBAK&quot;, max_rows=500)</pre><p><strong>Why this is better than SE16N scripting:</strong></p><ul><li>No need to navigate transaction screens, fill selection fields, press F8</li><li>Directly get structured data — no ALV grid parsing required</li><li>Works headlessly in any Python environment</li><li>Can be parallelized across multiple tables</li></ul><h3>7. ABAP Object Management</h3><h3>7.1 Search Repository Objects</h3><pre>def search_objects(<br>    client: ADTClient,<br>    query: str,<br>    object_type: str = &quot;&quot;,<br>) -&gt; list[dict]:<br>    &quot;&quot;&quot;<br>    Search the ABAP repository.<br>    object_type: CLAS, PROG, FUGR, TABL, DTEL,<br>                 DOMA, etc.<br>    &quot;&quot;&quot;<br>    params = {<br>        &quot;operation&quot;: &quot;quickSearch&quot;,<br>        &quot;query&quot;: query,<br>        &quot;maxResults&quot;: &quot;50&quot;,<br>    }<br>    if object_type:<br>        params[&quot;objectType&quot;] = object_type</pre><pre>    resp = client.get(<br>        &quot;repository/informationsystem/search&quot;,<br>        params=params,<br>    )</pre><pre>    ns = (&quot;http://www.sap.com/adt/repository/&quot;<br>          &quot;informationsystem&quot;)<br>    root = ET.fromstring(resp.content)<br>    results = []<br>    for obj in root.iter(f&quot;{{{ns}}}object&quot;):<br>        results.append({<br>            &quot;name&quot;: obj.attrib.get(&quot;name&quot;, &quot;&quot;),<br>            &quot;type&quot;: obj.attrib.get(&quot;type&quot;, &quot;&quot;),<br>            &quot;uri&quot;: obj.attrib.get(&quot;uri&quot;, &quot;&quot;),<br>            &quot;package&quot;: obj.attrib.get(<br>                &quot;packageName&quot;, &quot;&quot;<br>            ),<br>        })<br>    return results</pre><h3>7.2 Read and Write Object Source Code</h3><pre>def read_source(<br>    client: ADTClient, object_path: str<br>) -&gt; str:<br>    &quot;&quot;&quot;<br>    Read source code of an ABAP object.</pre><pre>    object_path examples:<br>      &quot;oo/classes/zcl_my_class/source/main&quot;<br>      &quot;programs/programs/zmy_report/source/main&quot;<br>      &quot;functions/groups/zfg/fmodules/zfm/source/main&quot;<br>    &quot;&quot;&quot;<br>    resp = client.get(<br>        object_path,<br>        headers={&quot;Accept&quot;: &quot;text/plain&quot;},<br>    )<br>    return resp.text<br></pre><pre>def write_source(<br>    client: ADTClient,<br>    object_path: str,<br>    source: str,<br>    lock_handle: str,<br>) -&gt; None:<br>    &quot;&quot;&quot;Write source code — requires prior lock.&quot;&quot;&quot;<br>    client.put(<br>        object_path,<br>        data=source.encode(&quot;utf-8&quot;),<br>        headers={<br>            &quot;Content-Type&quot;:<br>                &quot;text/plain; charset=utf-8&quot;,<br>            &quot;X-sap-adt-lockhandle&quot;: lock_handle,<br>        },<br>    )</pre><h3>7.3 Lock / Unlock / Activate</h3><p>ADT uses a <strong>lock → edit → unlock → activate</strong> workflow for write operations:</p><pre>def lock_object(<br>    client: ADTClient, object_uri: str<br>) -&gt; str:<br>    &quot;&quot;&quot;Lock an ABAP object for editing.<br>    Returns lock handle.&quot;&quot;&quot;<br>    resp = client.post(<br>        object_uri,<br>        params={<br>            &quot;_action&quot;: &quot;LOCK&quot;,<br>            &quot;accessMode&quot;: &quot;MODIFY&quot;,<br>        },<br>    )<br>    root = ET.fromstring(resp.content)<br>    return root.attrib.get(&quot;LOCK_HANDLE&quot;, &quot;&quot;)<br></pre><pre>def unlock_object(<br>    client: ADTClient,<br>    object_uri: str,<br>    lock_handle: str,<br>) -&gt; None:<br>    &quot;&quot;&quot;Release the lock on an ABAP object.&quot;&quot;&quot;<br>    client.post(<br>        object_uri,<br>        params={<br>            &quot;_action&quot;: &quot;UNLOCK&quot;,<br>            &quot;lockHandle&quot;: lock_handle,<br>        },<br>    )<br></pre><pre>def activate_object(<br>    client: ADTClient,<br>    object_name: str,<br>    object_uri: str,<br>) -&gt; dict:<br>    &quot;&quot;&quot;Activate an ABAP object after modification.&quot;&quot;&quot;<br>    body = (<br>        &#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&#39;<br>        &#39;&lt;adtcore:objectReferences &#39;<br>        &#39;xmlns:adtcore=&#39;<br>        &#39;&quot;http://www.sap.com/adt/core&quot;&gt;&#39;<br>        &#39;&lt;adtcore:objectReference &#39;<br>        f&#39;adtcore:name=&quot;{object_name}&quot; &#39;<br>        f&#39;adtcore:uri=&quot;/{object_uri}&quot;/&gt;&#39;<br>        &#39;&lt;/adtcore:objectReferences&gt;&#39;<br>    )</pre><pre>    resp = client.post(<br>        &quot;activation&quot;,<br>        data=body,<br>        headers={&quot;Content-Type&quot;: &quot;application/xml&quot;},<br>    )<br>    return {&quot;status&quot;: resp.status_code}</pre><h3>8. Transport Request Management</h3><p>The /sap/bc/adt/cts/ endpoints replace manual transport operations:</p><pre>def list_transport_requests(<br>    client: ADTClient,<br>    user: str = &quot;&quot;,<br>    status: str = &quot;D&quot;,<br>) -&gt; list[dict]:<br>    &quot;&quot;&quot;<br>    List transport requests.<br>    status: D = modifiable, R = released<br>    &quot;&quot;&quot;<br>    params = {<br>        &quot;user&quot;: user or client.config.user,<br>        &quot;status&quot;: status,<br>    }<br>    resp = client.get(<br>        &quot;cts/transportrequests&quot;, params=params<br>    )</pre><pre>    root = ET.fromstring(resp.content)<br>    ns = {&quot;cts&quot;: &quot;http://www.sap.com/adt/cts&quot;}<br>    results = []</pre><pre>    for req in root.findall(&quot;.//cts:request&quot;, ns):<br>        results.append({<br>            &quot;number&quot;: req.attrib.get(&quot;number&quot;, &quot;&quot;),<br>            &quot;description&quot;: req.attrib.get(<br>                &quot;description&quot;, &quot;&quot;<br>            ),<br>            &quot;owner&quot;: req.attrib.get(&quot;owner&quot;, &quot;&quot;),<br>            &quot;status&quot;: req.attrib.get(&quot;status&quot;, &quot;&quot;),<br>        })<br>    return results<br></pre><pre>def create_transport_request(<br>    client: ADTClient,<br>    description: str,<br>    target_system: str = &quot;&quot;,<br>) -&gt; str:<br>    &quot;&quot;&quot;Create a new workbench transport request.&quot;&quot;&quot;<br>    body = (<br>        &#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&#39;<br>        &#39;&lt;cts:request &#39;<br>        &#39;xmlns:cts=&quot;http://www.sap.com/adt/cts&quot; &#39;<br>        &#39;cts:type=&quot;K&quot; &#39;<br>        f&#39;cts:description=&quot;{description}&quot; &#39;<br>        f&#39;cts:target=&quot;{target_system}&quot;/&gt;&#39;<br>    )</pre><pre>    resp = client.post(<br>        &quot;cts/transportrequests&quot;,<br>        data=body,<br>        headers={&quot;Content-Type&quot;: &quot;application/xml&quot;},<br>    )</pre><pre>    root = ET.fromstring(resp.content)<br>    return root.attrib.get(&quot;number&quot;, &quot;&quot;)<br></pre><pre>def release_transport(<br>    client: ADTClient, request_number: str<br>) -&gt; dict:<br>    &quot;&quot;&quot;Release a transport request.&quot;&quot;&quot;<br>    resp = client.post(<br>        f&quot;cts/transportrequests/&quot;<br>        f&quot;{request_number}/newreleasejobs&quot;,<br>    )<br>    return {<br>        &quot;status&quot;: resp.status_code,<br>        &quot;request&quot;: request_number,<br>    }</pre><h3>9. ATC (ABAP Test Cockpit) Integration</h3><p>Run automated code quality checks directly from your AI pipeline:</p><pre>def run_atc_check(<br>    client: ADTClient, object_uri: str<br>) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Run ATC checks on an ABAP object.<br>    Returns findings with severity and message.<br>    &quot;&quot;&quot;<br>    # Step 1: Create an ATC run<br>    body = (<br>        &#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;&#39;<br>        &#39;&lt;atc:run &#39;<br>        &#39;xmlns:atc=&quot;http://www.sap.com/adt/atc&quot; &#39;<br>        &#39;maximumViolations=&quot;100&quot;&gt;&#39;<br>        &#39;&lt;objectSets &#39;<br>        &#39;xmlns:adtcore=&quot;http://www.sap.com/adt/core&quot;&gt;&#39;<br>        &#39;&lt;objectSet kind=&quot;inclusive&quot;&gt;&#39;<br>        &#39;&lt;adtcore:objectReferences&gt;&#39;<br>        &#39;&lt;adtcore:objectReference &#39;<br>        f&#39;adtcore:uri=&quot;/{object_uri}&quot;/&gt;&#39;<br>        &#39;&lt;/adtcore:objectReferences&gt;&#39;<br>        &#39;&lt;/objectSet&gt;&#39;<br>        &#39;&lt;/objectSets&gt;&#39;<br>        &#39;&lt;/atc:run&gt;&#39;<br>    )</pre><pre>    resp = client.post(<br>        &quot;atc/runs&quot;,<br>        data=body,<br>        headers={&quot;Content-Type&quot;: &quot;application/xml&quot;},<br>    )</pre><pre>    # Step 2: Extract run ID and fetch results<br>    run_id = resp.headers.get(<br>        &quot;Location&quot;, &quot;&quot;<br>    ).split(&quot;/&quot;)[-1]</pre><pre>    results_resp = client.get(<br>        f&quot;atc/runs/{run_id}/results&quot;<br>    )<br>    root = ET.fromstring(results_resp.content)</pre><pre>    findings = []<br>    ns = {&quot;atc&quot;: &quot;http://www.sap.com/adt/atc&quot;}<br>    for finding in root.findall(<br>        &quot;.//atc:finding&quot;, ns<br>    ):<br>        findings.append({<br>            &quot;priority&quot;: finding.attrib.get(<br>                &quot;priority&quot;, &quot;&quot;<br>            ),<br>            &quot;message&quot;: finding.attrib.get(<br>                &quot;messageTitle&quot;, &quot;&quot;<br>            ),<br>            &quot;location&quot;: finding.attrib.get(<br>                &quot;location&quot;, &quot;&quot;<br>            ),<br>            &quot;check_id&quot;: finding.attrib.get(<br>                &quot;checkId&quot;, &quot;&quot;<br>            ),<br>        })</pre><pre>    return {&quot;run_id&quot;: run_id, &quot;findings&quot;: findings}</pre><h3>10. Customizing Read/Write via Data Preview</h3><p>For reading customizing tables, the data preview API works directly:</p><pre># Read shipping condition config<br>shipping = read_table(client, &quot;T685&quot;, max_rows=1000)</pre><pre># Read pricing procedures<br>pricing = read_table(client, &quot;T683S&quot;, max_rows=500)</pre><pre># Read output types<br>outputs = read_table(client, &quot;T685B&quot;, max_rows=500)</pre><p>For <strong>writing</strong> customizing data, there are two practical approaches:</p><p><strong>Approach A — Custom OData/REST Service:</strong> Create a thin ABAP wrapper (RFC or OData) that exposes customizing maintenance logic. This is the cleanest and most controlled approach.</p><p><strong>Approach B — BDC Recording via ADT:</strong> Use ADT to trigger batch input sessions for transactions like OVX4, OVXI, OVXB. While less elegant, it provides a bridge for scenarios where direct table manipulation is not feasible.</p><pre>def run_program(<br>    client: ADTClient,<br>    program_name: str,<br>    variant: str = &quot;&quot;,<br>) -&gt; dict:<br>    &quot;&quot;&quot;Execute an ABAP program via ADT.&quot;&quot;&quot;<br>    params = {<br>        &quot;sap-language&quot;: client.config.language<br>    }<br>    if variant:<br>        params[&quot;variant&quot;] = variant</pre><pre>    resp = client.post(<br>        f&quot;programs/programs/&quot;<br>        f&quot;{program_name.lower()}/run&quot;,<br>        params=params,<br>    )<br>    return {&quot;status&quot;: resp.status_code}</pre><h3>11. AI Integration Patterns</h3><h3>11.1 Claude Tool Use (Function Calling)</h3><pre>from anthropic import Anthropic</pre><pre>client_ai = Anthropic()<br>adt = ADTClient(config)</pre><pre>tools = [<br>    {<br>        &quot;name&quot;: &quot;read_sap_table&quot;,<br>        &quot;description&quot;: (<br>            &quot;Read data from an SAP table. &quot;<br>            &quot;Use for reporting and data extraction.&quot;<br>        ),<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;table_name&quot;: {<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;description&quot;: (<br>                        &quot;SAP table name, &quot;<br>                        &quot;e.g. VBAK, MARA, KNA1&quot;<br>                    ),<br>                },<br>                &quot;max_rows&quot;: {<br>                    &quot;type&quot;: &quot;integer&quot;,<br>                    &quot;description&quot;:<br>                        &quot;Maximum rows to return&quot;,<br>                    &quot;default&quot;: 100,<br>                },<br>            },<br>            &quot;required&quot;: [&quot;table_name&quot;],<br>        },<br>    },<br>    {<br>        &quot;name&quot;: &quot;search_abap_objects&quot;,<br>        &quot;description&quot;: (<br>            &quot;Search the ABAP repository for classes, &quot;<br>            &quot;programs, function modules, etc.&quot;<br>        ),<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;query&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                &quot;object_type&quot;: {<br>                    &quot;type&quot;: &quot;string&quot;,<br>                    &quot;enum&quot;: [<br>                        &quot;CLAS&quot;, &quot;PROG&quot;, &quot;FUGR&quot;,<br>                        &quot;TABL&quot;, &quot;DTEL&quot;,<br>                    ],<br>                },<br>            },<br>            &quot;required&quot;: [&quot;query&quot;],<br>        },<br>    },<br>    {<br>        &quot;name&quot;: &quot;read_abap_source&quot;,<br>        &quot;description&quot;:<br>            &quot;Read the source code of an ABAP object.&quot;,<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;object_path&quot;: {&quot;type&quot;: &quot;string&quot;},<br>            },<br>            &quot;required&quot;: [&quot;object_path&quot;],<br>        },<br>    },<br>    {<br>        &quot;name&quot;: &quot;run_atc_check&quot;,<br>        &quot;description&quot;: (<br>            &quot;Run ABAP Test Cockpit quality checks &quot;<br>            &quot;on an object.&quot;<br>        ),<br>        &quot;input_schema&quot;: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;object_uri&quot;: {&quot;type&quot;: &quot;string&quot;},<br>            },<br>            &quot;required&quot;: [&quot;object_uri&quot;],<br>        },<br>    },<br>]</pre><pre># The AI agent can now reason about SAP data<br>response = client_ai.messages.create(<br>    model=&quot;claude-sonnet-4-6&quot;,<br>    max_tokens=4096,<br>    tools=tools,<br>    messages=[{<br>        &quot;role&quot;: &quot;user&quot;,<br>        &quot;content&quot;: (<br>            &quot;Show me all sales orders from table &quot;<br>            &quot;VBAK created in the last month, then &quot;<br>            &quot;find any custom Z-classes related to &quot;<br>            &quot;sales order processing.&quot;<br>        ),<br>    }],<br>)</pre><h3>11.2 MCP Server Integration</h3><p>The <strong>Model Context Protocol (MCP)</strong> is the most seamless way to connect AI agents to SAP. Several community MCP servers already exist:</p><p><strong>sap-adt-mcp-server</strong> — Eclipse plugin bridging Claude Code to ABAP via ADT</p><p><strong>mcp-abap-adt</strong> — Standalone MCP server wrapping ADT REST APIs</p><p><strong>abap-adt-api</strong> (npm) — JavaScript/TypeScript ADT client used by MCP servers</p><p>These allow Claude, Cursor, or any MCP-compatible AI to directly read ABAP code, search objects, and run checks against a live SAP system.</p><h3>11.3 LangChain Agent</h3><pre>from langchain.agents import tool<br>from langchain_anthropic import ChatAnthropic</pre><pre>@tool<br>def sap_table_query(<br>    table_name: str, max_rows: int = 100<br>) -&gt; str:<br>    &quot;&quot;&quot;Query an SAP table and return results<br>    as formatted text.&quot;&quot;&quot;<br>    rows = read_table(<br>        adt, table_name, max_rows=max_rows<br>    )<br>    if not rows:<br>        return f&quot;No data found in {table_name}&quot;<br>    headers = list(rows[0].keys())<br>    lines = [&quot; | &quot;.join(headers)]<br>    for row in rows[:20]:<br>        lines.append(<br>            &quot; | &quot;.join(<br>                str(row.get(h, &quot;&quot;)) for h in headers<br>            )<br>        )<br>    return &quot;\n&quot;.join(lines)</pre><pre>@tool<br>def sap_search(<br>    query: str, object_type: str = &quot;&quot;<br>) -&gt; str:<br>    &quot;&quot;&quot;Search SAP ABAP repository for objects<br>    matching the query.&quot;&quot;&quot;<br>    results = search_objects(<br>        adt, query, object_type<br>    )<br>    return &quot;\n&quot;.join(<br>        f&quot;{r[&#39;type&#39;]} {r[&#39;name&#39;]} ({r[&#39;package&#39;]})&quot;<br>        for r in results<br>    )</pre><pre>llm = ChatAnthropic(model=&quot;claude-sonnet-4-6&quot;)<br># Build agent with these tools...</pre><h3>12. Excel Report Generation</h3><p>Combine ADT data extraction with Python reporting:</p><pre>from openpyxl import Workbook<br>from openpyxl.chart import BarChart, Reference<br>from datetime import datetime<br></pre><pre>def generate_sales_report(<br>    client: ADTClient, output_path: str<br>):<br>    &quot;&quot;&quot;Generate a sales report from VBAK data.&quot;&quot;&quot;<br>    data = read_table(client, &quot;VBAK&quot;, max_rows=5000)</pre><pre>    wb = Workbook()</pre><pre>    # Sheet 1: Summary<br>    ws_summary = wb.active<br>    ws_summary.title = &quot;Summary&quot;<br>    ws_summary.append([<br>        &quot;Generated&quot;, datetime.now().isoformat()<br>    ])<br>    ws_summary.append([&quot;Source Table&quot;, &quot;VBAK&quot;])<br>    ws_summary.append([&quot;Total Records&quot;, len(data)])<br>    ws_summary.append([])</pre><pre>    # Sheet 2: Raw Data<br>    ws_data = wb.create_sheet(&quot;Raw Data&quot;)<br>    if data:<br>        headers = list(data[0].keys())<br>        ws_data.append(headers)<br>        for row in data:<br>            ws_data.append([<br>                row.get(h, &quot;&quot;) for h in headers<br>            ])</pre><pre>    # Sheet 3: Chart<br>    ws_chart = wb.create_sheet(&quot;Analysis&quot;)<br>    # Add aggregation and chart logic here...</pre><pre>    wb.save(output_path)<br>    return output_path</pre><h3>13. Complete Workflow Example</h3><p>Here is an end-to-end scenario: an AI agent reads sales data, identifies anomalies, checks related custom code quality, and produces a report.</p><pre>def ai_sap_workflow(config: ADTConfig):<br>    &quot;&quot;&quot;Complete AI-powered SAP workflow.&quot;&quot;&quot;</pre><pre>    adt = ADTClient(config)<br>    adt.ping()  # Verify connection</pre><pre>    # 1. Read sales order data<br>    orders = read_table(adt, &quot;VBAK&quot;, max_rows=1000)<br>    print(f&quot;Retrieved {len(orders)} sales orders&quot;)</pre><pre>    # 2. Read billing documents<br>    billings = read_table(<br>        adt, &quot;VBRK&quot;, max_rows=1000<br>    )<br>    print(<br>        f&quot;Retrieved {len(billings)} billing docs&quot;<br>    )</pre><pre>    # 3. Search for custom sales processing code<br>    custom_classes = search_objects(<br>        adt, &quot;ZCL_SALES*&quot;, &quot;CLAS&quot;<br>    )<br>    print(<br>        f&quot;Found {len(custom_classes)} custom classes&quot;<br>    )</pre><pre>    # 4. Run ATC on each custom class<br>    for cls in custom_classes:<br>        findings = run_atc_check(adt, cls[&quot;uri&quot;])<br>        count = len(findings[&quot;findings&quot;])<br>        print(f&quot;  {cls[&#39;name&#39;]}: {count} findings&quot;)</pre><pre>    # 5. Read source of critical classes<br>    for cls in custom_classes[:5]:<br>        source = read_source(<br>            adt,<br>            f&quot;oo/classes/&quot;<br>            f&quot;{cls[&#39;name&#39;].lower()}/source/main&quot;,<br>        )<br>        print(<br>            f&quot;  {cls[&#39;name&#39;]}: {len(source)} chars&quot;<br>        )</pre><pre>    # 6. Check transport status<br>    transports = list_transport_requests(adt)<br>    open_t = [<br>        t for t in transports<br>        if t[&quot;status&quot;] == &quot;D&quot;<br>    ]<br>    print(f&quot;Open transports: {len(open_t)}&quot;)</pre><pre>    # 7. Generate report<br>    generate_sales_report(adt, &quot;sales_report.xlsx&quot;)<br>    print(&quot;Report generated&quot;)</pre><h3>14. Security Considerations</h3><p><strong>Never hardcode credentials.</strong> Use environment variables, vault services, or SAP Credential Store.</p><p><strong>Use HTTPS only.</strong> ADT APIs should never be exposed over plain HTTP.</p><p><strong>Principle of least privilege.</strong> Create a dedicated service user with only the required S_ADT_RES and specific transaction authorizations.</p><p><strong>Audit logging.</strong> All ADT REST calls are logged in SAP Security Audit Log (SM20) — ensure your compliance team is aware.</p><p><strong>Rate limiting.</strong> Implement client-side rate limiting to avoid overloading the ICF handler.</p><h3>15. Comparison Summary</h3><p><strong>Read table data</strong> GUI Scripting → Navigate SE16N screens, fill filters, parse ALV grid. ADT REST → GET /datapreview/{table} — direct structured response.</p><p><strong>Search ABAP objects</strong> GUI Scripting → Not possible programmatically. ADT REST → GET /repository/.../search — instant results.</p><p><strong>Read ABAP source code</strong> GUI Scripting → Not possible. ADT REST → GET /oo/classes/{name}/source/main</p><p><strong>Modify ABAP source</strong> GUI Scripting → Not practical. ADT REST → PUT with lock handle — clean edit/activate cycle.</p><p><strong>Transport management</strong> GUI Scripting → Handle popups, parse status bar. ADT REST → GET/POST /cts/transportrequests</p><p><strong>ATC quality checks</strong> GUI Scripting → Not possible. ADT REST → POST /atc/runs</p><p><strong>Headless execution</strong> — GUI: No. ADT: Yes. <strong>CI/CD pipeline</strong> — GUI: No. ADT: Yes. <strong>Multi-platform</strong> — GUI: Windows only. ADT: Any OS. <strong>AI-native</strong> — GUI: No. ADT: Yes.</p><h3>Conclusion</h3><p>GUI scripting served its purpose, but it was always a workaround — automating a human interface rather than using a machine interface. ADT REST services provide that machine interface natively.</p><p>By combining ADT REST APIs with modern AI frameworks (Claude Tool Use, MCP, LangChain), organizations can build SAP automation that is faster, more reliable, platform-independent, and truly AI-native. The age of simulating clicks in SAP GUI is over — the age of API-first SAP automation has begun.</p><h3>References</h3><ul><li><a href="https://help.sap.com/doc/2e65ad9a26c84878b1413009f8ac07c3/202210.000/en-US/config_guide_system_backend_abap_development_tools.pdf">SAP ADT Configuration Guide (7.57)</a></li><li><a href="https://community.sap.com/t5/application-development-and-automation-blog-posts/joys-and-sorrows-of-the-abap-developer-tools-api/ba-p/13409390">Joys and Sorrows of the ADT API — SAP Community</a></li><li><a href="https://github.com/marcellourbani/abap-adt-api">abap-adt-api (npm) — GitHub</a></li><li><a href="https://lobehub.com/mcp/serdarbeden-abap-adt-mcp-server">ADT MCP Server for Claude</a></li><li><a href="https://community.sap.com/t5/technology-q-a/looking-for-documentation-on-adt-abap-development-tools-api-endpoints/qaq-p/14217047">SAP Community: ADT API Endpoints Discussion</a></li></ul><p><em>This article demonstrates how AI agents should interact with SAP — not through fragile GUI automation, but through stable, structured REST APIs that were designed for programmatic access.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=343ea86064ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>