Tool Runner

When the LLM asks for a tool, the tool's code in the app checks the permissions and the cache. On a cache miss it resolves the call, decrypting the credential from its Smarter Secret, into a ToolCall of plain values. The tool runner, from get_tool_runner(), finds the executor of the call's kind in TOOL_EXECUTORS: execute_mcp_call for MCP clients, execute_api_call for API plugins, execute_sql_call for SQL plugins, through an SSH tunnel when the connection uses one, execute_extension_call for Extensions, whose code gets its settings, switches and caller as plain values, execute_http_call for the web search apis, the Brave image search, the checks of each image's url and websites' robots.txt, and execute_webfetch_call for the pages that the web search plugin reads, with its domain policy and robots.txt checked again on each redirect. The executor reads neither the app's database nor a Secret, and calls the MCP server, the api, the SqlConnection's database, the search api or the website. Its ToolCallResult returns to the tool's code in the app, which sends the signals, caches the result and gives it to the LLM. The in-process runner executes the call in the app's process. The remote runner sends it as JSON through Redis to the tool worker, smarter-worker-tools, which has no database, no Secret and no cloud credential, runs the same executor there, and returns the result through Redis.

Every LLM tool call is resolved in the app into a serializable call, with the credentials it needs, and executed by the tool runner: in the app’s own process, or in the tool worker, a Celery worker that holds no credential of the platform’s (ADR-038).

The tool’s own code stays in the app, around the runner: it checks the permissions and the cache, resolves the call only when the cache misses, so that a credential is read only for a call that runs, and, from the result, sends the signals, stores the result in the cache and answers the LLM. The executor of each kind of call, registered in TOOL_EXECUTORS, reads no database and no Smarter Secret. These go through it:

  • MCP clients, with smarter.apps.mcpclient.execution;

  • API plugins, with smarter.apps.connection.execution;

  • SQL plugins, with smarter.apps.connection.execution, through an SSH tunnel (smarter.apps.connection.ssh) for a connection that uses one;

  • Extensions, with smarter.apps.llmtool.extension.execution. Their code is a third party’s, so its context holds plain values decided before the call: its settings, its switches, and who called it, as an ExtensionCaller. The executor loads an Extension’s code, its archive, by its sha256, from the cache, where the app publishes it for the remote runner, or else from the database, the first time a process runs a version;

  • the WebsearchPlugin’s search apis (Brave, Tavily), the ImageSearchPlugin’s Brave image search and its checks of each image’s url, and every website’s robots.txt, with smarter.apps.llmtool.runner.http. Its fetch_with_runner() takes the place of safe_http.fetch(), so each of them changed by one line;

  • the WebsearchPlugin’s fetch of a page, with WebFetchToolCall and execute_webfetch_call() in smarter.apps.llmtool.plugin.websearch_fetch. fetch’s redirect_policy is a function, which can’t travel with a call, so the call carries what it decides on, the domain policy and whether to obey robots.txt, and the executor builds the function where the call runs.

Choosing the runner

SMARTER_APP_LLMTOOL_TOOL_RUNNER chooses the runner that get_tool_runner() returns:

in_process, the default

InProcessToolRunner executes each call in the process that resolved it: the app, or the Celery worker that runs an orchestration.

remote

RemoteToolRunner sends each call, as JSON, in the Celery task run_tool_call (smarter.apps.llmtool.tasks), on the queue SMARTER_APP_TOOLS_TASKS_CELERY_TASK_QUEUE (tools_celery_task_queue), and waits for its result in the result backend, the broker’s Redis. The tool worker rebuilds the call with its kind’s model, registered in TOOL_CALL_MODELS, runs it in process, and returns its result. The app waits four times the call’s timeout, plus 15 seconds, and at most 10 minutes; a worker that doesn’t answer in that time, or a task that fails, is a failure for the LLM, as any call that couldn’t be made is.

The tool worker, smarter-worker-tools, runs with SMARTER_DATABASE_UNAVAILABLE=true: it never opens a database connection, reads every waffle switch as off, and starts without the Django secret key. It takes nothing from the platform but the broker’s and the cache’s url: each call brings what it needs. It runs without task events (no -E), which would copy each call’s arguments, and its credentials, to Celery’s events stream. make run starts one, which takes calls only when the app’s SMARTER_APP_LLMTOOL_TOOL_RUNNER is remote. On Kubernetes, the Helm chart’s workerTools.enabled deploys it and makes the app’s runner remote: see The Tool Worker.

A safe HTTP request, executed by the tool runner: the http kind of tool call.

Several tools make one request to a url with smarter.apps.llmtool.plugin.safe_http.fetch(), often with an api key in a header: the WebsearchPlugin’s search apis (Brave, Tavily), and the ImageSearchPlugin’s Brave image search and its checks of each image’s url. fetch_with_runner() takes the place of fetch for them. It resolves the request into an HttpToolCall, which the tool runner executes with execute_http_call(), and turns the result back into a SafeResponse, or raises SafeHttpError, as fetch does. The caller is unchanged, and the request can run in a worker without credentials (ADR-038).

fetch’s redirect_policy, a function, can’t travel with a call, so a request that needs one, such as the WebsearchPlugin’s fetch of a page, isn’t an http call.

Nothing here logs or reads the database: the ImageSearchPlugin checks image urls in worker threads, where either would open a database connection per thread.

smarter.apps.llmtool.runner.http.HTTP_TOOL_CALL_KIND: Final = 'http'

The kind of a safe HTTP request, which selects execute_http_call().

class smarter.apps.llmtool.runner.http.HttpToolCall(**data)[source]

Bases: ToolCall

A safe HTTP request, resolved for execution: the arguments of fetch().

Warning

headers may hold an api key. It is excluded from repr(). Never log the call’s model_dump().

accept_status: tuple[int, ...]
headers: dict[str, str]
json_body: JsonValue
kind: Literal['http']
max_bytes: int
max_redirects: int
method: str
model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

params: dict[str, JsonValue] | None
permit_local_loopback: bool
require_https: bool
timeout: float
url: str
smarter.apps.llmtool.runner.http.execute_http_call(call)[source]

Execute a resolved safe HTTP request.

Parameters:

call (ToolCall) – The call, an HttpToolCall.

Return type:

ToolCallResult

Returns:

The response, from response_to_value(), with its status code; or a result with a failure, and the status code if the server answered, when fetch raises.

Raises:

TypeError – If the call isn’t an HttpToolCall.

smarter.apps.llmtool.runner.http.fetch_with_runner(url, *, method='GET', headers=None, params=None, json_body=None, timeout=15, max_bytes=2000000, max_redirects=3, accept_status=(200,), require_https=True, permit_local_loopback=False)[source]

Make a safe HTTP request through the tool runner: fetch(), as an HttpToolCall.

Its arguments are fetch’s, but for redirect_policy, which can’t travel with a call.

Return type:

SafeResponse

Returns:

The response.

Raises:

SafeHttpError – As fetch does: if a url is not permitted, the request fails or times out, the response status is not accepted, or the response is too large.

smarter.apps.llmtool.runner.http.response_to_value(response)[source]

Return a response as JSON: its url, headers and redirects, and its body in base64, so that any bytes survive.

Parameters:

response (SafeResponse) – The response.

Return type:

dict[str, Any]

Returns:

The JSON value of a ToolCallResult.

smarter.apps.llmtool.runner.http.value_to_response(value, status_code)[source]

Return the response that response_to_value() turned into JSON.

Parameters:
  • value (TypeAliasType) – The result’s value.

  • status_code (int) – The result’s status code.

Return type:

SafeResponse

Returns:

The response.

Raises:

SafeHttpError – If the value isn’t a response.

The call and result models of smarter.apps.llmtool.runner.

A tool call is resolved in the app, where the database and the Smarter Secrets are, into a ToolCall: plain values, with every credential the call needs already decrypted, and nothing that needs a database connection. A ToolRunner executes it and returns a ToolCallResult. Both are Pydantic models, so that a call can be sent to, and its result returned from, a worker that holds no credentials of its own (see ADR-038).

Warning

A resolved call holds credentials. Never log it, or its model_dump(). Fields that hold credentials are excluded from repr(), as a guard against an accidental log line.

class smarter.apps.llmtool.runner.models.ToolCall(**data)[source]

Bases: BaseModel

A tool call, resolved for execution.

Each kind of tool subclasses it, with a kind of its own, and registers the function that executes it in smarter.apps.llmtool.runner.runner.TOOL_EXECUTORS.

Variables:

kind – The kind of tool, e.g. mcp. It selects the executor.

kind: str
model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class smarter.apps.llmtool.runner.models.ToolCallLabel(**data)[source]

Bases: BaseModel

What a tool call is for, so that the tool worker’s log can say so.

The app sets it around each tool call that the LLM makes (labeled_tool_calls()), and the remote runner sends it to the tool worker beside the call. It holds names and ids only, never a credential, an argument or a result: it is logged as is.

Variables:
  • tool – The tool’s name, as users know it, e.g. a plugin’s or an MCP tool’s name.

  • llmclient – The LLMClient that the call is made for, as <name> (<id>), or None.

  • session – The chat session’s key, masked, or None.

  • request_id – The id of the request that made the call, or None.

describe()[source]

Describe the label for a log line.

Return type:

str

Returns:

e.g. tool=stackademy_sql llmclient=stackademy (12) session=****a1b2c3 request=r-123, with - for what isn’t known.

llmclient: str | None
model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

request_id: str | None
session: str | None
tool: str | None
class smarter.apps.llmtool.runner.models.ToolCallResult(**data)[source]

Bases: BaseModel

The result of a tool call.

A call has one of three outcomes:

  • it succeeded: value is its result, and is_error is False;

  • the tool answered with an error of its own, e.g. an MCP tool’s isError: value describes it, and is_error is True;

  • it couldn’t be made: refused, unreachable, timed out or misconfigured. failure describes why, and value is None.

An HTTP tool, e.g. an ApiPlugin’s api, also reports the response’s status_code, so that the app can tell a rejected credential (401, 403) from any other failure.

Variables:
  • value – The tool’s result, as JSON.

  • is_error – Whether the tool answered with an error of its own.

  • failure – Why the call couldn’t be made, or None.

  • status_code – The HTTP status of an HTTP tool’s response, or None when there was none.

failure: str | None
is_error: bool
model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

status_code: int | None
value: JsonValue

The tool runner: where a resolved tool call is executed.

get_tool_runner() returns the runner that every tool call goes through, as the setting app_llmtool_tool_runner (SMARTER_APP_LLMTOOL_TOOL_RUNNER) chooses:

  • InProcessToolRunner, the default, executes the call in the app’s own process.

  • RemoteToolRunner sends it, as JSON, to the tool worker, smarter-worker-tools, through the Celery queue app_tools_tasks_celery_task_queue, and waits for its result. The worker holds no database, no Smarter Secret and no cloud credential: each call brings what it needs (ADR-038).

The code that resolves a call is the same either way. Each kind of tool registers its executor in TOOL_EXECUTORS, and its call’s model in TOOL_CALL_MODELS, by dotted path. A path, rather than an import, keeps this module free of the apps that it runs tools for, several of which import from smarter.apps.llmtool.

Inside the tool worker, every call runs in process, whatever the setting says: an executor that uses the runner itself, e.g. the web search page fetch’s robots.txt, must not send its call back to the queue that it is serving (running_in_tool_worker()).

class smarter.apps.llmtool.runner.runner.InProcessToolRunner[source]

Bases: ToolRunner

Executes each call in this process, with the executor that its kind registered.

run(call)[source]

Execute a resolved tool call in this process.

Parameters:

call (ToolCall) – The call.

Return type:

ToolCallResult

Returns:

The executor’s result.

Raises:

SmarterConfigurationError – If no executor is registered for the call’s kind.

smarter.apps.llmtool.runner.runner.MAX_REMOTE_TIMEOUT_SECONDS = 600.0

The longest that the remote runner waits for a result.

class smarter.apps.llmtool.runner.runner.RemoteToolRunner[source]

Bases: ToolRunner

Sends each call to the tool worker, smarter-worker-tools, and waits for its result.

The call travels as JSON, in a Celery task on the queue app_tools_tasks_celery_task_queue, and its result comes back through the result backend, the broker’s Redis. A worker that doesn’t answer in time, or a task that fails, is a result with a failure, as any call that couldn’t be made is.

Warning

The task’s arguments hold the call’s credentials, in Redis, until the worker takes the task. Smarter’s Celery app sends messages with protocol 1, which has no argsrepr header, and its worker logs a task’s name and id, not its arguments. The tool worker runs without task events (-E), so that they don’t reach an events stream either.

run(call)[source]

Execute a resolved tool call in the tool worker.

Parameters:

call (ToolCall) – The call.

Return type:

ToolCallResult

Returns:

The worker’s result, or a result with a failure if the worker doesn’t answer in time, or the task fails.

smarter.apps.llmtool.runner.runner.TOOL_CALL_MODELS: dict[str, str] = {'api': 'smarter.apps.connection.execution.ApiToolCall', 'extension': 'smarter.apps.llmtool.extension.execution.ExtensionToolCall', 'http': 'smarter.apps.llmtool.runner.http.HttpToolCall', 'mcp': 'smarter.apps.mcpclient.execution.MCPToolCall', 'sql': 'smarter.apps.connection.execution.SqlToolCall', 'webfetch': 'smarter.apps.llmtool.plugin.websearch_fetch.WebFetchToolCall'}

Each kind of tool call, and the dotted path of its model, which rebuilds a call from its JSON in the tool worker.

{
    'api': 'smarter.apps.connection.execution.ApiToolCall',
    'extension': 'smarter.apps.llmtool.extension.execution.ExtensionToolCall',
    'http': 'smarter.apps.llmtool.runner.http.HttpToolCall',
    'mcp': 'smarter.apps.mcpclient.execution.MCPToolCall',
    'sql': 'smarter.apps.connection.execution.SqlToolCall',
    'webfetch': 'smarter.apps.llmtool.plugin.websearch_fetch.WebFetchToolCall',
}
smarter.apps.llmtool.runner.runner.TOOL_EXECUTORS: dict[str, str] = {'api': 'smarter.apps.connection.execution.execute_api_call', 'extension': 'smarter.apps.llmtool.extension.execution.execute_extension_call', 'http': 'smarter.apps.llmtool.runner.http.execute_http_call', 'mcp': 'smarter.apps.mcpclient.execution.execute_mcp_call', 'sql': 'smarter.apps.connection.execution.execute_sql_call', 'webfetch': 'smarter.apps.llmtool.plugin.websearch_fetch.execute_webfetch_call'}

Each kind of ToolCall, and the dotted path of its executor.

{
    'api': 'smarter.apps.connection.execution.execute_api_call',
    'extension': 'smarter.apps.llmtool.extension.execution.execute_extension_call',
    'http': 'smarter.apps.llmtool.runner.http.execute_http_call',
    'mcp': 'smarter.apps.mcpclient.execution.execute_mcp_call',
    'sql': 'smarter.apps.connection.execution.execute_sql_call',
    'webfetch': 'smarter.apps.llmtool.plugin.websearch_fetch.execute_webfetch_call',
}
smarter.apps.llmtool.runner.runner.ToolExecutor

A function that executes one kind of resolved tool call, and returns its result.

alias of Callable[[ToolCall], ToolCallResult]

class smarter.apps.llmtool.runner.runner.ToolRunner[source]

Bases: ABC

Executes resolved tool calls.

abstractmethod run(call)[source]

Execute a resolved tool call.

Parameters:

call (ToolCall) – The call, with everything it needs already resolved.

Return type:

ToolCallResult

Returns:

The result. A call that couldn’t be made is a result with a failure, not an exception.

smarter.apps.llmtool.runner.runner.call_model_for(kind)[source]

Return the model of a kind of tool call.

Parameters:

kind (str) – The call’s kind.

Return type:

type[ToolCall]

Returns:

The model, a subclass of ToolCall.

Raises:

SmarterConfigurationError – If no model is registered for the kind.

smarter.apps.llmtool.runner.runner.call_timeout(call)[source]

Return the timeout that a call names, its own or its MCP endpoint’s.

Parameters:

call (ToolCall) – The call.

Return type:

float

Returns:

Seconds, or DEFAULT_CALL_TIMEOUT_SECONDS if it names none.

smarter.apps.llmtool.runner.runner.carry_tool_call_label(function)[source]

Return a function that runs function with the current tool call label.

A thread doesn’t inherit the context variables of the code that starts it, so a call made from a thread pool, e.g. an ImageSearchPlugin’s validation of image urls, would lose its label.

Parameters:

function (Callable[[ParamSpec(P)], TypeVar(R)]) – The function that a thread runs.

Return type:

Callable[[ParamSpec(P)], TypeVar(R)]

Returns:

The function, wrapped.

smarter.apps.llmtool.runner.runner.current_tool_call_label()[source]

Return the label that labeled_tool_calls() set, if any.

Return type:

ToolCallLabel | None

Returns:

The label, or None.

smarter.apps.llmtool.runner.runner.describe_remote_failure(error, timeout)[source]

Describe, for the LLM, why the tool worker didn’t return a call’s result.

Parameters:
  • error (Exception) – What the wait raised.

  • timeout (float) – Seconds that the runner waited.

Return type:

str

Returns:

The description.

smarter.apps.llmtool.runner.runner.executor_for(kind)[source]

Return the executor of a kind of tool call.

Parameters:

kind (str) – The call’s kind.

Return type:

Callable[[ToolCall], ToolCallResult]

Returns:

The executor.

Raises:

SmarterConfigurationError – If no executor is registered for the kind.

smarter.apps.llmtool.runner.runner.get_tool_runner()[source]

Return the runner that tool calls go through.

Return type:

ToolRunner

Returns:

RemoteToolRunner when app_llmtool_tool_runner is remote, outside the tool worker; otherwise InProcessToolRunner.

smarter.apps.llmtool.runner.runner.labeled_tool_calls(label)[source]

Label every tool call made inside the with block, so that the tool worker’s log says what it was for.

The chat provider sets it around each tool call that the LLM makes (OpenAICompatibleChatProvider.process_tool_call()). A call made without one is logged without it.

Parameters:

label (ToolCallLabel) – The label, names and ids only.

Return type:

Iterator[None]

smarter.apps.llmtool.runner.runner.remote_timeout(call)[source]

Return how long the remote runner waits for a call’s result.

Parameters:

call (ToolCall) – The call.

Return type:

float

Returns:

Seconds: the call’s timeout times REMOTE_TIMEOUT_FACTOR, plus REMOTE_TIMEOUT_MARGIN_SECONDS, at most MAX_REMOTE_TIMEOUT_SECONDS.

smarter.apps.llmtool.runner.runner.running_in_tool_worker()[source]

Mark the code inside the with block as running in the tool worker, so that get_tool_runner() runs its calls in process.

The tool worker’s task, smarter.apps.llmtool.tasks.run_tool_call(), runs each call inside it.

Return type:

Iterator[None]