hana_ai.tools
hana.ai tools is a set of tools that can be used to perform various tasks like forecasting, time series analysis, etc.
agent_as_a_tool
|
Agent as a tool. |
code_template_tools
Get code template from vector database. |
hana_ml_tools
|
This tool is used to fit and predict the additive model forecast. |
|
This tool is used to load the additive model forecast from model storage and predict. |
|
This tool fits a grouped additive model forecast and saves it in model storage. |
|
This tool loads a grouped additive model forecast from model storage and predicts. |
|
This tool fits a time series model and saves it in the model storage. |
|
This tool load model from model storage and do the prediction. |
|
This tool load model from model storage and do the scoring. |
This tool generates CAP artifacts for a given model. |
|
|
Query |
|
Return the resolved |
|
Verify (and, if needed, amend) an AutoML |
Import a local CSV file into a HANA table. |
|
|
Split a source HANA table into time-ordered train/test/validation tables for forecasting. |
This tool fetches data from a given table. |
|
This tool generates HDI artifacts for a given model. |
|
|
This tool generates forecast for the intermittent demand dataset. |
Tool to list all models in the model storage. |
|
Tool to delete a model from the model storage. |
|
Tool to display the |
|
|
This tool stores SelectStatement data into a HANA table. |
|
This tool calculates the accuracy measure for the time series forecast. |
This tool calls stationarity test, intermittent check, trend test and seasonality test for the given time series data. |
|
This tool calls stationarity test for the given time series data. |
|
This tool calls trend test for the given time series data. |
|
This tool calls seasonality test for the given time series data. |
|
This tool calls white noise test for the given time series data. |
|
|
This tool creates a predict table for time series forecasting in HANA. |
|
This tool detects outliers in time series data. |
|
This tool generates a report for a time series dataset. |
This tool generates a line plot for the forecasted result. |
graph_tools
Knowledge-graph-backed retrieval tools exposed on the MCP server. ObjectDiscoveryTool calls the HANA AI Core object-discovery procedure (default AI_OBJECT_RETRIEVAL) to surface schemas, tables, columns, and their relationships as narrative context. DataRetrievalTool calls the paired data-retrieval procedure to fetch rows or aggregations for a natural-language question. Both tools share the hana_ai.retrieval clients and expect a HANA remote source connected to AI Core.
Tool for discovering HANA objects via knowledge graph. |
|
Tool for interacting with Data Retrieval. |
df_tools
|
This tool fits a time series model and saves it in the model storage. |
|
This tool load model from model storage and do the prediction. |
|
This tool load model from model storage and do the scoring. |
|
This tool fetches data from a given table. |
This tool detects outliers in time series data. |
|
This tool generates a report for a time series. |
hana_ml_toolkit
|
Toolkit for interacting with HANA SQL. |
hana_ml_tools.utility
Module-level helpers for MCP server/client bootstrap, audit inspection, and
the HANA-side APPLICATIONSOURCE pack that carries MCP identity into
M_SQL_PLAN_CACHE / AUDIT_LOG. See MCP session auditing for the audit
story end-to-end.
- hana_ai.tools.hana_ml_tools.utility.build_context_agent_mcp_tools(base_url: str, *, timeout: int = 120, client_name: str, client_version: str = '0.1', client_metadata: dict[str, Any] | None = None, skip_admin_tools: bool = True)
Build LangChain-compatible tools backed by an HTTP MCP server.
Opens an HTTP MCP session against
base_urlviaSyncHTTPMCPClient, callsinitializeto hand the server the end-user / agent / model identity that will show up in every HANA audit row (see MCP session auditing), enumerates the server's tool catalogue viatools/list, and wraps each one as alangchain_core.tools.StructuredToolwhoseargs_schemais derived from the tool's JSON Schema. The returned tools are drop-in replacements for localBaseToolinstances — hand them toContextAgent(or any LangChain agent) and every invocation transparently round-trips through the MCP server, so the HANA-side audit path (setclientinfo, plan cache, audit log) is exercised end-to-end.- Parameters:
- base_urlstr
MCP server URL. Trailing
/mcpis added automatically if absent (e.g.http://127.0.0.1:8001andhttp://127.0.0.1:8001/mcpare both accepted). Onlyhttp/httpstransports are supported by this helper — for stdio, use the stdio client directly.- timeoutint, default 120
Per-request HTTP timeout in seconds. Applied to every
tools/listandtools/callrequest.- client_namestr
End-user identity or client name passed to the server via
clientInfo.nameand thex-mcp-client-nameheader. Lands on HANA'sAPPLICATIONUSERchannel and inside the pack'scli=segment.- client_versionstr, default "0.1"
Client version tag; lands on HANA's
APPLICATIONVERSION.- client_metadatadict, optional
Optional identity metadata forwarded to the server. Recognised keys:
client_id— sets thex-mcp-client-idheaderagent_name— setsx-ai-agent-name; lands in packagent=model_name— setsx-ai-model-name; lands in packmodel=model_version— setsx-ai-model-version
Values are stringified. Unknown keys are ignored.
- skip_admin_toolsbool, default True
When
True, tools whose name starts withadmin_(e.g.admin_update_connection_context) are excluded from the returned list. Set toFalseif the agent needs to manage the server's connection context at runtime.
- Returns:
- tuple[list[StructuredTool], SyncHTTPMCPClient]
(tools, client)— the LangChain-ready tools, and the live MCP client. Keep the client alive for the duration of the agent session; when done, callclient.close()to release the HTTP session and its MCP session id.
See also
SyncHTTPMCPClientthe underlying JSON-RPC client, exposed for callers that want direct access (session id inspection, manual
call_toolinvocations, etc.).fetch_hana_mcp_audit_viewquery the HANA-side audit view populated by every tool call made through the returned tools.
Examples
Launch the MCP server on one process, then wire it into a
ContextAgentfrom another:>>> from hana_ai.tools.hana_ml_tools.utility import build_context_agent_mcp_tools >>> tools, client = build_context_agent_mcp_tools( ... "http://127.0.0.1:8001/mcp", ... client_name="context-agent-notebook", ... client_metadata={ ... "agent_name": "context-agent", ... "model_name": "gpt-4.1", ... }, ... ) >>> [t.name for t in tools][:3] ['fetch_data', 'list_models', 'display_config_dict'] >>> # Hand `tools` to any LangChain agent; every call now carries the >>> # context-agent identity all the way into HANA's audit trail.
- hana_ai.tools.hana_ml_tools.utility.ensure_mcp_audit_log(audit_log_path: str = 'logs/mcp-audit.jsonl') Path
Ensure the MCP audit JSONL file exists and return its resolved path.
- hana_ai.tools.hana_ml_tools.utility.fetch_mcp_audit_rows(audit_log_path: str, session_id: str)
Fetch audit rows for a given MCP session id from the JSONL audit log.
In addition to the flat MCP audit event columns, each row includes
APPLICATIONSOURCE_PACK— the pipe-delimited pack that would land in HANA's setclientinfo APPLICATIONSOURCE for that invocation. This makes the JSONL sink self-describing for the "what did HANA see?" question without a separate live connection.
- hana_ai.tools.hana_ml_tools.utility.fetch_hana_session_context(connection, keys: list[str] | None = None) DataFrame
Fetch selected HANA SESSION_CONTEXT values into a single-row DataFrame.
- hana_ai.tools.hana_ml_tools.utility.fetch_hana_appsource_pack(connection) dict
Read APPLICATIONSOURCE off the current HANA connection and parse it.
Convenience wrapper around
SESSION_CONTEXT('APPLICATIONSOURCE')+parse_appsource_pack. Returns an empty dict when APPLICATIONSOURCE is unset. Useful when hand-inspecting a live MCP session's HANA-side context without opening the JSONL / HANA audit sink.
- hana_ai.tools.hana_ml_tools.utility.fetch_hana_mcp_audit_view(connection, *, mcp_session_id: str | None = None, application_name: str | None = None, tool_name: str | None = None, since_seconds: int | None = None, limit: int = 200) DataFrame
Query
M_SQL_PLAN_CACHEfor MCP-tagged SQL and decode the pack.Returns a DataFrame of
HANA_MCP_AUDIT_VIEW_COLUMNS, one row per plan-cache entry produced by an MCP tool call visible on this HANA instance. Each row's identity fields (MCP_SESSION_ID,TOOL_NAME,INVOCATION_ID,AGENT_NAMEetc.) are decoded from the pack inM_SQL_PLAN_CACHE.APPLICATION_SOURCE.This gives an auditor sitting on the HANA side, with only
SELECTonM_SQL_PLAN_CACHE, a picture of which MCP session / agent / tool / invocation first produced each cached SQL plan — without needing HANA audit policies to be enabled and without touching the MCP host at all.- Parameters:
- connection
A live HANA
dbapi.Connection. Any connection with SELECT onM_SQL_PLAN_CACHEworks — it does not have to be the same connection that ran the MCP tools.- mcp_session_idstr, optional
Filter to a single MCP session id. Matches the
sess=field.- application_namestr, optional
Filter by the setclientinfo
APPLICATIONvalue (MCP client's declared name). Useful when several MCP fleets share one HANA landscape.- tool_namestr, optional
Filter to a specific tool invocation. Matches the pack's
tool=field viaAPPLICATION_SOURCE LIKEso schema differences across HANA builds don't matter.- since_secondsint, optional
Only rows with
LAST_EXECUTION_TIMESTAMPnewer than this many seconds ago.Nonereturns everything the plan cache still holds.- limitint
Maximum rows returned. Default 200. Set to a high number if you expect to paginate on the client side.
Notes
First-execution-wins semantics: HANA populates
M_SQL_PLAN_CACHE.APPLICATION_SOURCEfrom the first process that caused a given plan to be cached. Subsequent executions of the same SQL updateEXECUTION_COUNTandLAST_EXECUTION_TIMESTAMPbut leave the pack untouched. Different tools produce different SQL so each tool's rows carry that tool's own pack, but repeated calls to the same tool from different MCP sessions all appear under the first session's pack. This is a HANA server-side property; no client-side merge with local files is done here (audit is server-side by contract).``RESPONSE_SIZE`` population: only known after the tool body runs, so it cannot travel in the started-path pack that HANA freezes onto the tool's own plan-cache rows. Instead, after each successful tool call the MCP host executes a synthetic "beacon" statement (
SELECT ... mcp-audit-beacon inv=<invocation_id> ...) whose APPLICATION_SOURCE carriesresp=<N>. This function extracts thatresp=per invocation and left-joins it back onto every row of the sameINVOCATION_ID(so the tool's real SQL rows showRESPONSE_SIZEtoo). The beacon rows themselves are filtered out of the returned DataFrame — auditors see one row per real cached plan, withRESPONSE_SIZEpopulated when the beacon fired. Failed tool calls have no beacon, soRESPONSE_SIZEstaysNone— check the JSONL sink or the audit sink to distinguish "beacon evicted / not yet fired" from "tool failed before returning".Plan cache eviction: entries age out on their own schedule. For long-term retention on the HANA side, enable HANA audit policies so the pack is recorded in
AUDIT_LOGat each SQL execution rather than only at plan-caching time.APPLICATION_USER_NAME: not exposed on every HANA build; this function uses
USER_NAME(HANA-authenticated) andAPPLICATION_NAME(setclientinfo APPLICATION) which are portable.
- hana_ai.tools.hana_ml_tools.utility.build_appsource_pack(*, mcp_version: str | None = None, mcp_session_id: str | None = None, client_declared_name: str | None = None, client_declared_agent_name: str | None = None, client_declared_model_name: str | None = None, client_ip: str | None = None, tool_name: str | None = None, invocation_id: str | None = None, hana_correlation_id: str | None = None, response_size: int | None = None, max_bytes: int = 254) str
Build the pipe-delimited pack for setclientinfo('APPLICATIONSOURCE').
All identity fields (
mcp,sess,agent,model,cli,mcp_ip,tool,inv,corr) are packed in fixed order; each is sanitized to an ASCII token ([A-Za-z0-9._:/@-]).resp(a decimal integer, tool response_size) is optional and packed last; it is only known after the tool body runs, so the started-path pack has norespand the success-path "beacon" pack adds it. When identity plusrespoverflows the 254-byte cap,respis dropped first (tail-first truncation via_truncate_on_pipe); auditors can still recover the value from the JSONL sink.The returned string is ASCII and its byte length is guaranteed to be
<= max_bytes(verified against HANA's 256-byte setclientinfo cap).
- hana_ai.tools.hana_ml_tools.utility.parse_appsource_pack(pack: str | None) dict
Parse the pipe-delimited APPLICATIONSOURCE pack into a dict.
Returns a dict of the identity K=V pairs (
mcp,sess,agent,model,cli,mcp_ip,tool,inv,corr) and, when present,response_size(parsed from theresp=segment written by the post-completion beacon; missing on started-path packs).
- hana_ai.tools.hana_ml_tools.utility.find_free_port(start: int = 8600, end: int = 8700) int
Return an available localhost TCP port.
- hana_ai.tools.hana_ml_tools.utility.DEFAULT_MCP_SESSION_CONTEXT_KEYS = ['EVENT_TYPE', 'OCCURRED_AT', 'MCP_SESSION_ID', 'CLIENT_IP', 'CLIENT_DECLARED_NAME', 'CLIENT_DECLARED_AGENT_NAME', 'CLIENT_DECLARED_MODEL_NAME', 'HANA_DB_USER', 'HANA_DB_SESSION_USER', 'HANA_CONNECTION_ID', 'HANA_APPLICATION_USER', 'HANA_APPLICATION', 'HANA_CLIENT_HOST', 'TOOL_NAME', 'TARGET_TABLES', 'TOOL_ARGS_JSON', 'RESPONSE_SIZE', 'MODEL_STORAGE_NAME', 'MODEL_STORAGE_VERSION', 'STATUS', 'DURATION_MS', 'HANA_CORRELATION_ID', 'INVOCATION_ID', 'MCP_CLIENT_NAME', 'MCP_CLIENT_ID', 'AI_AGENT_NAME', 'AI_MODEL_NAME']
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
- hana_ai.tools.hana_ml_tools.utility.APPLICATIONSOURCE_MAX_BYTES = 254
int([x]) -> integer int(x, base=10) -> integer
Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero.
If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4
- hana_ai.tools.hana_ml_tools.utility.APPLICATIONSOURCE_FIELD_ORDER = ('mcp', 'sess', 'agent', 'model', 'cli', 'mcp_ip', 'tool', 'inv', 'corr', 'resp')
Built-in immutable sequence.
If no argument is given, the constructor returns an empty tuple. If iterable is specified the tuple is initialized from iterable's items.
If the argument is a tuple, the return value is the same object.
- hana_ai.tools.hana_ml_tools.utility.HANA_MCP_AUDIT_VIEW_COLUMNS = ['LAST_EXECUTION_TIMESTAMP', 'MCP_SESSION_ID', 'INVOCATION_ID', 'HANA_CORRELATION_ID', 'TOOL_NAME', 'RESPONSE_SIZE', 'AGENT_NAME', 'MODEL_NAME', 'CLIENT_DECLARED_NAME', 'CLIENT_IP', 'MCP_VERSION', 'HANA_AUTHENTICATED_USER', 'HANA_SESSION_USER', 'STATEMENT_HASH', 'EXECUTION_COUNT', 'APPLICATION_NAME', 'APPLICATION_SOURCE']
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
- hana_ai.tools.hana_ml_tools.utility.MCP_BEACON_SQL_MARKER = 'mcp-audit-beacon'
str(object='') -> str str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to 'strict'.