# Custom Tools A **custom tool** is a small Python function that returns a table (a pandas `DataFrame`) and is exposed to the model as its own MCP tool. The function can do anything that produces rows — read a CSV, run a OneTick query, or compute in-process. The server wraps it with OneTick authentication, a timeout, result formatting (and an optional row cap), so your file only contains the logic. This is the general extension point for **non-search** tools that return data. If instead you want to make a folder of Markdown **searchable** (natural-language `query` lookups), use `CUSTOM_COLLECTIONS` — see `Custom Search Tools`. Rule of thumb: *search my documents* → custom search tool; *run my query/code and return a table* → custom tool (this page). The bundled `search_symbol_universe` tool is itself a custom tool (see `OneTick Data Tools`); to replace its query, add your own custom tool and disable the built-in — see `Replacing a bundled tool` below. ## What you write A tool is a single `.py` module. You provide three things: * **Tool name** — a module-level `TOOL_NAME` string, the name the model (and `ONETICK_DB_TOOLS`) uses, e.g. `"instrument_count"`. It must be unique. * **A function named exactly** `run` — it must return a `pandas.DataFrame`. Its **typed parameters become the tool’s inputs**; annotate each as `Annotated[, ""]` so the model knows what to pass. Give optional inputs a default value. * **A docstring on** `run` — it becomes the **tool description** the model reads to decide when to call the tool. The module is the single source of truth for the tool’s name, description and inputs — there is no duplicate configuration. #### NOTE `settings` is a **reserved** parameter name. If `run` declares a parameter named `settings` (unannotated, or annotated as the settings type), the server injects the settings object into it and hides it from the tool’s inputs — use it to read your own configuration. A `settings` parameter annotated as anything else makes the server fail fast at startup. #### NOTE A tool file may only import `onetick`, `datetime`, `typing`, `math` and `pandas` (see `Trust and OneTick access`). In particular it **cannot import** `pydantic` — the server refuses to load the file with `'from pydantic import ...' is not allowed` — so describe inputs with a plain string in `Annotated[...]`, as in the examples below. ## Example ```python # /opt/onetick/tools/watchlist.py from typing import Annotated import pandas as pd TOOL_NAME = "watchlist" def run( group: Annotated[str, "Watchlist group name, e.g. 'energy'."], ) -> pd.DataFrame: """Return the instruments in a named watchlist.""" df = pd.read_csv("/opt/onetick/watchlists.csv") return df[df["group"] == group] ``` The tool reads a CSV file with a `group` column; any other columns are returned as they are. For example, `/opt/onetick/watchlists.csv`: ``` group,symbol,db energy,XOM,US_COMP energy,CVX,US_COMP tech,AAPL,US_COMP tech,MSFT,US_COMP ``` Calling `watchlist` with `group="energy"` returns the two `energy` rows. A group that does not exist returns an empty table, not an error. #### NOTE The tool runs where the server runs, so the CSV path must exist on that host or inside that container. This example only reads a local file, but the server still checks OneTick WebAPI credentials before it serves any custom tool — see `Custom tools and OneTick credentials`. ## Registering it Put the tool file where the server can read it: the path in `CUSTOM_TOOLS` is resolved on the machine or inside the container that runs the server (in Docker, mount the file into the container). Then point the `CUSTOM_TOOLS` setting at your file(s), a list of `{"path": ...}` entries, in your `.env` or environment: ``` CUSTOM_TOOLS='[{"path": "/opt/onetick/tools/watchlist.py"}]' ``` #### NOTE If `ONETICK_DB_TOOLS` is set, include the tool’s `TOOL_NAME` in it. A custom tool file is only loaded when its name is listed, so an unlisted tool is not loaded or served, and its file is not checked at startup (see `Enabling and disabling`). Optional per-entry keys: `max_results` (hard row cap for this tool) and `timeout` (seconds). For example, to cap this tool at 50 rows and time it out after 30 seconds: ``` CUSTOM_TOOLS='[{"path": "/opt/onetick/tools/watchlist.py", "max_results": 50, "timeout": 30}]' ``` To see the cap work with the sample CSV above, set `"max_results": 1` and call `watchlist` with `group="energy"`. Only one of the two rows is returned, and the result says it was truncated. #### NOTE A tool’s result is truncated to a row cap resolved with this precedence: an **explicitly set** `QUERY_TOOL_MAX_RESULTS` (environment / `.env`) overrides everything; otherwise this entry’s `max_results`; otherwise the `QUERY_TOOL_MAX_RESULTS` default (`100`). When more rows match than are shown, the result reports the total and asks the agent to narrow the request. Set a per-entry `max_results` to raise or lower the default for one tool (a higher cap for a compact result, a lower one for very wide rows); set `QUERY_TOOL_MAX_RESULTS=0` to disable the cap globally. The MCP client still rejects any result over its own tool-result size limit. The tool registers at startup under its `TOOL_NAME`. Once the tool is enabled, the server **fails fast** with a clear message if the file is missing, defines a duplicate name, or is missing `TOOL_NAME` / `run`. ## Enabling and disabling Every tool is enabled or disabled **by its name** via `ONETICK_DB_TOOLS`: * Leave `ONETICK_DB_TOOLS` unset to serve everything, including custom tools. * List names to restrict. Once it is set, only the names listed are served, custom tools included. For example, serve only your tool plus the reference-data tools: ``` ONETICK_DB_TOOLS=watchlist,list_databases,db_tables,db_table_schemas,db_field_descriptions,db_field_enumerations,calendar_holidays,trading_hours ``` * An unknown name fails fast at startup (typo guard). * To confirm a custom tool is active, look for `Loaded custom tool ''` and `Registered MCP tool: ` in the startup log. The bundled tools always log `Loaded custom tool` even when `ONETICK_DB_TOOLS` leaves them out, so `Registered MCP tool` is the line that means the tool is served. See `Tools` for the full enablement model. ## Example: a custom database info tool The reference-data tools (`Reference Data Tools`) read a fixed set of files. To serve information they do not cover — for example which team owns each database, its region and how long data is retained — keep it in a file of your own and add a custom tool that reads it. 1. **Create the data file.** Put it in your `ONETICK_DB_CSV_DATA_PATH` directory next to the reference-data files, tab-separated with a header row like them. For example, `db_info.txt`: ``` DB_NAME OWNER REGION RETENTION_DAYS DESCRIPTION US_COMP Equities Data US 3650 Consolidated US equities trades and quotes CME_GLOBEX Futures Data US 1825 CME Globex futures and options LSE Equities Data EU 3650 London Stock Exchange equities ``` The columns are separated by tab characters, not spaces. 2. **Write the tool file.** It declares the reserved `settings` parameter so the server passes in its settings, and builds the file path from `settings.CSV_DATA_PATH`. The path therefore follows `ONETICK_DB_CSV_DATA_PATH` on every host, in Docker and on Windows, with nothing hard-coded. `settings` is not shown to the model as an input. ```python # /opt/onetick/tools/db_info.py from typing import Annotated, Optional import pandas as pd TOOL_NAME = "db_info" def run( settings, db_name: Annotated[Optional[str], "OneTick database name, e.g. 'US_COMP' (case-insensitive). Omit to list all."] = None, region: Annotated[Optional[str], "Region filter, e.g. 'US' or 'EU' (case-insensitive)."] = None, ) -> pd.DataFrame: """Look up in-house information about our OneTick databases: owning team, region, retention and a description. Use for questions like "who owns US_COMP?" or "which databases are in the EU?". """ path = settings.CSV_DATA_PATH.rstrip("/\\") + "/db_info.txt" df = pd.read_csv(path, sep="\t", dtype=str) if db_name: df = df[df["DB_NAME"].str.upper() == db_name.strip().upper()] if region: df = df[df["REGION"].str.upper() == region.strip().upper()] return df ``` The path is built with string concatenation because a tool file cannot import `os` or `pathlib` (see `Trust and OneTick access`). `pd.read_csv` accepts `/` as the separator on Windows too. 3. **Register and enable it** in your `.env`. Give the tool its own name: `list_databases` is a bundled name, and a custom tool that reuses it is rejected at startup. ``` ONETICK_DB_CSV_DATA_PATH=/opt/onetick/reference-data/ CUSTOM_TOOLS='[{"path": "/opt/onetick/tools/db_info.py"}]' ONETICK_DB_TOOLS=db_info,list_databases,db_tables,db_table_schemas ``` The server must also pass the OneTick credentials check — see `Custom tools and OneTick credentials`. 4. **Restart the server** and check the startup log for `Registered MCP tool: db_info`. Calling `db_info` with `region="us"` returns: ``` Total results: 2. DB_NAME OWNER REGION RETENTION_DAYS DESCRIPTION US_COMP Equities Data US 3650 Consolidated US equities trades and quotes CME_GLOBEX Futures Data US 1825 CME Globex futures and options ``` The tool reads the file on every call, so edits to `db_info.txt` take effect on the next call without a restart. Changes to the tool file itself need a restart. ### Choosing the columns to filter on The filters are defined in the tool file; there is no setting that lists filter columns. Each filter is one parameter of `run` plus one line that applies it to the table. The model sees each parameter’s name, type and description, so that is how it learns what it can filter on. To filter on another column, add a parameter and a matching line: * Give the parameter a default of `None` so the model can omit it; when it is omitted, the `if` skips that filter. * Refer to the column by its exact header name in the file (names are case-sensitive). * Filters combine: a call that passes several parameters returns only the rows that match all of them. Common patterns, each added to `run` in `db_info.py` above: ```python # Parameters region: Annotated[Optional[str], "Region filter, e.g. 'US' or 'EU' (case-insensitive)."] = None, description_contains: Annotated[Optional[str], "Text to look for in the description, e.g. 'futures'."] = None, min_retention_days: Annotated[Optional[int], "Only databases that keep at least this many days of data."] = None, # Exact match, ignoring case if region: df = df[df["REGION"].str.upper() == region.strip().upper()] # Text contained anywhere in a column, ignoring case if description_contains: df = df[df["DESCRIPTION"].str.contains(description_contains, case=False, regex=False)] # Numeric comparison: the file is read as text (dtype=str), so convert the column first if min_retention_days is not None: df = df[df["RETENTION_DAYS"].astype(int) >= min_retention_days] # Return only some columns (by default every column in the file is returned) return df[["DB_NAME", "OWNER", "REGION", "RETENTION_DAYS"]] ``` For example, `region="eu"` with `min_retention_days=3000` returns only `LSE`. If the file has no column with a name the tool uses, the call fails with an error that names the column, for example `Error running db_info: 'REGION'`, instead of returning wrong rows. ## Replacing a bundled tool The shipped tools — including `search_symbol_universe`, the symbology tool — are bundled custom tools. A bundled tool’s query cannot be edited in place, and there is no setting that points it at a different query file. To run your own version, **add a new custom tool with a different name and turn the bundled one off**: 1. **Write a tool file** with its own `TOOL_NAME` — see `Example: a custom symbology tool` below. A custom tool that reuses a bundled name (for example `search_symbol_universe`) is rejected at startup as a duplicate. 2. **Register the file** with `CUSTOM_TOOLS` in your `.env`: ``` CUSTOM_TOOLS='[{"path": "/opt/onetick/tools/venue_instruments.py"}]' ``` 3. **Turn the bundled tool off.** `ONETICK_DB_TOOLS` is an allow-list: once it is set, only the tools it names are served. List your tool plus every other tool you want to keep, and leave `search_symbol_universe` out. To keep all the other bundled tools (see `Tools` for the full list): ``` ONETICK_DB_TOOLS=venue_instruments,search_cloud_coverage,search_python-docs,search_python-examples,search_sql-docs,list_products,list_continuous_contracts,db_load_availability,futures_holiday_calendar,futures_trading_hours,list_databases,db_field_descriptions,db_field_enumerations,db_tables,db_table_schemas,calendar_holidays,trading_hours ``` 4. **Restart the server.** An unknown name in `ONETICK_DB_TOOLS` or a bad tool file stops it at startup with a clear message, so typos show up immediately. #### NOTE In `ONETICK_DB_TOOLS` always use the bare `TOOL_NAME` (`venue_instruments`). MCP clients may display the tool with a bundle prefix, for example `onetick_venue_instruments`. #### NOTE **Migrating from** `OTP_SYMBOL_UNIVERSE_QUERY_PATH`. Earlier versions replaced the symbology query by pointing the `OTP_SYMBOL_UNIVERSE_QUERY_PATH` environment variable at a Python file (the former *Programmable Queries* page). That setting is no longer read, so setting it has no effect. Move your query into a custom tool file as described above. ### Example: a custom symbology tool This tool lists the instruments traded on one venue, read from the `SYMBOL_UNIVERSE` database. It is a complete tool file: the docstring is the description the model sees, and each input is described with a plain string in `Annotated[...]`. ```python # /opt/onetick/tools/venue_instruments.py from datetime import date, timedelta from typing import Annotated, Optional import onetick.py as otp import pandas as pd TOOL_NAME = "venue_instruments" def run( mic: Annotated[str, "Market Identifier Code of the venue, e.g. 'XNYS' or 'XLON' (case-insensitive)."], sec_type: Annotated[Optional[str], "Security type filter, e.g. 'Equity' or 'ETF'. Omit for all types."] = "Equity", limit: Annotated[int, "Maximum number of instruments to return."] = 25, ) -> pd.DataFrame: """List instruments traded on one venue, from the OneTick SYMBOL_UNIVERSE. Use for questions like "which equities trade on XLON?" or "show some ETFs listed on XNYS". Returns one row per instrument with its database, symbol, currency, ISIN and MIC. """ mic = mic.strip().upper() # MICs are stored in upper case, so 'xlon' would match nothing day = date.today() - timedelta(days=1) while day.weekday() >= 5: # SYMBOL_UNIVERSE is a daily snapshot: use the last weekday day -= timedelta(days=1) data = otp.DataSource(db="SYMBOL_UNIVERSE", tick_type="STAT", schema_policy="manual") data = data.where(otp.Column("MIC", str) == mic) if sec_type: data = data.where(otp.Column("SEC_TYPE", str) == sec_type) symbols = otp.Symbols(db="SYMBOL_UNIVERSE", for_tick_type="STAT") source = otp.merge([data], symbols=symbols, identify_input_ts=True) df = otp.run( source.first(max(1, int(limit))), start=otp.dt(day), end=otp.dt(day + timedelta(days=1)), output_structure="df", ) keep = [c for c in ("DB_NAME", "DB_SYMBOL", "SEC_TYPE", "CURRENCY", "ISIN", "MIC") if c in df.columns] return df[keep] ``` With the `.env` settings from the steps above, the model can answer questions such as “which equities trade on XLON?” by calling `venue_instruments` with `mic="XLON"`. ## Trust and OneTick access Operator tool files are scanned with an AST allow-list before loading — a guardrail against accidents, **not** a security sandbox (the file is operator-owned config-as-code, the same trust level as your `.env` or the wheel). Allowed import roots: `onetick`, `datetime`, `typing`, `math`, `pandas`. Banned: `open`, `exec`, `eval`, `compile`, `__import__`, `input`, `breakpoint`, and dunder attribute access. A tool that runs a OneTick query gets the server’s configured authentication applied automatically (see `OneTick WebAPI authentication`). ### Custom tools and OneTick credentials The server treats every custom tool as a OneTick query tool, including one that only reads a file or computes. Before it serves any custom tool, it checks that the credentials for `ONETICK_DB_OUTBOUND_STRATEGY` (default `service_account`) are set: * If they are, custom tools are served normally. * If they are not, the server logs `OneTick connectivity check: FAILED - queries unavailable` and does not serve any custom tool. Any other enabled tools, such as the reference-data tools, are still served. If only custom tools are enabled, the server exits at startup with `no tool is servable`. For a deployment that runs no OneTick queries — only file-based custom tools, the reference-data tools or the search tools — set: ``` ONETICK_DB_OUTBOUND_STRATEGY=none ``` Then no credentials are needed. Do not use `none` if the server also serves tools that query a OneTick server which requires authentication: their calls are sent without credentials and fail.