Skip to main content
Glama
odata-mcp-server

odata-mcp-server

by Caio2M
README.md
# odata-mcp-server

[![CI](https://github.com/Caio2M/odata-mcp-server/actions/workflows/ci.yml/badge.svg)](https://github.com/Caio2M/odata-mcp-server/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

**Turn any OData V2/V4 service — SAP CAP, SAP Gateway, ABAP RAP, or any other — into tools for AI agents, generated from `$metadata`.**

Point it at a service URL. It reads the `$metadata`, understands entity sets, keys, types, labels, navigation, functions/actions and capability annotations, and serves them over the [Model Context Protocol](https://modelcontextprotocol.io) so Claude, Cursor, VS Code or your own agent code can query and (optionally) change business data — with no per-service code.

```bash
npx odata-mcp-server http://localhost:4004/odata/v4/catalog/ --allow-writes --list-tools
```

```
service_info        [read]  Overview of the CatalogService OData V4 service: entity sets with keys, fields, …
list_Books          [read]  Query Books — Books available in the store. Fields: ID (Int32, key, not null); title "Title" …
get_Books           [read]  Read one Books entry by key (ID). Navigation (use in expand): author → Authors.
create_Books        [WRITE] Create a new entry in Books — Books available in the store. Server-computed fields are omitted.
update_Books        [WRITE] Partially update one Books entry identified by its key (ID). …
call_booksByAuthor  [read]  Call function booksByAuthor. Returns Collection(Books).
call_submitOrder    [WRITE] Invoke action submitOrder. Returns Orders. This may change data on the server.
…
```

## Why

Agents are good at OData — *if* they know the model. This server gives them exactly that:

- **Schema-aware tools.** One `list_` / `get_` (and, if enabled, `create_` / `update_` / `delete_`) tool per entity set, plus one tool per function/action import. Input schemas are real JSON Schema derived from EDM types: keys are required, `$select`/`$expand` are enums of real property names, enums are enums, computed fields are hidden from create.
- **Annotations become context.** `@title`/`Common.Label`, `@description`/`Core.Description`, `sap:label`, `sap:quickinfo` end up in tool descriptions, so the agent knows that `KUNNR` is *Customer*.
- **Capabilities are respected.** CAP `@readonly`, V4 `Capabilities.Insert/Update/DeleteRestrictions`, `sap:creatable/updatable/deletable/pageable/searchable` decide which tools exist.
- **V2 and V4 quirks handled for you.** `d.results` unwrapping, `__count` vs `@odata.count`, `/Date(…)/` ⇄ ISO 8601, `Edm.Decimal`/`Int64` as strings in V2, typed literals (`guid'…'`, `datetime'…'`, `10M`) in keys and function parameters, `MERGE` vs `PATCH`.
- **Enterprise plumbing.** Basic, bearer and **OAuth2 client credentials (SAP BTP XSUAA)** auth, **CSRF token + session cookie** handling for SAP Gateway, `sap-client` / `sap-language`, ETag `If-Match` retry, readable SAP error messages (incl. `errordetails`).
- **Safe by default.** Read-only unless you pass `--allow-writes`. Every tool carries MCP `readOnlyHint` / `destructiveHint` annotations so clients can ask for confirmation.
- **Scales to big services.** `--tool-mode auto` switches to a compact set of generic tools (`query_entities`, `get_entity`, `describe_entity_set`, …) when a service has more entity sets than `maxEntityTools` (default 25), keeping the tool list — and token cost — small. `--include` / `--exclude` globs narrow it further.

## Quick start

### Claude Desktop / Claude Code / Cursor

```json
{
  "mcpServers": {
    "bookshop": {
      "command": "npx",
      "args": ["-y", "odata-mcp-server", "http://localhost:4004/odata/v4/catalog/", "--name", "bookshop"]
    }
  }
}
```

Claude Code: `claude mcp add bookshop -- npx -y odata-mcp-server http://localhost:4004/odata/v4/catalog/ --name bookshop`

### SAP Gateway (on-premise / S/4HANA) — OData V2

```json
{
  "mcpServers": {
    "sales": {
      "command": "npx",
      "args": ["-y", "odata-mcp-server", "https://my-s4:44300/sap/opu/odata/sap/API_SALES_ORDER_SRV/",
               "--name", "sales", "--sap-client", "100", "--sap-language", "EN"],
      "env": { "ODATA_USERNAME": "ME", "ODATA_PASSWORD": "••••" }
    }
  }
}
```

### SAP BTP (CAP app protected by XSUAA)

Use the `clientid`, `clientsecret` and `url` from the XSUAA service key:

```json
{
  "mcpServers": {
    "cap-on-btp": {
      "command": "npx",
      "args": ["-y", "odata-mcp-server", "https://my-app-srv.cfapps.eu10.hana.ondemand.com/odata/v4/catalog/"],
      "env": {
        "ODATA_TOKEN_URL": "https://my-subaccount.authentication.eu10.hana.ondemand.com/oauth/token",
        "ODATA_CLIENT_ID": "sb-my-app!t123",
        "ODATA_CLIENT_SECRET": "••••"
      }
    }
  }
}
```

### Several services in one server

```bash
odata-mcp --config odata-mcp.json
```

```json
{
  "services": [
    { "name": "catalog", "url": "http://localhost:4004/odata/v4/catalog/" },
    {
      "name": "bp",
      "url": "https://my-s4/sap/opu/odata/sap/API_BUSINESS_PARTNER/",
      "auth": { "type": "basic", "username": "${S4_USER}", "password": "${S4_PASSWORD}" },
      "sapClient": "100",
      "include": ["A_BusinessPartner*", "A_Customer"],
      "toolMode": "entity"
    }
  ]
}
```

`${VAR}` placeholders are expanded from the environment, so secrets stay out of the file. See [`examples/`](examples).

## What gets generated

| From `$metadata`                         | MCP tool                                  | Notes                                                        |
| ---------------------------------------- | ----------------------------------------- | ------------------------------------------------------------ |
| every service                            | `service_info`                            | entity sets, keys, fields, navigation, operations            |
| `EntitySet`                              | `list_<Set>`                              | `filter`, `select`, `orderby`, `top`/`skip`, `expand`, `count`, `search` |
| `EntitySet` with key                     | `get_<Set>`                               | typed key fields, `select`, `expand`                         |
| insertable `EntitySet` *(writes)*        | `create_<Set>`                            | computed fields hidden, non-nullable fields required          |
| updatable `EntitySet` *(writes)*         | `update_<Set>`                            | `PATCH` (V4) / `MERGE` (V2), optional `etag`                 |
| deletable `EntitySet` *(writes)*         | `delete_<Set>`                            | optional `etag`                                              |
| V4 `FunctionImport`, V2 GET `FunctionImport` | `call_<Name>`                         | read-only                                                    |
| V4 `ActionImport`, V2 POST `FunctionImport` *(writes)* | `call_<Name>`               | marked destructive                                           |

With `--tool-mode generic` (or `auto` on large services) you get instead: `service_info`, `describe_entity_set`, `query_entities`, `get_entity`, `call_operation` (+ `create_entity`, `update_entity`, `delete_entity` with writes enabled).

Results come back as compact JSON: `{ "results": [...], "count": 42, "nextSkip": 20 }` for queries, the plain entity for reads — OData noise (`__metadata`, `@odata.*`, `__deferred`) stripped.

## CLI reference

```
odata-mcp [url] [options]

  -c, --config <file>         JSON config with one or more services
  -n, --name <name>           service name, used as tool prefix
  -u, --user / -p, --password basic auth        (env: ODATA_USERNAME / ODATA_PASSWORD)
  --token <token>             bearer token      (env: ODATA_TOKEN)
  --token-url, --client-id, --client-secret
                              OAuth2 client credentials (env: ODATA_TOKEN_URL / ODATA_CLIENT_ID / ODATA_CLIENT_SECRET)
  -H, --header "Name: value"  extra header (repeatable)
  --sap-client <client>       SAP client / mandant (env: ODATA_SAP_CLIENT)
  --sap-language <lang>       SAP logon language
  -w, --allow-writes          expose create/update/delete and actions
  --tool-mode <mode>          auto | entity | generic (default: auto)
  --include / --exclude <globs>  comma-separated entity set / operation globs
  --default-top / --max-top   paging limits (default 20 / 500)
  --metadata-file <file>      read $metadata from disk
  --list-tools                print generated tools and exit
```

The URL can also come from `ODATA_URL`.

## Use as a library

```ts
import { createServer } from 'odata-mcp-server';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';

const { server, tools } = await createServer({
  services: [{ name: 'catalog', url: 'http://localhost:4004/odata/v4/catalog/', allowWrites: true }],
});
// connect to any MCP transport, or call tools[i].handler(args) directly from your own agent
```

`parseMetadata(xml)`, `ODataService` and `buildTools(service)` are exported too, if you only need parts of the pipeline.

## Development

```bash
npm install
npm test          # unit + end-to-end tests
npm run build
npm run dev -- http://localhost:4004/odata/v4/catalog/ --list-tools
```

The end-to-end tests start a real **SAP CAP** bookshop (in-memory SQLite) from [`test/fixtures/bookshop`](test/fixtures/bookshop), served both as OData V4 and — through [`@cap-js-community/odata-v2-adapter`](https://github.com/cap-js-community/odata-v2-adapter) — as OData V2. An MCP client then talks to this server over an in-memory transport and over stdio, exercising queries, paging, expands, functions, actions and CRUD on both protocol versions. Parser tests additionally cover hand-written SAP Gateway (SEGW-style) and ABAP RAP-style `$metadata`.

## Roadmap

- Bound actions/functions (CAP `actions { … }` on entities, RAP actions)
- SAP BTP Destination service + Connectivity (Cloud Connector) support
- `$batch` for multi-entity changes
- Streamable HTTP transport in the CLI
- Deep insert hints from compositions

## Related projects

- [oisee/odata_mcp_go](https://github.com/oisee/odata_mcp_go) — a Go OData→MCP bridge with a similar idea. This one focuses on the SAP BTP / CAP side: a TypeScript npm package that also works as a library, V4 capability vocabularies, OAuth2 client credentials for XSUAA, read-only by default, MCP tool annotations, and a test suite that runs against a real CAP service.

## License

MIT © Caio Marinho Melo