---
name: magicline-roaming-integration
description: Build or change an eMSP integration with the MagicLine Roaming Hub over OCPI 2.2.1 (registration, locations, tariffs, remote start and stop, real-time authorization, sessions, charge detail records, monthly settlement). Use when connecting a charging app or e-mobility platform to MagicLine charge points in Bulgaria.
---

# MagicLine Roaming Hub: AI setup guide

This file gives an AI coding agent what it needs to connect an e-mobility platform to the MagicLine
Roaming Hub as an **eMSP** (e-mobility service provider): your drivers find MagicLine charge points in
your app, start and stop charging there, and you receive the session and the final charge detail record
(CDR) at the price agreed for your company.

- Protocol: **OCPI 2.2.1** only.
- Human-readable documentation: https://magiclineenergy.com/bg/en/docs/roaming
- Version of this guide: 2026-11-19. Contact: info@magiclineenergy.com

## How to use this file (for the human)

- **Claude Code:** save this file in your repository as `.claude/skills/magicline-roaming/SKILL.md`,
  then ask: *"Integrate our platform with the MagicLine Roaming Hub using the magicline-roaming-integration
  skill."*
- **Other agents** (Cursor, GitHub Copilot, Codex and others): put the file in your repository, for example
  `docs/magicline-roaming.md`, and point your agent's rules file (`AGENTS.md`, `.cursor/rules`) to it, or
  attach it to the chat.
- **Connection details are not in this file.** MagicLine sends the hub's versions address and a one-time
  registration token to your company privately, first for the test environment and later, separately, for
  production. Keep them in your secret store; never paste them into code, chat logs or commits.

---

## 1. Instructions for the agent

You are implementing the eMSP side of an OCPI 2.2.1 connection to the MagicLine Roaming Hub (called *the
hub* below). Follow this order:

1. **Read this whole file** before writing code. The facts in §3 to §9 are fixed by the hub; do not
   "improve" them from general OCPI knowledge.
2. **Explore the codebase** and find: language and framework, HTTP server and client layers,
   persistence, configuration and secret handling, background job scheduling, logging, any existing OCPI
   code (reuse it), how drivers and their charging tokens are modelled, and how the app shows charge
   points and running charges.
3. **Ask the human the questions in §2.** Do not guess the answers.
4. **Propose a short plan** that maps the phases in §10 onto this codebase, and wait for approval.
5. **Implement phase by phase**, with tests for each phase, and keep each phase reviewable on its own.
6. **Never** print, log, commit or hard-code a token. Mask the `Authorization` header in all logs.

## 2. Ask the human before you start

1. Your company's OCPI **country code** and **party ID** (for example `BG` and `ABC`). They must match what
   MagicLine registered for your company.
2. The public **HTTPS base address** where your OCPI endpoints will be reachable (it needs a certificate
   from a publicly trusted authority).
3. Where secrets are kept (environment variables, a vault, a cloud secret manager) and how the hub's
   versions address and the one-time registration token will be supplied to the application.
4. Which **token types** your drivers use (`APP_USER`, `RFID`, ...), how a driver maps to a token `uid`
   (at most 36 characters) and the format of your `contract_id`.
5. When a driver may charge: valid account, payment method, credit limit, blocked users. This becomes
   your real-time authorization answer (§7.4).
6. Whether the platform already has OCPI code, an OCPI library or another roaming connection to reuse.
7. How the app should present a start in progress, a refused start, a running charge and a finished
   charge.

## 3. Fixed facts

| Topic | Value |
|---|---|
| Protocol | OCPI 2.2.1. No other version is offered. |
| Your role | `EMSP` |
| Charge point operator | country code `BG`, party ID `MGL` (on locations, sessions and CDRs) |
| Transport | HTTPS only, in both directions |
| JSON | OCPI 2.2.1 field names (`snake_case`); all timestamps UTC, ISO 8601 with `Z` |
| Currency | `EUR`. Tariff prices are per kWh excluding VAT, with the VAT rate in `vat`. |
| Settlement month | Calendar month in `Europe/Sofia` local time, by session end |
| Page size | `limit` up to 100 (default 100) on every list the hub serves |

## 4. The three tokens

OCPI 2.2.1 registration uses three tokens. Keep the names straight; most integration bugs come from
using the wrong one.

| Token | Who creates it | Who sends it | Used for |
|---|---|---|---|
| **A**, one-time registration token | MagicLine, sent to you privately | You, to the hub | Only for reading the hub's versions and version details and for `POST credentials`. It stops working after registration. |
| **B**, your token | You generate it | The hub, to you | Every call the hub makes to your platform. Random, printable ASCII, **at most 64 characters**. |
| **C**, the hub's token | The hub, in the registration response | You, to the hub | Every call you make to the hub after registration. |

Every request in both directions carries `Authorization: Token <base64 of the token>` (OCPI 2.2.1).
Your platform must accept a request only when the decoded value equals token B. Store B and C encrypted
or in your secret store.

## 5. What your platform must expose

All of these answer with the OCPI response envelope:

```json
{ "data": { }, "status_code": 1000, "status_message": "Success", "timestamp": "2026-11-18T09:05:01Z" }
```

The hub treats a call as successful only when the HTTP status is 2xx **and** `status_code` is between
1000 and 1999. Anything else counts as a failure and is retried (see §8), so **every receiver must be
idempotent**.

| Endpoint (paths are up to you, except the OCPI suffixes) | Required | Called by the hub |
|---|---|---|
| `GET {your-base}/versions` | Yes | During registration and when it refreshes your endpoints |
| `GET {your-base}/2.2.1` (version details) | Yes | Same. Must list `credentials` and the modules below. |
| Tokens **SENDER**: `POST {tokens}/{uid}/authorize?type={type}` | Yes | Before every start. Answer within 10 seconds. |
| Sessions **RECEIVER**: `PUT {sessions}/{country_code}/{party_id}/{session_id}` | Recommended | On every status change, and about once a minute while charging |
| CDRs **RECEIVER**: `POST {cdrs}` | Recommended | Once per completed session with energy |
| Your `response_url` for each command: `POST` | Yes | When a start or stop command has a result |

Version details example (your platform):

```json
{
  "data": {
    "version": "2.2.1",
    "endpoints": [
      { "identifier": "credentials", "role": "RECEIVER", "url": "https://<your platform>/ocpi/2.2.1/credentials" },
      { "identifier": "tokens", "role": "SENDER", "url": "https://<your platform>/ocpi/2.2.1/tokens" },
      { "identifier": "sessions", "role": "RECEIVER", "url": "https://<your platform>/ocpi/2.2.1/sessions" },
      { "identifier": "cdrs", "role": "RECEIVER", "url": "https://<your platform>/ocpi/2.2.1/cdrs" }
    ]
  },
  "status_code": 1000,
  "timestamp": "2026-11-18T09:00:00Z"
}
```

Notes:

- If you leave out the Sessions or CDRs receiver, you must **pull** them instead (§7.5, §7.6).
- **If the Tokens SENDER is missing or unreachable, starts are not authorized by you.** The hub then lets
  the charge go ahead so the driver is not left waiting, and flags the session in the monthly statement.
  Implement it.
- If you add an endpoint later, the hub picks it up when it next reads your version details (at most every
  15 minutes when it needs an endpoint it does not know yet).
- The hub sends `X-Request-ID` and `X-Correlation-ID` on every call; log them for support.

## 6. What you call on the hub

Read the hub's version details (with token A before registration, with token C after) and use the URLs
listed there. Do not build hub paths yourself. Use only these entries; the hub lists others you do not
need as an eMSP.

| Module | Role in hub's list | What you do |
|---|---|---|
| `credentials` | `SENDER` / `RECEIVER` | Register (`POST`), read (`GET`), rotate (`PUT`), unregister (`DELETE`) |
| `locations` | `SENDER` | Pull charge points: list, or one location, EVSE or connector by path |
| `tariffs` | `SENDER` | Pull your partner-specific tariffs |
| `commands` | `RECEIVER` | `POST {commands}/START_SESSION` and `POST {commands}/STOP_SESSION` |
| `sessions` | `SENDER` | Pull your sessions (fallback or reconciliation) |
| `cdrs` | `SENDER` | Pull your CDRs (fallback or reconciliation) |

Headers on every call to the hub:

```http
Authorization: Token <base64 of token C>
X-Request-ID: <new UUID per request>
X-Correlation-ID: <UUID shared by related requests>
OCPI-from-country-code: <your country code>
OCPI-from-party-id: <your party ID>
```

Paging on every list (`locations`, `tariffs`, `sessions`, `cdrs`): query parameters `offset`, `limit`
(at most 100), `date_from` (inclusive) and `date_to` (exclusive). Response headers `X-Total-Count` and
`X-Limit`; when there is a next page, `Link: <url>; rel="next"`. Follow `Link` until it is absent.

## 7. Flows

### 7.1 Registration (once per environment)

Your versions and version details endpoints must be **live before** step 4, because the hub calls them
during that request.

1. `GET <hub versions address>` with token A. Pick the entry with `"version": "2.2.1"`.
2. `GET` its `url` (version details) with token A and keep the `credentials` URL.
3. Generate token B and store it, so your endpoints already accept it.
4. `POST {credentials}` with token A:

   ```json
   {
     "token": "<token B>",
     "url": "https://<your platform>/ocpi/versions",
     "roles": [
       {
         "role": "EMSP",
         "country_code": "BG",
         "party_id": "ABC",
         "business_details": { "name": "Your company" }
       }
     ]
   }
   ```

   Rules: `url` must be HTTPS; `roles` must contain `EMSP` with exactly the country code and party ID
   MagicLine registered for you.

5. The hub reads your versions and version details with token B, then answers with its own credentials:
   `data.token` is **token C**, `data.url` is the hub's versions address and the role is `HUB`. Store C,
   discard A.
6. Read the hub's version details again with token C and store the endpoint URLs from §6.

Errors during registration:

| HTTP | status_code | Meaning | What to do |
|---|---|---|---|
| 401 | 2000 | Token A unknown or already used | Ask MagicLine for a new registration token |
| 400 | 2001 | `token`, `url` or `roles` invalid, or the party does not match your registration | Fix the body |
| 400 | 3001 | The hub could not read your versions or version details | Check HTTPS, the certificate, and that token B is accepted |
| 400 | 3002 | Your versions list has no 2.2.1 | Offer 2.2.1 |
| 400 | 3003 | Your 2.2.1 version details do not list `credentials` | Add it |
| 405 | 2000 | Already registered | Use `PUT` to rotate instead |

**Rotate tokens:** `PUT {credentials}` with token C and the same body shape with a new token B; the answer
carries a new token C. **Unregister:** `DELETE {credentials}` with token C.

### 7.2 Locations

- First run: pull the full list. Then pull incrementally with `date_from` set to the start time of your last
  successful pull (filtered on `last_updated`). Changes reach the hub within about a minute; an
  incremental pull every minute keeps EVSE status fresh. Run a full pull daily to self-heal.
- You only receive charge points MagicLine has enabled for your company.
- Start a charge with the location `id` and the EVSE `uid`. Show drivers the readable `evse_id`
  (for example `BG*MGL*E000001*1`).
- Treat an EVSE with status `REMOVED` as gone.

### 7.3 Tariffs

- Pull `GET {tariffs}` the same way. The tariffs you receive are **yours alone**: they carry the price agreed
  for your company and do not apply to anyone else.
- Each connector names its tariff in `tariff_ids`.
- Price per kWh including VAT = `price × (1 + vat / 100)`. The price of a charge is fixed when the session
  starts; a later tariff change does not affect a running charge.
- What you charge your own driver is your decision.

### 7.4 Start a charge

1. The driver chooses an EVSE in your app. Run your own checks first (account, payment).
2. `POST {commands}/START_SESSION` with token C:

   ```json
   {
     "response_url": "https://<your platform>/ocpi/2.2.1/commands/START_SESSION/<your command id>",
     "token": {
       "country_code": "BG",
       "party_id": "ABC",
       "uid": "TOKEN-123",
       "type": "APP_USER",
       "contract_id": "BG-ABC-C00000001",
       "issuer": "Your company",
       "valid": true,
       "whitelist": "NEVER",
       "last_updated": "2026-11-18T09:05:00Z"
     },
     "location_id": "<location id>",
     "evse_uid": "<EVSE uid>",
     "authorization_reference": "<your command id>"
   }
   ```

   - `response_url`: unique per command, absolute, HTTPS.
   - `token.country_code` and `token.party_id` must be **your own** party; `token.uid` at most 36 characters.
   - `evse_uid` is required unless the location has a single EVSE. `connector_id` is optional.
   - `authorization_reference` (at most 36 characters) is optional, but send it: the session and the CDR
     carry it back, which is how you match them to this command.

3. For well-formed JSON the immediate answer is HTTP 200 / `status_code` 1000 with a `CommandResponse`:
   - `"result": "ACCEPTED"` with `"timeout"` in seconds (currently 230): wait for the result at your
     `response_url`.
   - `"result": "REJECTED"` with a `message`: the request was invalid, the token is not yours or the
     location is unknown or not enabled for you. Show the failure; do not retry unchanged.
4. The hub asks your Tokens endpoint (§7.4.1), then the charge point. The outcome arrives as
   `POST <response_url>` with `{"result": "...", "message": [{"language": "en", "text": "..."}]}`.
   Answer it with the envelope and `status_code` 1000.

| Result | Meaning |
|---|---|
| `ACCEPTED` | Charging started (for a stop: the charge ended) |
| `REJECTED` | Not allowed: your authorization answer, or the charge point refused |
| `EVSE_OCCUPIED` | The connector is in use |
| `EVSE_INOPERATIVE` | The charge point is offline, closed or faulted |
| `TIMEOUT` | The cable was not plugged in, or the charge point did not answer in time |
| `FAILED` | Any other failure |

5. If no result arrives within `timeout` seconds, show the start as failed but **still accept** session
   updates that may arrive later.

#### 7.4.1 Real-time authorization (your Tokens endpoint)

The hub calls, with token B:

```http
POST {your tokens}/TOKEN-123/authorize?type=APP_USER

{ "location_id": "<location id>", "evse_uids": ["<EVSE uid>"] }
```

Answer within **10 seconds** (aim for well under 2) with an `AuthorizationInfo`:

```json
{
  "data": {
    "allowed": "ALLOWED",
    "token": { "country_code": "BG", "party_id": "ABC", "uid": "TOKEN-123", "type": "APP_USER", "contract_id": "BG-ABC-C00000001", "issuer": "Your company", "valid": true, "whitelist": "NEVER", "last_updated": "2026-11-18T09:05:00Z" }
  },
  "status_code": 1000,
  "timestamp": "2026-11-18T09:05:01Z"
}
```

- Only `ALLOWED` lets the start continue. `BLOCKED`, `EXPIRED`, `NO_CREDIT` and `NOT_ALLOWED` stop it, and
  your command result becomes `REJECTED`.
- No answer within 10 seconds, an error, or a body without `allowed`: the hub starts the charge anyway and
  flags it. Keep this endpoint fast (no slow external calls on the request path) and always available.

### 7.5 Sessions

- With a Sessions receiver, the hub sends the **full** Session object with
  `PUT {your sessions}/{country_code}/{party_id}/{session_id}` (`country_code`/`party_id` are the charge
  point operator's: `BG`/`MGL`). Store it as an upsert keyed by those three values.
- Status changes arrive at once; `kwh` and `total_cost` (your price) about once a minute.
- Statuses: `PENDING` (waiting for the cable or starting), `ACTIVE`, `COMPLETED`, and `INVALID` for a
  start that never happened.
- Ignore an update whose `last_updated` is older than the one you have.
- Without a receiver, pull `GET {sessions}` with `date_from` (on `last_updated`) and the paging in §6.
- The Session `id` is the hub's session id. Use it for `STOP_SESSION`; use `authorization_reference` to
  match the session to your start command.

```json
{
  "country_code": "BG",
  "party_id": "MGL",
  "id": "<session id>",
  "start_date_time": "2026-11-18T09:05:20Z",
  "kwh": 4.32,
  "cdr_token": { "country_code": "BG", "party_id": "ABC", "uid": "TOKEN-123", "type": "APP_USER", "contract_id": "BG-ABC-C00000001" },
  "auth_method": "COMMAND",
  "authorization_reference": "<your command id>",
  "location_id": "<location id>",
  "evse_uid": "<EVSE uid>",
  "connector_id": "1",
  "currency": "EUR",
  "total_cost": { "excl_vat": 1.80, "incl_vat": 2.16 },
  "status": "ACTIVE",
  "last_updated": "2026-11-18T09:07:00Z"
}
```

### 7.6 Stop a charge

- `POST {commands}/STOP_SESSION` with `{ "response_url": "<unique url>", "session_id": "<session id>" }`.
- Immediate answer: `ACCEPTED` with `timeout` (currently 170), or `UNKNOWN_SESSION` when the hub knows no
  such session for your company. The result follows at `response_url` as in §7.4.
- Send a stop only for a session that is `PENDING` or `ACTIVE`. A stop for a session that has already ended
  is first answered `ACCEPTED`, and the result at `response_url` is then `FAILED`.
- The driver can also end the charge at the vehicle or the charge point: the session then becomes
  `COMPLETED` without a stop command. Handle both.

### 7.7 Charge detail records (CDRs)

- Every completed session with energy produces exactly **one** CDR, a few seconds after the end. A session
  that never started (`INVALID`) or delivered no energy has none.
- `total_cost` is your price. A CDR is never changed or resent with different content.
- With a CDRs receiver, the hub sends `POST {your cdrs}` with the CDR. Store it **idempotently** by
  (`country_code`, `party_id`, `id`): a delivery that looked failed to the hub is sent again.
- Without a receiver, pull `GET {cdrs}`; here `date_from` and `date_to` refer to when the hub received the
  record. Pull at least every few minutes and run a daily catch-up from the start of the previous day.
- Match a CDR to its session with `session_id` (and `authorization_reference`).

```json
{
  "country_code": "BG",
  "party_id": "MGL",
  "id": "<cdr id>",
  "start_date_time": "2026-11-18T09:05:20Z",
  "end_date_time": "2026-11-18T09:35:20Z",
  "session_id": "<session id>",
  "authorization_reference": "<your command id>",
  "cdr_token": { "country_code": "BG", "party_id": "ABC", "uid": "TOKEN-123", "type": "APP_USER", "contract_id": "BG-ABC-C00000001" },
  "auth_method": "COMMAND",
  "cdr_location": {
    "id": "<location id>",
    "name": "Example station",
    "address": "1 Example Blvd",
    "city": "Sofia",
    "country": "BGR",
    "coordinates": { "latitude": "42.697700", "longitude": "23.321900" },
    "evse_uid": "<EVSE uid>",
    "evse_id": "BG*MGL*E000001*1",
    "connector_id": "1",
    "connector_standard": "IEC_62196_T2",
    "connector_format": "SOCKET",
    "connector_power_type": "AC_3_PHASE"
  },
  "currency": "EUR",
  "charging_periods": [ { "start_date_time": "2026-11-18T09:05:20Z", "dimensions": [ { "type": "ENERGY", "volume": 7.5 } ] } ],
  "total_cost": { "excl_vat": 3.13, "incl_vat": 3.75 },
  "total_energy": 7.5,
  "total_time": 0.5,
  "last_updated": "2026-11-18T09:35:25Z"
}
```

### 7.8 Monthly settlement

- MagicLine invoices you monthly from a statement built on the CDRs: count, kWh, amounts excluding and
  including VAT.
- The month is the calendar month in `Europe/Sofia` local time of each CDR's `end_date_time`.
- A CDR that arrives after its month has ended is added to its own month and marked as late.
- Build a report that sums your stored CDRs the same way, so you can reconcile the invoice line by line.

## 8. Reliability rules

| Situation | Hub behaviour | What your platform must do |
|---|---|---|
| Your command result receiver fails | Retried with growing delays (up to 10 minutes apart) for 24 hours | Answer 1000 even for a result you already processed |
| Your CDRs receiver fails | Same as above; after 24 hours the CDR is only available by pull | Idempotent store; daily pull catch-up |
| Your Sessions receiver fails | The next update is retried after about 30 seconds | Upsert; ignore older `last_updated` |
| Your Tokens endpoint is slow or down | The charge starts after 10 seconds and is flagged | Keep it fast and monitored |
| The hub answers 401 | Token C is invalid or was revoked | Stop calling, alert a human; do not loop |
| The hub answers 403 | Your company is not active on the hub | Alert a human |
| The hub answers 5xx or times out | Temporary | Retry with backoff; reuse `X-Correlation-ID` |

## 9. Data to store (suggested)

- **Connection** (per environment): hub versions address, hub endpoint URLs, token B, token C (both
  secret), status, registered at.
- **Locations, EVSEs, connectors, tariffs**: the latest copy per `id`/`uid`, with `last_updated`.
- **Commands**: your command id (used in `response_url` and `authorization_reference`), type, driver,
  location and EVSE, sent at, timeout at, immediate answer, final result.
- **Sessions**: (`country_code`, `party_id`, `id`), `authorization_reference`, status, `kwh`,
  `total_cost`, `last_updated`, link to your driver.
- **CDRs**: unique (`country_code`, `party_id`, `id`), the full JSON, received at, settlement month.

Keep test and production completely separate: different hub addresses, different tokens, different data.

## 10. Implementation phases

Each phase ends with passing tests. Use a fake hub in tests; never call the real hub from unit tests.

1. **OCPI foundation:** response envelope, `Authorization` check against token B, outgoing client
   (`Token <base64 C>`, request IDs, `OCPI-from-*`), configuration and secrets, log masking.
2. **Versions and credentials:** your versions and version details endpoints, registration (§7.1), token
   rotation and unregistration, a one-off command or admin action that runs the registration.
3. **Locations and tariffs:** full and incremental pulls with paging, scheduled jobs, display in the app
   with the price including VAT.
4. **Real-time authorization:** the Tokens endpoint with your business rules and a response-time test.
5. **Commands:** start and stop, the `response_url` receiver, timeouts, the app states.
6. **Sessions:** the receiver (or pull), live progress in the app.
7. **CDRs and settlement:** the receiver (or pull), idempotent storage, the monthly reconciliation report.
8. **End-to-end in the MagicLine test environment** using the checklist in §11.

## 11. Acceptance checklist (test environment)

- [ ] Registration succeeds; token A no longer works; calls with token C succeed.
- [ ] A full locations pull follows `Link` to the last page; an incremental pull returns only changes.
- [ ] Tariffs are linked to connectors and the app shows the price including VAT.
- [ ] Authorization answers within 2 seconds; a blocked token makes the start end with `REJECTED`.
- [ ] Start: `ACCEPTED` → command result `ACCEPTED` → session `PENDING`/`ACTIVE` → `kwh` grows.
- [ ] Start without plugging in the cable ends with `TIMEOUT` (or `FAILED`) and the app explains it.
- [ ] Stop from the app → session `COMPLETED` → exactly one CDR stored, even if it is delivered twice.
- [ ] A charge ended at the vehicle also completes cleanly.
- [ ] `GET sessions` and `GET cdrs` pulls return the same data as the pushes.
- [ ] Logs contain no tokens.
- [ ] The monthly sum of your CDRs equals MagicLine's statement.

## 12. Status codes the hub returns

| status_code | HTTP | Meaning |
|---|---|---|
| 1000 | 200 | Success |
| 2000 | 401 | Missing or invalid token |
| 2000 | 403 | Not allowed for your company, or your company is not active |
| 2001 | 400 | Invalid or missing parameters |
| 2003 | 404 | Unknown location |
| 3001 | 400 | Registration could not use your API (your versions endpoint was not reachable) |
| 3002 | 400 | No common OCPI version (2.2.1 is required) |
| 3003 | 400 | Your 2.2.1 endpoints do not include credentials |
| 3000 | 500 | Server error; retry later |

## 13. Not offered (do not build)

- Starting with an RFID card at the charge point (remote start from your app only, for now).
- Reservations and smart charging (charging profiles).
- OCPI 2.3 or 2.1.1.
- Pushing locations or tariffs to your platform: you pull them.

## 14. Security

- HTTPS only, with a certificate from a publicly trusted authority, in both directions.
- Tokens: stored encrypted or in a secret store, never logged, never committed. The registration token works
  once. Ask MagicLine to revoke and reissue if one may have leaked.
- Records carry the token ID and contract ID only; never send names, e-mail addresses or phone numbers.
- Report a vulnerability to info@magiclineenergy.com and do not publish details before MagicLine has
  responded.
