Data Brain

Connect databases and files, inspect them, and query them without handing credentials to a model.

Data Brain sits between your data and anything that asks questions of it. It connects to a source, previews and inspects it, and answers queries, so an agent can use the data without ever holding the connection details.

It stores no credentials. The connection (host, user, password, or the details of an uploaded file) travels with every query, and the service keeps a pooled connection open for a while so repeated queries are fast. Your backend holds the connection details; the model only ever sees results.

pip install aice-data-brain

Create a client

import os
from aice_data_brain import DataBrainClient

client = DataBrainClient(
    base_url=os.environ["AICE_DATA_BRAIN_URL"],  # http://localhost:6300
    api_key=os.environ["AICE_API_KEY"],
    user_id=current_user.id,                     # recorded in the query log
)
Argument (Python / TypeScript)DefaultMeaning
base_url / baseUrlthe service host. The client adds /v1/plugin/... itself, so there is no path to include
api_key / apiKeythe project key. Needs Data Brain enabled on the project
user_id / userIdnonesent as X-User-Id, the acting user the query log records (see Access)
user_role / userRolenonesent as X-User-Role
timeout30.0 s / 30000 msper-request timeout
max_retries / maxRetries3retries for reads and uploads. process and cleanup are never retried

Python also has AsyncDataBrainClient with the same resources; await every call and close it with await client.aclose(). The sync client closes with client.close() or with DataBrainClient(...) as client:.

Find out what you can connect to

for connector in client.descriptors.list():
    print(connector["key"], [f["name"] for f in connector["input_fields"]])

descriptors.list() returns one entry per connector. key is the connection_type every other call takes, and input_fields describes the form a connection needs (name, label, type, whether it is required). Build your own connection form from it.

connection_type is one of:

DatabasesFilesAPIs
postgresql, mysql, mariadb, oracledb, couchdb, duckdbcsv_v2, excel, parquet, jsondatadog (only when the deployment has its API collection)

An unknown connection_type returns 404, which the SDK raises as NotFoundError.

Query a database

The connection goes in data; the query goes in query. For SQL connectors a plain string is enough: the client wraps it as {"query": "..."} for you.

result = client.connections.query(
    "postgresql",
    data={
        "host": "db.internal", "port": 5432, "database": "sales",
        "user": "reader", "password": os.environ["SALES_DB_PASSWORD"],
    },
    query="SELECT region, SUM(total) AS revenue FROM orders GROUP BY region",
)
if result["error"]:
    print("query failed:", result["error"])
else:
    print(result["rowCount"], result["rows"])

The result has the same shape in both languages:

FieldMeaning
rowsa list of objects, one per row, keyed by column name
rowCounthow many rows came back
errornull on success, otherwise the database's message
cachepresent only when the cache was involved: status (hit, miss, bypass), plus ageMs, storedAt, ttlMs

A failed query is not an exception

A query the database rejects (bad SQL, missing table, permission denied) still returns HTTP 200 with rows: [], rowCount: 0 and the message in error. Check error on every result. Exceptions are raised only for transport and service failures: an unknown connector (NotFoundError), a malformed body (ValidationError), or the service being down.

Non-SQL connectors take a structured query. Pass a dict / object instead of a string:

Connectorquery
SQL connectors (postgresql, mysql, mariadb, oracledb, duckdb, file connectors){"query": "SELECT ..."} or just the string
couchdb (Mango){"db": "orders", "selector": {...}, "limit": 50}
couchdb (all documents){"db": "orders", "allDocs": true, "limit": 100}
datadog{"endpointName": "List Metrics", "params": {...}}

Preview and inspect a connection

conn = {"host": "db.internal", "port": 5432, "database": "sales", "user": "reader", "password": "…"}

check = client.connections.preprocess("postgresql", data=conn)
print(check["success"], check.get("issues"))
for table in check.get("tables", []):
    print(table["table_name"], [c["name"] for c in table["columns"]])

schema = client.connections.inspect("postgresql", data=conn)
print(schema["mode"], schema["tables"])
  • preprocess validates the configuration, tests that it connects, and returns {success, issues, tables} with each table's columns and a few preview rows. It changes nothing, so use it for a "test connection" button.
  • inspect returns the schema in a form built for writing queries. Most connectors answer mode: "schema" with tables; API connectors such as datadog answer mode: "query_builder" with the endpoints you can call. legacyTables repeats tables for older readers.
  • process establishes or syncs state. For database connectors it does nothing ({}); for file connectors it reconciles stored files against the connection's history. It is not retried: a second run could repeat work.
  • cleanup releases what the connection holds: it drops the pooled database connection immediately, or deletes a file connector's stored objects. Call it when you delete a connection in your own system. It is not retried, because a blind duplicate is the worst outcome for something destructive.

In Python, preprocess, process, cleanup and inspect take the body as keyword arguments (data=...); in TypeScript they take (connectionType, payload).

Work with files

File connectors read a file you upload, using DuckDB underneath. Four are available: csv_v2 (csv, tsv, parquet, json, ndjson, jsonl), excel (xlsx), parquet and json.

Upload

with open("sales.csv", "rb") as f:
    uploaded = client.files.upload("csv_v2", file=f.read(), filename="sales.csv")

details = uploaded["file_details"]
table = details[0]["tables"][0]
print(table["table_name"], [c["name"] for c in table["columns"]])

files.upload does three calls: Data Brain signs an upload form, the SDK posts the file straight to Data Brain's storage (no bytes pass through the API), then Data Brain checks and describes it. The file is stored under your project, at a key of its own: uploading the same name again stores a second file and never replaces the first. The response is {"file_details": [...]}: for each file, its bucket_name, object_name, file_name and its tables, each with columns and a preview.

Set rectify_issue=True / rectifyIssue: true to let Data Brain clean up column names it can't use as they are, the same option preprocess takes.

Query

Pass file_details back unchanged, and name the table in your SQL:

rows = client.files.query(
    "csv_v2", details, f'SELECT region, COUNT(*) AS n FROM "{table["table_name"]}" GROUP BY region'
)["rows"]

files.query is connections.query with the connection already set to {"file_details": ...}. You can store file_details in your own database and reuse it for later queries.

To delete a file connector's stored objects when you delete the connection in your own system, call connections.cleanup.

Uploads are limited to 100 MiB by default (UPLOAD_MAX_BYTES) and the file's extension must be one the connector accepts. These errors come back as the SDK's usual types:

StatusRaised asWhen
400ValidationErrorempty file, bad file name, or a connector that isn't a file connector
401AuthenticationErrormissing or invalid key, or key not issued for Data Brain
404NotFoundErrorcompleting an upload whose file never reached storage
409AiceErrorthe stored file changed while Data Brain was checking it
413AiceErrorover the size limit (storage itself also refuses a bigger file)
415AiceErrorthe connector doesn't accept that extension
422ValidationErrorDuckDB couldn't read the file (the stored object is deleted)

Call any REST API

The rest_api connector reaches any HTTP API, reads and writes alike. The connection says where and how to call it; each query names a method and a path.

api = {
    "baseUrl": "https://api.example.com/v1",          # https only
    "auth": {"type": "bearer", "token": os.environ["SHOP_TOKEN"]},
    "allowedMethods": ["GET", "POST"],                 # default: all seven
    "allowedPaths": ["/orders*"],                      # default: every path
    "pagination": {"type": "cursor", "cursorPath": "meta.next"},
    "openapi": {"specUrl": "https://api.example.com/openapi.json"},   # optional
}
client.rest.check(api)                                 # reachable with these credentials?
client.rest.inspect(api)                               # the operations a query may call
rows = client.rest.request(api, "GET", "/orders", params={"status": "open"}, select="data")["rows"]
client.rest.request(api, "POST", "/orders", body={"sku": "A-1", "qty": 2})
Connection field
baseUrlEvery path is relative to it. Optional when the OpenAPI spec names a server.
authbearer {token}, basic {username, password}, header or query {name, value}, or oauth2_client_credentials {tokenUrl, clientId, clientSecret, scope?, audience?, authStyle?}.
allowedMethods, allowedPathsThe only limits on what a query may do, for your code and for agents alike. Paths are globs (* crosses /) and apply to every next-page link and redirect too.
defaultHeaders, pagination, openapi, healthPath, timeoutMsOptional. Pagination is offset, page, cursor or link, for GET requests.
  • A GET returns the API's records as rows, picked with select (JMESPath) or found as the first list in the response, and paged per the connection unless you pass paginate=False.
  • Anything other than GET, HEAD or OPTIONS changes data at once. There is no confirmation and no undo; each write is sent once (never retried automatically) and recorded in the query log as a write. Use a least-privilege API key.
  • Private and internal addresses are refused, and so are redirects to another host.
  • API errors come back in error ("HTTP 404: …"), with every credential masked.

The console's playground has the same connector: pick Database or API › REST API, fill in the form, and list the API's operations to fill in a request.

Retries

CallRetried?
descriptors.list, health.checkyes (reads)
connections.preprocess, query, inspectyes, with an automatic Idempotency-Key, except a rest_api write: sent once
connections.process, connections.cleanupno: one attempt, so a timeout can't run them twice
files.uploadthe signing call yes; the storage post and the completing call no (a completed upload can't be completed twice)

See Errors and retries for why.

Through the umbrella

aice.data_brain / aice.dataBrain on the umbrella gets the umbrella's acting user, so uploads work through it too (from aice-sdk 0.1.0 / @aiceafrica/sdk 0.2.0).

Use it from an agent

Add Data Brain to an agent in Agent Studio (tool_bindings: ["data_brain"] in code). Agents reach it through its MCP endpoint at /v1/mcp, with three tools:

ToolSame asDoes
list_connectors()descriptors.list()the connector types and the fields each needs
inspect_connection(connection_type, connection)connections.inspecttables and columns, or the endpoints a connector offers
run_query(connection_type, connection, query)connections.queryruns a query and returns rows

The connection is a tool argument

Because Data Brain stores no connections, the agent passes the full connection (credentials included) to inspect_connection and run_query. Nothing in the service ties a connection to the person asking, so scope which connection an agent may use upstream, in whatever supplies the agent's context. Never let content the agent has read decide the connection.

The REST API

The SDKs wrap these routes; call them directly from any other language. Every connection route is under /v1/plugin.

EndpointSDK methodDoes
POST /v1/plugin/{connection_type}/preprocessconnections.preprocessvalidates the configuration and previews the source
POST /v1/plugin/{connection_type}/processconnections.processprocesses it, for example reconciling files
POST /v1/plugin/{connection_type}/inspectconnections.inspectdescribes what's there: tables, columns, types
POST /v1/plugin/{connection_type}/queryconnections.queryruns a query. The only one with a second field, query
POST /v1/plugin/{connection_type}/cleanupconnections.cleanupreleases what process or the pool holds
POST /v1/plugin/{connection_type}/uploadsfiles.createUpload / create_uploadstep 1 of an upload: {upload_id, upload_url, fields, expires_in, max_bytes}, a signed form for one file. POST the file to upload_url as multipart, every fields entry first and file last
POST /v1/plugin/{connection_type}/uploads/{upload_id}/completefiles.completeUpload / complete_uploadstep 3: checks and describes the stored file, returns file_details
GET /v1/datasource-descriptorsdescriptors.listevery connector and its fields
GET /healthhealth.checkthe service and each connector's status
curl -X POST "$AICE_DATA_BRAIN_URL/v1/plugin/postgresql/query" \
  -H "Content-Type: application/json" \
  -d '{
    "data":  { "id": "conn_1", "workspace_id": "ws_1", "host": "db.internal", "database": "sales" },
    "query": { "query": "SELECT region, SUM(total) FROM orders GROUP BY region" }
  }'

The connection fields can sit directly under data or under data.properties; both are read. The fields themselves depend on the connector, and the descriptors list them.

Headers

HeaderPurpose
X-Workspace-Id, X-Connection-Idoptional. Let the service pool connections and keep file-based connectors inside a workspace

Caching

Query results are cached when data includes both workspace_id and id. Without them, every query runs fresh. The cache deliberately doesn't use the headers above.

Errors

A malformed body returns 400 with {statusCode, error, message}, not 422. An unknown connection_type returns 404.

Access

Every /v1/plugin route requires the project key; its project decides the bucket and the data you reach. /v1/datasource-descriptors and /health are open. Agents reach Data Brain through its MCP endpoint at /v1/mcp, which uses signed requests between services.

Send X-User-Id too, as the SDK and the console's snippets do: the query log attributes the call to that user (an unverified claim; the key is what's checked).

Query log

Data Brain records every query, inspect, preprocess, process, cleanup and upload, from your backend and from agents alike. Each record holds:

  • Who: the project, the user (verified when a valid key came with it), the agent for MCP calls, and the client IP.
  • What: the connector, target host and database, and the query text up to 16 KB with a hash of the whole query.
  • How it ended: status, error, row count, duration and whether the cache answered.
  • A classification: read, write, DDL, admin or multi-statement, plus flags such as system-catalog reads, file or OS access, time delays and UNION SELECT with a tautology.

Classification is for review only and never blocks a query. Connection credentials are never recorded: only the host and database are kept, picked out by name.

Organization admins see it in the console under Data Brain → Query log. Needs review filters to everything that isn't a plain read, and each row links to every run of the same query and everything from the same user. Records are kept for 395 days (QUERY_AUDIT_RETENTION_DAYS).

GET /health reports the service and each connector's status.

On this page