Skip to content

Chain Tools

A chain tool packs a whole ReasoningChain into a callable tool. The parent chain stores it in its top-level chain_tools field; at run time it is registered under its own name, so a tool step, an agent step or a map step can call it like any function.

Use it to reuse a tested sub-chain with a strict contract: typed input, typed output, its own budget, and no access to the parent’s state. To run a sub-chain that shares the parent’s memory, use handoff instead.

from mmar_carl import (
ChainToolDefinition, ReasoningChain, ToolStepConfig, ToolStepDescription,
)
child = ReasoningChain(steps=[
ToolStepDescription(
number=1,
title="Normalize text",
config=ToolStepConfig(tool_name="normalize",
input_mapping={"payload": "$outer_context"}),
),
])
normalizer = ChainToolDefinition.from_chain(
name="normalize_with_chain",
description="Run the pinned normalizer chain.",
chain=child,
input_schema={
"type": "object",
"properties": {"text": {"type": "string"}},
"required": ["text"],
"additionalProperties": False,
},
output_schema={
"type": "object",
"properties": {"normalized": {"type": "string"}},
"required": ["normalized"],
"additionalProperties": False,
},
output_reference="$steps.1.result_data",
allowed_tools=["normalize"], # host tools the child may use
timeout_seconds=5,
)

from_chain freezes the child through chain.to_dict(). Later edits to child do not change the tool.

parent = ReasoningChain(
steps=[
ToolStepDescription(
number=1,
title="Invoke child chain",
config=ToolStepConfig(tool_name="normalize_with_chain",
input_mapping={"text": "$outer_context"}),
),
],
chain_tools=[normalizer],
)
context = ReasoningContext(outer_context=" CARL Composition ", api=client)
context.register_tool("normalize", normalize) # every allowed_tools entry must exist
result = await parent.execute_async(context)
outcome = ChainToolOutcome.model_validate(result.step_results[0].result_data)
if outcome.success:
print(outcome.output) # {'normalized': 'carl composition'}
else:
print(outcome.status, outcome.error_code, outcome.error_message)

With ChainBuilder, add definitions with .add_chain_tool(definition). To register a definition on a context directly, call context.register_chain_tool(definition); re-registering the same contract is a no-op, and a name clash with a different tool raises unless replace=True.

The model is frozen and rejects unknown fields.

FieldTypeDefaultPurpose
namestrrequiredTool name: letter or _ first, then letters, digits, _, -; ≤ 64 chars. finish is reserved.
descriptionstrrequired≤ 2000 chars, non-blank.
chain_snapshotdictrequiredA complete ReasoningChain.to_dict() payload (format_version and steps required).
snapshot_sha256strcomputedSHA-256 of the canonical snapshot JSON. If you pass one, it must match.
input_schemadictrequiredSchema for the keyword arguments. Must be type: object.
output_schemadictrequiredSchema for the value read from the child after it finishes.
output_referencestrrequiredChild reference to read: $history…, $memory.…, $metadata.…, $steps.… or $outer_context….
allowed_toolslist[str][]Host tools copied into the child context. Unique names; a tool cannot list itself.
tagslist[str]["chain"]Tags of the registered tool (for allowed_tool_tags).
max_depthint4Nesting limit, 1–32.
timeout_secondsfloat120.0Budget for one invocation, finite, ≤ 86 400.
max_input_bytesint1000000Limit for the JSON-encoded arguments (≤ 16 MB).
max_output_bytesint1000000Limit for the JSON-encoded output (≤ 16 MB).
contract_version11Envelope version.

Both schemas use a small JSON Schema subset, checked when the definition is built: type (null, boolean, integer, number, string, array, object), properties, required, items, enum, and additionalProperties: false. Any other keyword is rejected.

The child gets a fresh context:

  • the validated arguments as JSON in outer_context, so $outer_context and $outer_context.<field> read them (they are also its runtime_input);
  • the parent’s LLM client, model, language, system prompt and retry settings;
  • only the host tools named in allowed_tools, and the chain tools embedded in its own snapshot;
  • empty memory and history.

It cannot read the parent’s history, memory, messages or metadata, and it does not inherit callbacks, the event bus, CommandPolicy, the network enforcer or other execution authority. Cancelling the parent cancels the child.

When the parent chain is built:

  • chain tool names must be unique;
  • a definition may not list a sibling chain tool in allowed_tools; nest it in the child’s own chain_tools instead;
  • every tool the child snapshot requires must be in allowed_tools.

When the parent runs, every allowed_tools entry must be registered on the context, or execution stops with Embedded chain tools require missing host tools: …. A name already taken by a different tool is an error.

Every call returns this envelope (as a dict in the tool step’s result_data, on success and on failure):

FieldMeaning
statuscompleted, failed, cancelled, timed_out, invalid_input, invalid_output, unavailable or recursion_limit.
successTrue only for completed.
outputThe schema-valid output; only on completed.
error_code, error_messageWhy it did not complete.
invocation_id, tool_name, depthIdentity of this call.
snapshot_sha256, input_sha256, output_sha256Provenance digests. output_sha256 only on completed.
duration_seconds, token_usage, executed_stepsCost of the call.
statusTypical error_code
invalid_inputinput_not_json, input_too_large, input_schema_mismatch
unavailablemissing_host_tools, invalid_chain_snapshot, snapshot_digest_mismatch
recursion_limitrecursion_limit (a cycle, or deeper than max_depth)
cancelledcancelled_by_host
timed_outchain_tool_timeout
failednested_chain_failed, nested_execution_exception
invalid_outputoutput_not_json, output_too_large, output_schema_mismatch

chain_tools is written by to_dict() and read back by from_dict(). Chain JSON older than the chain_tools field migrates with ReasoningChain.migrate(raw), which adds an empty list. A runtime that does not know the field rejects the chain with ChainFormatNewerError instead of silently dropping nested chains. See migration.