SAP Datasphere MCP Server

SAP Datasphere MCP Server

Model Context Protocol server that lets AI assistants explore and query SAP Datasphere — metadata discovery, catalog search, OData and SQL queries, ETL extraction, data lineage and column profiling — with built-in config-driven PII masking.

Category
访问服务器

README

🚀 SAP Datasphere MCP Server

PyPI version npm version Python 3.10+ MCP Protocol License: MIT

Model Context Protocol server that lets AI assistants explore and query SAP Datasphere — metadata discovery, catalog search, OData and SQL queries, ETL extraction, data lineage and column profiling — with built-in config-driven PII masking so sensitive fields never reach the LLM.

Version 1.4.0 · 42 tools advertised by default (51 with DATASPHERE_TOOL_PROFILE=full)


🤝 Relationship to the SAP Datasphere CLI

This server and the @sap/datasphere-cli split the work along one line:

Owns Because
MCP server (this repo) Reading data and metadata, catalog search, profiling Consumption and Catalog APIs
CLI Creating and changing objects, tenant administration Design-time and admin APIs

The CLI cannot read data rows — that is this server's reason to exist. This server does not create objects, apart from local tables (create_table), because the payload there is derived from data it has already read. Views, analytic models, flows, spaces, users and roles belong to the CLI.

Neither writes data rows. Rows arrive through a data/replication flow, a database user with a SQL client, or a CSV upload in the Data Builder UI.

Guide Content
docs/MCP_VS_CLI.md Authoritative capability split and routing rules
docs/TENANT_CONFIG.md The three config files and the two identities
docs/CLI_LINEAGE_LOOKUP.md Finding objects the Consumption API cannot see

A few tools shell out to the CLI (create_table, the *_database_user* tools, list_repository_objects). The CLI keeps its own session, separate from this server's OAuth credentials — check it with the datasphere_cli_status tool.


🚀 Quick Start

# npm
npm install -g @mariodefe/sap-datasphere-mcp && npx @mariodefe/sap-datasphere-mcp

# PyPI
pip install sap-datasphere-mcp && sap-datasphere-mcp

# From source
git clone https://github.com/MarioDeFelipe/sap-datasphere-mcp.git
cd sap-datasphere-mcp
pip install -r requirements.txt && pip install -e .
cp .env.example .env      # fill in your credentials
sap-datasphere-mcp

Full walkthrough: docs/GETTING_STARTED.md · OAuth setup: docs/OAUTH_SETUP.md

Configuration

DATASPHERE_BASE_URL=https://your-tenant.eu10.hcs.cloud.sap
DATASPHERE_TENANT_ID=your-tenant-id
DATASPHERE_CLIENT_ID=your-client-id
DATASPHERE_CLIENT_SECRET=your-client-secret
DATASPHERE_TOKEN_URL=https://your-tenant.authentication.eu10.hana.ondemand.com/oauth/token
USE_MOCK_DATA=false

Optional settings for the CLI-backed tools (DATASPHERE_CLI_PATH, _HOST, _SECRETS_FILE) are documented in .env.example and docs/TENANT_CONFIG.md.

Never commit .env.

Claude Desktop

{
  "mcpServers": {
    "sap-datasphere": {
      "command": "npx",
      "args": ["@mariodefe/sap-datasphere-mcp"],
      "env": {
        "DATASPHERE_BASE_URL": "https://your-tenant.eu20.hcs.cloud.sap",
        "DATASPHERE_CLIENT_ID": "your-client-id",
        "DATASPHERE_CLIENT_SECRET": "your-client-secret",
        "DATASPHERE_TOKEN_URL": "https://your-tenant.authentication.eu20.hana.ondemand.com/oauth/token"
      }
    }
  }
}

Config location — Windows: %APPDATA%\Claude\claude_desktop_config.json · macOS: ~/Library/Application Support/Claude/claude_desktop_config.json · Linux: ~/.config/Claude/claude_desktop_config.json


🛠️ Tool Catalog

42 tools in the default lean profile. Set DATASPHERE_TOOL_PROFILE=full to also advertise overlapping metadata tools, and DATASPHERE_EXPOSE_DIAGNOSTICS=true for the endpoint probes — 51 in total. Hiding them by default improves the model's tool selection; every handler stays reachable.

Foundation (5)

test_connection · get_current_user · get_tenant_info · get_available_scopes · list_spaces

Space discovery (3)

get_space_info · get_table_schema · search_tables

Catalog and search (5)

list_catalog_assets · get_asset_details · get_asset_by_compound_key · get_space_assets · search_catalog

Catalog search runs client-side: /catalog/search returns 404 on the tenants tested, so these tools fetch assets and filter locally across name, label, businessName and description.

Data discovery and quality (2)

Tool Purpose
find_assets_by_column Which assets contain a given column — lineage and impact analysis across spaces
analyze_column_distribution Null rate, distinct values, percentiles, IQR outlier detection

Querying data (4)

Tool Purpose
smart_query SQL router: picks analytical vs relational, falls back to client-side aggregation when the asset cannot aggregate
execute_query SELECT with SQL→OData conversion, max 1000 rows
query_relational_entity Relational OData, up to 50,000 records per batch for ETL
query_analytical_data Analytical OData with $apply, $filter, $orderby

Supported SQL: SELECT */column lists, WHERE, LIMIT, GROUP BY, aggregations with and without grouping, ORDER BY. No JOINs — OData is single-entity. Names are case-sensitive.

Metadata (7)

get_relational_metadata · list_relational_entities · get_relational_entity_metadata · get_analytical_metadata · get_analytical_model · list_analytical_datasets · get_asset_variables

get_relational_entity_metadata maps OData types to SQL (Edm.String → NVARCHAR(MAX), Edm.Int64 → BIGINT, Edm.Decimal → DECIMAL(18,2), …) for data-warehouse loading. get_asset_variables surfaces input parameters a parameterised view or analytic model expects.

Repository (3)

Tool Purpose
list_repository_objects Lists design-time objects via the CLI, so it also sees objects not exposed for consumption
get_deployed_objects Deployed objects in a space
get_object_definition Object definition (deprecated — prefer get_asset_details)

Database users (5) — CLI-backed

list_database_users · create_database_user · update_database_user · delete_database_user · reset_database_user_password

High-risk operations require consent, cached for 60 minutes.

Tasks (4)

get_task_status · run_task_chain · get_task_log · get_task_history

Object provisioning (1) — CLI-backed

create_table — builds a CSN definition from your column list and runs datasphere objects local-tables create. Local tables only; see the CLI split above.

Operations (4)

list_connections · browse_marketplace · datasphere_cli_status · get_relational_odata_service (full profile)

datasphere_cli_status reports whether the CLI is installed, which version, which host, and whether a session exists. Run it first when a CLI-backed tool fails.


🔏 PII / Sensitive-Field Masking

A config-driven, fail-closed masking layer runs inside the response pipeline. Every data-returning tool (smart_query, query_relational_entity, query_analytical_data, get_space_assets, analyze_column_distribution) funnels results through apply_masking() before they reach the LLM. No prompt bypasses it.

Defense in depth. The authoritative access control stays upstream — SAP Datasphere Data Access Controls, and not granting the technical user access to PII tables. This layer is the enforced, auditable net on top.

Environment variable Values Default Purpose
DATASPHERE_PII_POLICY path to YAML or JSON (unset) Policy file. Unset = masking fully disabled.
DATASPHERE_PII_MODE enforce | audit_only | off enforce when a policy is present audit_only logs what would be masked without changing data
DATASPHERE_PII_SALT secret string (empty) Salt for deterministic hash/tokenize. Treat as a secret.

If the policy file is configured but missing or unparseable, the server raises at startup and refuses to run. It never silently serves raw data with a broken policy.

mode: enforce
default_action: redact

rules:
  # Most specific wins: asset > space > global; exact > glob
  - space: ZDCS_08
    asset: ZR_SAP_CUSTOMER
    columns:
      EMAIL:  redact       # → "***"
      PHONE:  partial:4    # keep last 4 → "******1234"
      TAXID:  hash         # sha256(salt:value) — deterministic, safe for GROUP BY
      SSN:    drop         # column removed from every row
  - space: "*"
    columns:
      "*IBAN*": tokenize   # glob on column name → "TKN_<8hex>"

allowlist:
  enabled: true
  assets:
    ZDCS_08.ZR_OTC_CUST_MONTH: [CUSTOMER, MONTH, REVENUE]   # ONLY these returned

patterns:
  email: '[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}'
  iban:  '\b[A-Z]{2}\d{2}[A-Z0-9]{10,30}\b'

Precedence: allowlist (drops everything unlisted) → column rules → value-pattern scan on remaining strings.

Audit log — one structured line per call, values never logged:

[pii_masking] space=ZDCS_08 asset=ZR_SAP_CUSTOMER rows=42
              masked_fields=['EMAIL', 'PHONE', 'SSN'] mode=enforce

The response also carries masked_fields, so the client can see what was withheld. Annotated example: pii_policy.yaml.


🔒 Security

Authentication — OAuth 2.0 client credentials, tokens refreshed 60s before expiry and encrypted in memory (Fernet). No credentials in code.

Authorization — four permission levels (READ, WRITE, ADMIN, SENSITIVE), interactive consent for high-risk operations, full audit logging.

Query safety — the SQL sanitizer is fail-closed on SELECT: INSERT/UPDATE/DELETE/DROP and SQL comments are blocked, along with 15+ injection patterns. Write paths do not exist.


🌐 Transports

stdio by default; Streamable HTTP (spec 2025-03-26) at /mcp for long-lived service deployments.

Flag Env var Default Purpose
--transport MCP_TRANSPORT stdio stdio or http
--host MCP_HTTP_HOST 127.0.0.1 Bind address
--port MCP_HTTP_PORT 8080 Bind port
--path MCP_HTTP_PATH /mcp Endpoint path
--auth-token MCP_HTTP_AUTH_TOKEN (none) Require Authorization: Bearer <token>
pip install 'sap-datasphere-mcp[http]'
sap-datasphere-mcp --transport http --port 8080

The server warns when bound to a non-loopback interface without a token. /health serves a plain JSON liveness probe.


📊 Architecture

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│   AI Assistant  │◄──►│   MCP Server     │◄──►│  SAP Datasphere │
│ (Claude, Cursor)│    │  Authorization   │    │   (OAuth 2.0)   │
│                 │    │  PII masking     │    │                 │
│                 │    │  Caching         │    │  datasphere CLI │
└─────────────────┘    └──────────────────┘    └─────────────────┘
src/sap_datasphere_mcp/
├── server.py              # MCP server and all tool handlers
├── cli_runner.py          # Single entry point for `datasphere` CLI calls
├── pii_masking.py         # Config-driven, fail-closed masking
├── cache_manager.py       # TTL cache
├── telemetry.py           # Request metrics
├── tool_descriptions.py   # Tool metadata
├── error_helpers.py       # Error formatting
├── auth/
│   ├── oauth_handler.py             # Token management and refresh
│   ├── datasphere_auth_connector.py # Authenticated API connector
│   ├── authorization.py             # Permission levels
│   ├── consent_manager.py           # Consent tracking
│   ├── input_validator.py           # Input validation
│   ├── sql_sanitizer.py             # SELECT-only enforcement
│   └── data_filter.py               # Credential redaction
└── config/settings.py     # Environment-based settings

Caching TTLs — spaces 1h · assets 30min · metadata 15min · users 5min, LRU eviction.

Response times — cached metadata under 100ms · catalog 100–500ms · OData queries 500–2000ms depending on volume.


🧪 Testing

pytest                                              # full suite
pytest tests/test_cli_runner.py                     # CLI integration layer
npx @modelcontextprotocol/inspector sap-datasphere-mcp

tests/test_cli_runner.py verifies every CLI command the server hardcodes against the --help dumps in the DataphereCLI repo. Point DATASPHERE_CLI_HELP_DIR at tools/cli-help to enable it; it skips otherwise.

Known failure: tests/test_mcp_server.py uses await server.list_resources()(), an idiom the current MCP SDK no longer supports. Pre-existing, unrelated to the server itself.


🚀 Deployment

docker build -t sap-datasphere-mcp:latest .
docker run -d --name sap-mcp --env-file .env sap-datasphere-mcp:latest
# or
docker-compose up -d

Full guide incl. Kubernetes: docs/DEPLOYMENT.md


📚 Documentation

Guide Content
Getting Started Setup walkthrough with examples
API Reference Technical API docs, Python and cURL
OAuth Setup App Integration and OAuth client
Tenant Config Config files, the two identities
MCP vs CLI Which tool owns which task
CLI Lineage Lookup Objects invisible to Consumption
Deployment Docker, Kubernetes, PyPI
Developer Guide Contributing to the codebase
Changelog Version history

🙏 Acknowledgments

Built with Amazon Kiro (specifications and architectural steering) and Claude Code (security and authentication, tool descriptions and error handling, caching and telemetry, repository and analytics tools, CLI integration layer).


📄 License

MIT — see LICENSE.

📞 Support

Issues · Discussions · SAP Datasphere docs · Model Context Protocol

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选