Metadata-Version: 2.4
Name: oracle-data-studio
Version: 1.0.41
Summary: Python client for Oracle Data Studio Database Service
License: Copyright (c) 2023-2025, Oracle and/or its affiliates
        
        The Universal Permissive License (UPL), Version 1.0
        
        Subject to the condition set forth below, permission is hereby granted to any person obtaining a copy of this software, associated documentation and/or data (collectively the "Software"), free of charge and under any and all copyright rights in the Software, and any and all patent rights owned or freely licensable by each licensor hereunder covering either (i) the unmodified Software as contributed to or provided by such licensor, or (ii) the Larger Works (as defined below), to deal in both
        
        (a) the Software, and
        (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if one is included with the Software (each a "Larger Work" to which the Software is contributed by such licensors), 
        
        without restriction, including without limitation the rights to copy, create derivative works of, display, perform, and distribute the Software and make, use, sell, offer for sale, import, export, have made, and have sold the Software and the Larger Work(s), and to sublicense the foregoing rights on either these or other terms.
        
        This license is subject to the following condition:
        
        The above copyright notice and either this complete permission notice or at a minimum a reference to the UPL must be included in all copies or
        substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
        
Keywords: Oracle database,ORDS,Oracle database actions,Oracle Data Studio
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
License-File: THIRD_PARTY_LICENSES.txt
Requires-Dist: requests>=2.28.2
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.0.0; extra == "mcp"
Requires-Dist: keyring>=25.0.0; extra == "mcp"
Provides-Extra: codemode
Requires-Dist: mcp<2,>=1.7.0; extra == "codemode"
Requires-Dist: keyring>=25.0.0; extra == "codemode"
Requires-Dist: pydantic-monty<1.8,>=1.7.0; python_version >= "3.11" and extra == "codemode"
Provides-Extra: pandas
Requires-Dist: pandas>=2.2.3; extra == "pandas"
Provides-Extra: agents
Requires-Dist: mcp<2,>=1.0.0; extra == "agents"
Requires-Dist: keyring>=25.0.0; extra == "agents"
Requires-Dist: uvicorn>=0.23.0; extra == "agents"
Requires-Dist: starlette>=0.27; extra == "agents"
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.40.0; extra == "anthropic"
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == "openai"
Provides-Extra: redis
Requires-Dist: redis>=5.0.0; extra == "redis"
Provides-Extra: oracle
Requires-Dist: oracledb>=2.0.0; extra == "oracle"
Dynamic: license-file

# Oracle Data Studio API

The Python client for Oracle Data Studio on Autonomous Database offers various operations for accessing and managing Oracle Databases via Oracle REST Data Services (ORDS). It provides functions to support uploading files from Cloud Storage to the database, importing tables from database links, and manipulating analytic views and insights.

The Data Studio API works with Python 3.10 or later.

### Install Data Studio API

	pip install oracle-data-studio

For the MCP server that lets AI assistants (Claude, Cursor, Codex and others) work with Autonomous Database, Essbase and Data Transforms, install the `mcp` extra:

	pip install "oracle-data-studio[mcp]"

### Quick start

**From Python:**

```python
import adp

client = adp.login("https://<adb-host>.adb.<region>.oraclecloudapps.com", "ADMIN", password)
client.Misc.run_query("select table_name from user_tables")
```

**As an MCP server.** Store each connection once. URLs and users go to `~/.oracle-data-studio/config`; passwords are prompted for and kept in the OS keyring, never on disk:

```bash
oracle-data-studio-config set adp --url https://<adb-host>.adb.<region>.oraclecloudapps.com --user ADMIN
oracle-data-studio-config set essbase --url https://<essbase-host> --user admin
oracle-data-studio-config set datatransforms --url https://<adb-host>.adb.<region>.oraclecloudapps.com --user ADMIN
oracle-data-studio-config list
```

Configure only the services you use; the server shows only their tools. Data Transforms can be on another database than ADP, or a Marketplace deployment; with the same database and user as `adp`, the two share one login. Then add the server to your assistant. For Claude Code:

```bash
claude mcp add oracle-data-studio -- oracle-data-studio-mcp --profile analyst
```

For Claude Desktop, in `claude_desktop_config.json` (no secrets needed here, since the server reads the stored connections):

```json
{
  "mcpServers": {
    "oracle-data-studio": {
      "command": "oracle-data-studio-mcp",
      "args": ["--profile", "analyst"]
    }
  }
}
```

The profile decides which tools the assistant sees:

| Profile | Tools |
|---|---|
| `viewer` (default) | 19 read-only tools: browse, describe, search and explore across Autonomous Database, Essbase and Data Transforms |
| `analyst` | Also MDX queries and exports, analytic view and mounted-table queries, Essbase calculations and insights |
| `admin` | All 73, including SQL, Select AI, loads, pipelines, and create and drop. Destructive actions need a `confirm` value, usually the object's name |

Every tool is annotated as read-only or destructive for clients that auto-approve or warn. Instead of the config store, connections can also come from environment variables (`ADP_URL`, `ADP_USER`, `ADP_PASSWORD`, `ESSBASE_URL`, … `DT_URL`) or command-line flags (`oracle-data-studio-mcp --help`). To share one server over HTTPS with several users, run `oracle-data-studio-mcp --transport streamable-http --auth-token <token> --ssl-certfile … --ssl-keyfile …`. For the Oracle AI Data Catalog, see its section below.


#### Code mode (experimental)

With `--code-mode`, the read-only tools become functions of one `run_code` tool. The assistant writes a short Python program that calls them, and only the program's answer comes back, not every intermediate result. It is off by default. Install the `codemode` extra (Python 3.11 or later) and add the flag:

```bash
pip install "oracle-data-studio[codemode]"
oracle-data-studio-mcp --profile analyst --code-mode          # or MCP_CODE_MODE=1
```

```python
# what an assistant might run
found = call_many("adp_search", ["OFFER", "BROWSING"])
tables = sorted({hit["name"] for reply in found
                 for hit in reply["results"] if hit["type"] == "TABLE"})
notes = call_many("adp_get_annotations", tables)
{t: len(n["annotations"]["columns"]) for t, n in zip(tables, notes)}
```

It helps with loops, joins across services and large results, and the tool list shrinks from about 5,700 to 2,200 tokens on the `analyst` profile. In our test of 13 tasks with one model, calls and results took 86% fewer tokens, and loops over searches and annotations ran about four times faster. Single cube lookups take a second or two longer, because the assistant usually reads the outline first. The measurements are in `docs/code-mode-evaluation.md` in the repository.

Programs run in a [Monty](https://github.com/pydantic/monty) sandbox in a separate process, with no files, network or environment, and with limits on time, memory, calls and output. They reach only the read-only tools of the server's profile, with the same checks as direct calls. Tools that change something stay ordinary tools. Runs on one server happen in turn, so on a server shared by several people one long program makes the others wait (up to 5 seconds of computing, plus its tool calls). Without the extra the server says so and starts with the ordinary tools.


### Using Data Studio API

Please visit [Oracle documentation](https://docs.oracle.com/en/database/oracle/sql-developer-web/sdwad/python-ords-api-oml-1.html) for details.

### Connecting in Graph Python notebooks

Use the database connection already supplied by Graph:

```python
import adp

client = adp.connect()
rows = client.Misc.run_query("select user as database_user from sys.dual d")
```

No URL, username, password, or token is needed. `connect()` first reuses an ORDS session bound to the interpreter by its embedding application. Otherwise it discovers Graph's authenticated `connection_pool` and registers or reuses `data_studio_python_client` through that SQL connection. It grants only the `SQL Developer` role, rotates a nonstored client secret, exchanges it for an ORDS token, and verifies that the bearer connects as the Graph database user.

This automatic discovery supports Autonomous Database's standard ORDS endpoint and an enabled base-path schema mapping. It requires the updated Python package in the Graph interpreter and access to the `ORDS_METADATA.ORDS_SECURITY` APIs. Missing permissions or configuration produce a setup error; they do not prompt for another login. Graph documents its pool in the [Python interpreter reference](https://docs.oracle.com/en/cloud/paas/autonomous-database/csgru/python-pgx-interpreter.html).

Repeated calls reuse the connected client within that interpreter. Before every REST request, the client checks its authenticated SQL context and renews an expiring token. Replaced or closed pools cannot continue using cached credentials. A 401 allows renewal on the next explicit request; the failed SQL is never replayed automatically. Separate interpreters keep separate tokens, although simultaneous secret rotation shares ORDS's two-secret limit for this client.

Without a bound ORDS session or Graph pool, `connect()` retains its existing OML behavior. Explicit `connect(url)` calls also retain their OML behavior. Other Data Studio operations may require additional privileges beyond SQL.

### Reusing a host database session

An application that already manages an ORDS OAuth session can supply its current token without another database login or an OML cursor:

```python
import adp

# host_session is supplied by the embedding application. Its provider must
# remain bound to this database and user, including after a connection switch.
client = adp.connect_with_token_provider(
    schema_url="https://database.example.com/ords/schema-alias/",
    username="VERIFIED_DATABASE_USER",
    token_provider=host_session.get_ords_access_token,
)
rows = client.Misc.run_query("select user as database_user from sys.dual d")
```

Pass the full HTTPS schema URL, including any deployment prefix and schema alias. The alias can differ from the verified database username; both retain their case.

The provider is a synchronous callback returning a bare access token. It runs before every HTTP request, so the host can renew its token and enforce expiry, disconnect, and connection changes. Connection construction does not call the provider or contact ORDS. Requests stay within the configured schema, redirects are rejected, and failed requests are not replayed automatically.

If the provider cannot supply a token, or ORDS returns 401, restore the database session in the host application before retrying. The existing `login()` and OML `connect()` entry points remain available. SQL needs the host token's SQL privilege; other client operations may need additional privileges. This connection does not sign in to Data Transforms.

To expose this session through argument-free `connect()`, the embedding application binds the verified capability to the same namespace used to execute notebook cells:

```python
adp.bind_runtime_connection(
    interpreter_namespace,
    host_session.schema_url,
    host_session.verified_database_user,
    host_session.get_ords_access_token,
)
# On disconnect or interpreter teardown:
adp.unbind_runtime_connection(interpreter_namespace)
```

The host must supply this binding inside the Python runtime and remove or replace it when the database session changes. Browser credentials are not automatically present in a remote interpreter. Graph's SQL pool supplies the automatic OAuth fallback described above. Do not paste bearer tokens or client secrets into saved notebooks.

### Oracle AI Data Catalog

The [Oracle AI Data Catalog](https://docs.oracle.com/en/cloud/paas/autonomous-database/serverless/adbsb/oracle-ai-data-catalog.html) is the Iceberg REST catalog built into Autonomous AI Database. One database in a tenancy hosts it; other databases mount it and query its tables in SQL. `client.AICatalog` covers both sides.

Before the first call, turn the catalog on: in the OCI console, give the Autonomous AI Database the tag `ADB$TOOLS` with value `AI_CAT` (the `ADB$FEATURE` tag `{"name": "AI_CAT", "enable": false}` turns it off). A database without it answers sign-in with "Unable to provision required compute resources"; the SDK says what that means. Catalog users are database users: ADMIN, or a user with the `AICAT_USER` or `PDB_DBA` role.

Browse and manage the catalog through its REST API. The catalog issues tokens for a database user and password, so `connect()` takes the password again; by default it uses the catalog on the database you logged in to:

```python
import adp

client = adp.login(url, "ADMIN", password)
cat = client.AICatalog
cat.connect(password=password)        # or catalog_url=..., username=... for another database

cat.list_namespaces()                 # ['sales', 'sales.eu']
cat.create_namespace("staging")
cat.list_tables("sales")
cat.get_table("sales", "orders")      # columns, partitioning, current snapshot
cat.grant(["SELECT_TABLE"], "ANALYST", "TABLE", "sales.orders")
cat.check_access("SELECT_TABLE", "TABLE", "sales.orders")
```

On the catalog database, ADMIN or PDB_DBA registers the object storage that holds the tables. The location must be empty and used for nothing else:

```python
cat.register_storage(
    "s3://my-bucket",
    "https://<namespace>.compat.objectstorage.<region>.oci.customer-oci.com",
    provider="OCI", region="<region>",
    access_key=customer_secret_key_id, secret_key=customer_secret_key)
```

To query catalog tables from a database, allow outbound HTTPS to the catalog host, create the credential the database signs in with, and mount the catalog. The catalog does not vend storage credentials, so reading data also needs a storage credential: an OCI Customer Secret Key whose user can read the catalog's bucket. Without one, schemas and tables can still be listed, `mount()` returns a warning, and reads fail with an error that names the bucket and the fix:

```python
cat.allow_catalog_host()              # as ADMIN, once per database user
cat.create_catalog_credential("AICAT_CRED", "CATALOG_USER", catalog_user_password,
                              catalog_url="https://<catalog-host>/catalog")
cat.create_storage_credential("OBJ_STORE_CRED", customer_secret_key_id, customer_secret_key)
cat.mount("AICAT", "AICAT_CRED", storage_credential="OBJ_STORE_CRED",
          catalog_url="https://<catalog-host>/catalog")
cat.set_storage_credential("AICAT", "OBJ_STORE_CRED")   # attach or replace later, no remount

cat.list_mounts()
cat.list_mounted_tables("AICAT", "sales")
cat.preview("AICAT", "sales", "orders", rows=10)
cat.query("AICAT", "sales", "orders",
          filters=[{"column": "order_date", "op": ">=", "value": "2026-01-01"}],
          group_by=["region"], aggregates=["SUM(amount) AS total"],
          order_by=["total DESC"], rows=10)
client.Misc.run_query('select * from "sales"."orders"@AICAT fetch first 10 rows only')
```

`query()` works on a table of any mounted catalog and never takes SQL text: column names must match the table's columns, and values are bind variables. Every value, including secrets, is sent as a SQL bind variable, and errors raise `adp.AICatalogError` without echoing the request. The MCP server exposes the same features as `adp_browse_ai_catalog` (read-only), `adp_query_mounted_table` (analyst) and `adp_manage_ai_catalog` (admin). Storage registration and credential creation stay in the SDK, so keys never pass through tool arguments.


`cat.check_setup("AICAT")` checks every step of a mount on both databases (sign-in, network access, mount, both credentials, a one-row read) and returns the fix for each one that fails.

#### Through the MCP server

With the MCP server, the same setup runs without Python and without secrets in the chat. Keep the catalog login and the bucket key on the server, in the OS keyring:

```bash
oracle-data-studio-config set ai_catalog --url https://<catalog-host>/catalog --user CATUSER   # prompts for the password; leave out --url when the catalog is on the ADP database
oracle-data-studio-config set ai_catalog --storage-key                                         # prompts for the OCI Customer Secret Key
```

(or set `ADP_AI_CATALOG_URL`, `ADP_AI_CATALOG_USER`, `ADP_AI_CATALOG_PASSWORD`, `ADP_AI_CATALOG_STORAGE_ACCESS_KEY` and `ADP_AI_CATALOG_STORAGE_SECRET_KEY`). Then `adp_manage_ai_catalog` runs `allow_catalog_host`, `create_catalog_credential`, `create_storage_credential` and `mount`, taking the secrets and the catalog address from that configuration, and `adp_browse_ai_catalog(action='check_setup')` confirms each step. The `ai_catalog_setup` prompt walks an assistant through it in order. Registering storage on the catalog database stays in the SDK.

The database that runs the queries can be a different one from the catalog's. Both need access to the bucket: the catalog database through `register_storage()` (read and write), and the querying database through the mount's storage credential (read and list), ideally with separate keys. The tools use only the configured catalog, refuse any other address, and never store the ADP login; use a dedicated catalog user with the `AICAT_USER` role rather than ADMIN.
