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.AgentAsATool(agent, name, ...)

Agent as a tool.

code_template_tools

code_template_tools.GetCodeTemplateFromVectorDB(*)

Get code template from vector database.

hana_ml_tools

hana_ml_tools.additive_model_forecast_tools.AdditiveModelForecastFitAndSave(...)

This tool is used to fit and predict the additive model forecast.

hana_ml_tools.additive_model_forecast_tools.AdditiveModelForecastLoadModelAndPredict(...)

This tool is used to load the additive model forecast from model storage and predict.

hana_ml_tools.additive_model_forecast_tools.MassiveAdditiveModelForecastFitAndSave(...)

This tool fits a grouped additive model forecast and saves it in model storage.

hana_ml_tools.additive_model_forecast_tools.MassiveAdditiveModelForecastLoadModelAndPredict(...)

This tool loads a grouped additive model forecast from model storage and predicts.

hana_ml_tools.automatic_timeseries_tools.AutomaticTimeSeriesFitAndSave(...)

This tool fits a time series model and saves it in the model storage.

hana_ml_tools.automatic_timeseries_tools.AutomaticTimeSeriesLoadModelAndPredict(...)

This tool load model from model storage and do the prediction.

hana_ml_tools.automatic_timeseries_tools.AutomaticTimeSeriesLoadModelAndScore(...)

This tool load model from model storage and do the scoring.

hana_ml_tools.cap_artifacts_tools.CAPArtifactsTool(...)

This tool generates CAP artifacts for a given model.

hana_ml_tools.config_dict_validator_tools.GetPALPipelineInfo(...)

Query _SYS_AFL.PAL_PIPELINE_INFO for the catalogue of operators supported by the current HANA instance.

hana_ml_tools.config_dict_validator_tools.GetAutoMLConfigDict(...)

Return the resolved config_dict for a given AutoML pipeline type.

hana_ml_tools.config_dict_validator_tools.ModifyAutoMLConfigDict(...)

Verify (and, if needed, amend) an AutoML config_dict via _SYS_AFL.PAL_AUTOML_CONFIG.

hana_ml_tools.dataset_prep_tools.ImportCSVToTableTool(...)

Import a local CSV file into a HANA table.

hana_ml_tools.dataset_prep_tools.SplitTableForForecastingTool(...)

Split a source HANA table into time-ordered train/test/validation tables for forecasting.

hana_ml_tools.fetch_tools.FetchDataTool(...)

This tool fetches data from a given table.

hana_ml_tools.hdi_artifacts_tools.HDIArtifactsTool(...)

This tool generates HDI artifacts for a given model.

hana_ml_tools.intermittent_forecast_tools.IntermittentForecast(...)

This tool generates forecast for the intermittent demand dataset.

hana_ml_tools.model_storage_tools.ListModels(...)

Tool to list all models in the model storage.

hana_ml_tools.model_storage_tools.DeleteModels(*, ...)

Tool to delete a model from the model storage.

hana_ml_tools.model_storage_tools.DisplayConfigDict(...)

Tool to display the config_dict used at training time for a stored AutoML model.

hana_ml_tools.select_statement_to_table_tools.SelectStatementToTableTool(...)

This tool stores SelectStatement data into a HANA table.

hana_ml_tools.ts_accuracy_measure_tools.AccuracyMeasure(...)

This tool calculates the accuracy measure for the time series forecast.

hana_ml_tools.ts_check_tools.TimeSeriesCheck(...)

This tool calls stationarity test, intermittent check, trend test and seasonality test for the given time series data.

hana_ml_tools.ts_check_tools.StationarityTest(...)

This tool calls stationarity test for the given time series data.

hana_ml_tools.ts_check_tools.TrendTest(...)

This tool calls trend test for the given time series data.

hana_ml_tools.ts_check_tools.SeasonalityTest(...)

This tool calls seasonality test for the given time series data.

hana_ml_tools.ts_check_tools.WhiteNoiseTest(...)

This tool calls white noise test for the given time series data.

hana_ml_tools.ts_make_predict_table.TSMakeFutureTableTool(...)

This tool creates a predict table for time series forecasting in HANA.

hana_ml_tools.ts_outlier_detection_tools.TSOutlierDetection(...)

This tool detects outliers in time series data.

hana_ml_tools.ts_visualizer_tools.TimeSeriesDatasetReport(...)

This tool generates a report for a time series dataset.

hana_ml_tools.ts_visualizer_tools.ForecastLinePlot(...)

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.

hana_ml_tools.graph_tools.ObjectDiscoveryTool(...)

Tool for discovering HANA objects via knowledge graph.

hana_ml_tools.graph_tools.DataRetrievalTool(...)

Tool for interacting with Data Retrieval.

df_tools

df_tools.automatic_timeseries_tools.AutomaticTimeSeriesFitAndSave(...)

This tool fits a time series model and saves it in the model storage.

df_tools.automatic_timeseries_tools.AutomaticTimeSeriesLoadModelAndPredict(...)

This tool load model from model storage and do the prediction.

df_tools.automatic_timeseries_tools.AutomaticTimeSeriesLoadModelAndScore(...)

This tool load model from model storage and do the scoring.

df_tools.fetch_tools.FetchDataTool(...[, ...])

This tool fetches data from a given table.

df_tools.ts_outlier_detection_tools.TSOutlierDetection(...)

This tool detects outliers in time series data.

df_tools.ts_visualizer_tools.TimeSeriesDatasetReport(...)

This tool generates a report for a time series.

hana_ml_toolkit

toolkit.HANAMLToolkit(connection_context[, ...])

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_url via SyncHTTPMCPClient, calls initialize to 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 via tools/list, and wraps each one as a langchain_core.tools.StructuredTool whose args_schema is derived from the tool's JSON Schema. The returned tools are drop-in replacements for local BaseTool instances — hand them to ContextAgent (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 /mcp is added automatically if absent (e.g. http://127.0.0.1:8001 and http://127.0.0.1:8001/mcp are both accepted). Only http/https transports 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/list and tools/call request.

client_namestr

End-user identity or client name passed to the server via clientInfo.name and the x-mcp-client-name header. Lands on HANA's APPLICATIONUSER channel and inside the pack's cli= 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 the x-mcp-client-id header

  • agent_name — sets x-ai-agent-name; lands in pack agent=

  • model_name — sets x-ai-model-name; lands in pack model=

  • model_version — sets x-ai-model-version

Values are stringified. Unknown keys are ignored.

skip_admin_toolsbool, default True

When True, tools whose name starts with admin_ (e.g. admin_update_connection_context) are excluded from the returned list. Set to False if 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, call client.close() to release the HTTP session and its MCP session id.

See also

SyncHTTPMCPClient

the underlying JSON-RPC client, exposed for callers that want direct access (session id inspection, manual call_tool invocations, etc.).

fetch_hana_mcp_audit_view

query 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 ContextAgent from 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_CACHE for 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_NAME etc.) are decoded from the pack in M_SQL_PLAN_CACHE.APPLICATION_SOURCE.

This gives an auditor sitting on the HANA side, with only SELECT on M_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 on M_SQL_PLAN_CACHE works — 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 APPLICATION value (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 via APPLICATION_SOURCE LIKE so schema differences across HANA builds don't matter.

since_secondsint, optional

Only rows with LAST_EXECUTION_TIMESTAMP newer than this many seconds ago. None returns 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_SOURCE from the first process that caused a given plan to be cached. Subsequent executions of the same SQL update EXECUTION_COUNT and LAST_EXECUTION_TIMESTAMP but 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 carries resp=<N>. This function extracts that resp= per invocation and left-joins it back onto every row of the same INVOCATION_ID (so the tool's real SQL rows show RESPONSE_SIZE too). The beacon rows themselves are filtered out of the returned DataFrame — auditors see one row per real cached plan, with RESPONSE_SIZE populated when the beacon fired. Failed tool calls have no beacon, so RESPONSE_SIZE stays None — 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_LOG at 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) and APPLICATION_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 no resp and the success-path "beacon" pack adds it. When identity plus resp overflows the 254-byte cap, resp is 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 the resp= 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'.