Tool-First Agent Environment Synthesis: A Practical Guide for Cross-Environment Tool-Use Agents

    This guide explains how to build training environments for tool-use agents by starting with tool execution closures instead of databases. It covers extracting tools from real execution trajectories, building a weighted tool graph with data and state dependencies, running state-aware random walks to sample cross-environment call chains, converting chains into tasks with replayable verification scripts, and handling cold-start limitations with practical troubleshooting tips.

    1. Start with the Tool Execution Closure, Not a Database

    When building training environments for tool-use agents, many teams instinctively start by creating a database. The order feels natural, but it caps the quality of everything that follows: tool interfaces, task difficulty, and verification scripts.

    A more reliable sequence is:

    • Inspect real execution trajectories first, then extract tools.
    • Define dependencies between tools before generating data that satisfies them.
    • Define state and side effects before writing tasks.
    • Build replayable verification before scaling up sample generation.

    There are three common failure modes:

    Defect Root cause Consequence How the tool-first approach helps
    Interface semantic drift Tool signatures are reverse-engineered from data tables without real call evidence Tools are callable, but parameter semantics are hollow; the model learns a fictitious schema mapping Extract tools from real trajectories, so each tool carries call counts and context evidence
    Combinations without execution basis Tool chaining relies on human experience rather than execution traces Call chains may be logically impossible or only work by accident Build a tool composition graph from trajectory co-occurrence and preconditions, with weighted edges and dependency types
    Single-environment lock-in All task information can be retrieved from the same data table Cannot train cross-system data movement, state handoff, or tool orchestration State-aware random walks prioritize cross-environment edges, making tasks naturally multi-domain

    FAQ

    What is tool-first environment synthesis?
    It treats the environment as “the closure of data, state, permissions, and side effects required for a set of tools to run,” rather than designing a static database first and then reverse-engineering tools.

    What goes wrong when you build the database first?
    Common problems include tool parameters with no real call traces, missing executable dependencies between tools, tasks that can only be completed within one database, and no way to simulate cross-system state transfer.

    How should edge weight thresholds be chosen?
    Do not hard-code a number. First compute the edge weight distribution, plot a histogram, inspect the proportion of low-weight edges, and manually sample low-frequency edges to see whether they represent stable call patterns. A threshold is only a filter for incidental co-occurrence, not a business rule itself.

    2. The Paradigm Shift: An Environment Is a Tool Execution Dependency Closure

    A tool-centric synthesis framework changes the modeling target from “business data” to “tools and their execution dependencies.” The database is not the starting point; it is an implementation detail of how tools land. The environment is the closure of data and state required for a set of tools to run.

    This perspective yields three direct benefits:

    1. Traceable tool interfaces: Every tool comes from a real trajectory, so you can see how many times it was called, in what context, which inputs it depends on, and which outputs it produces.
    2. Grounded tool composition: Edges between tools can be classified as data dependencies or state dependencies, annotated with weights, preconditions, and side effects.
    3. Naturally cross-environment tasks: If a call chain spans multiple environments such as orders, payments, inventory, and notifications, the task is no longer single-database question answering but cross-system orchestration.

    3. Stage 1: Extract Tools from Trajectories and Build the Tool Graph

    3.1 Trajectory Input Contract

    The input to the tool composition graph should not be abstract “logs” but structured trajectory records. A minimal usable trajectory contains at least the following fields:

    1. {
    2. "trajectory_id": "traj_001",
    3. "started_at": "2026-01-01T10:00:00Z",
    4. "env": "erp",
    5. "calls": [
    6. {
    7. "step": 1,
    8. "tool": "create_order",
    9. "args": {
    10. "customer_id": "C001",
    11. "sku": "SKU-88"
    12. },
    13. "outputs": {
    14. "order_id": "ORD-001",
    15. "status": "created"
    16. },
    17. "status": "success",
    18. "failed": false,
    19. "error": null,
    20. "latency_ms": 120,
    21. "idempotency_key": "idem-001"
    22. }
    23. ]
    24. }

    When building the main graph, prioritize successful calls:

    1. Valid call = status is success, failed is false, and error is empty.
    2. Failed calls can be used to analyze retries, rollbacks, and exception recovery, but should not serve directly as evidence for main dependency edges.

    3.2 Edge Weight Definition

    Nodes in the tool composition graph are tools; edges represent dependencies between tools. Edges should distinguish at least two types:

    • Data dependency: Input fields required by the downstream tool come from the upstream tool’s outputs.
    • State dependency: The downstream tool’s preconditions depend on side effects produced by the upstream tool, for example, an order must be created before payment.

    Edge weight is best defined as a conditional transition probability:

    1. P(v | u) = count(u -> v) / count(u -> *)

    Here, count(u -> v) is the number of times tool v immediately follows a successful call to tool u in real trajectories; count(u -> *) is the total number of successful next hops after tool u succeeds, i.e., the sum of all outgoing edge counts.

    Note that count(u -> *) is not the total number of times tool u appears, but the sum of counts over all successor edges where u is the upstream node. If u is the last step in a trajectory, it should not contribute to the denominator.

    3.3 Tool Graph Pseudocode

    1. from collections import defaultdict, Counter
    2. def valid_call(call):
    3. return (
    4. call.get("status") == "success"
    5. and not call.get("failed")
    6. and not call.get("error")
    7. )
    8. def build_tool_graph(trajectories, min_weight=0.02):
    9. counts = defaultdict(Counter) # counts[u][v] = count(u -> v)
    10. data_links = defaultdict(set) # (u, v) -> shared fields
    11. state_links = defaultdict(set) # (u, v) -> state dependencies
    12. for traj in trajectories:
    13. calls = [c for c in traj.get("calls", []) if valid_call(c)]
    14. for i in range(len(calls) - 1):
    15. u = calls[i]
    16. v = calls[i + 1]
    17. u_tool = u["tool"]
    18. v_tool = v["tool"]
    19. counts[u_tool][v_tool] += 1
    20. u_outputs = set(u.get("outputs", {}).keys())
    21. v_inputs = set(v.get("required_inputs", []))
    22. shared = u_outputs & v_inputs
    23. if shared:
    24. data_links[(u_tool, v_tool)].update(shared)
    25. if u.get("has_side_effect") and v.get("needs_state"):
    26. state_links[(u_tool, v_tool)].add(v.get("needs_state"))
    27. graph = {}
    28. for u_tool, next_tools in counts.items():
    29. denom = sum(next_tools.values()) # count(u -> *)
    30. if denom == 0:
    31. continue
    32. for v_tool, cnt in next_tools.items():
    33. weight = cnt / denom
    34. if weight < min_weight:
    35. continue
    36. graph.setdefault(u_tool, {})[v_tool] = {
    37. "weight": weight,
    38. "count": cnt,
    39. "denom": denom,
    40. "data_link": sorted(data_links.get((u_tool, v_tool), set())),
    41. "state_link": sorted(state_links.get((u_tool, v_tool), set()))
    42. }
    43. return graph

    Threshold recommendations:

    1. First output a histogram of all weights.
    2. Inspect the low-weight range, such as the 10th, 20th, and 30th percentiles.
    3. Manually sample low-frequency edges to decide whether they are incidental co-occurrences or stable but low-frequency business paths.
    4. When trajectories are few and tools are many, raise the threshold to avoid incidental co-occurrence polluting the graph structure.
    5. When trajectories are abundant and coverage matters, lower the threshold to retain long-tail paths.
    6. Use one consistent edge weight definition throughout; do not mix conditional transition probability and raw frequency.

    4. Stage 2: State-Aware Random Walk

    4.1 State Data Contract

    When sampling call chains on the tool composition graph, transition probability alone is not enough; you must maintain a virtual state. The state includes at least the environment, entities, variables, historical side effects, and a random seed.

    1. {
    2. "root_env": "erp",
    3. "envs": {
    4. "erp": {
    5. "entity": {
    6. "order": {
    7. "order_id": "ORD-001",
    8. "status": "created"
    9. }
    10. },
    11. "vars": {}
    12. },
    13. "crm": {
    14. "entity": {
    15. "lead": {
    16. "lead_id": "LEAD-001",
    17. "notes": []
    18. }
    19. },
    20. "vars": {}
    21. }
    22. },
    23. "created_entities": [
    24. "erp.order:ORD-001"
    25. ],
    26. "side_effects": [
    27. {
    28. "env": "erp",
    29. "entity": "order",
    30. "field": "status",
    31. "value": "created"
    32. }
    33. ],
    34. "random_seed": 42
    35. }

    4.2 Edge Preconditions and Side Effects

    Every candidate edge should carry executable preconditions and side effects, not just an abstract “state-related” label.

    1. {
    2. "from": "create_order",
    3. "to": "charge_payment",
    4. "weight": 0.35,
    5. "preconditions": [
    6. {
    7. "type": "data",
    8. "path": "erp.order.order_id",
    9. "not_empty": true
    10. },
    11. {
    12. "type": "state",
    13. "env": "erp",
    14. "entity": "order",
    15. "field": "status",
    16. "equals": "created"
    17. }
    18. ],
    19. "side_effects": [
    20. {
    21. "op": "set",
    22. "path": "billing.payment.status",
    23. "value": "paid"
    24. },
    25. {
    26. "op": "append",
    27. "path": "crm.order.notes",
    28. "value": "payment completed"
    29. }
    30. ]
    31. }

    4.3 Fallback Strategy When No Candidate Edge Exists

    During a state-aware random walk, the current node may have no candidate edge whose preconditions are satisfied. Do not force an edge. Handle it in this order:

    1. Generate a terminal-state sample: If the current chain already contains a clear goal, stop the walk and convert it into a shorter task.
    2. Look for a repair edge: Check whether a repair tool can fill in missing state or data, such as querying an order, adding a field, or retrying a payment.
    3. Backtrack to the nearest executable node: Remove the failed segment from the path and resample from an earlier stable state.
    4. Relax the cross-environment goal: If the goal is to cover three environments but only two are reachable, lower the sample’s difficulty label instead of fabricating a cross-environment edge.
    5. Escalate to a human rule base: If a certain state frequently deadlocks, the tool graph is missing a key node; add the tool or precondition manually.

    4.4 Walk Pseudocode

    1. def sample_chain(graph, state, max_len=12, target_envs=3):
    2. chain = []
    3. current = state["root_env"]
    4. visited_envs = {current}
    5. while len(chain) < max_len:
    6. candidates = []
    7. for next_tool, edge in graph.get(current, {}).items():
    8. if preconditions_ok(edge, state):
    9. candidates.append((next_tool, edge))
    10. if not candidates:
    11. return fallback_sample(graph, state, chain, target_envs)
    12. if len(visited_envs) < target_envs:
    13. candidates.sort(
    14. key=lambda item: item[1].get("crosses_env", False),
    15. reverse=True
    16. )
    17. next_tool, edge = weighted_sample(candidates)
    18. state = apply_side_effects(state, edge.get("side_effects", []))
    19. chain.append({
    20. "from": current,
    21. "to": next_tool,
    22. "edge": edge
    23. })
    24. current = next_tool
    25. visited_envs.add(current)
    26. return chain

    5. Stage 3: Convert Call Chains into Tasks and Verification Scripts

    5.1 Task Template

    Once a call chain is generated, it must be converted into a natural-language task that is trainable and evaluable. The task template should preserve four layers of information: intent, constraints, success criteria, and difficulty labels.

    1. {
    2. "task_id": "task_001",
    3. "intent": "Create an order for the customer and complete payment, while syncing the order status to CRM.",
    4. "constraints": [
    5. "The order must be created before payment is initiated.",
    6. "After successful payment, the order note in CRM must be updated.",
    7. "Directly modifying the payment status field is not allowed."
    8. ],
    9. "success_criteria": [
    10. "erp.order.status is paid.",
    11. "billing.payment.status is success.",
    12. "crm.order.notes contains payment completed."
    13. ],
    14. "difficulty": {
    15. "chain_length": 8,
    16. "cross_env_count": 3,
    17. "branch_count": 2,
    18. "requires_failure_recovery": false
    19. }
    20. }

    The same call chain can generate prompts at different abstraction levels: some instructions are explicit and suitable for cold start; others provide only the business goal and require the model to infer tool order, suitable for high-difficulty evaluation.

    5.2 Verification Script Generation Rules

    Verifiability takes priority over language fluency. A verification script should not only check the final answer, but also verify that each step satisfies its preconditions and that cross-environment entities remain consistent.

    Use the following assertion structure:

    1. {
    2. "verification": {
    3. "replay": {
    4. "enabled": true,
    5. "strict": true,
    6. "on_replay_failure": "reject"
    7. },
    8. "entity_mapping": [
    9. {
    10. "name": "order",
    11. "env": "erp",
    12. "id_path": "erp.order.order_id"
    13. },
    14. {
    15. "name": "payment",
    16. "env": "billing",
    17. "id_path": "billing.payment.payment_id"
    18. },
    19. {
    20. "name": "crm_note",
    21. "env": "crm",
    22. "id_path": "crm.order.notes"
    23. }
    24. ],
    25. "step_assertions": [
    26. {
    27. "step": 1,
    28. "type": "input_schema",
    29. "required": ["customer_id", "sku"]
    30. },
    31. {
    32. "step": 2,
    33. "type": "output_path",
    34. "path": "billing.payment.status",
    35. "equals": "success"
    36. },
    37. {
    38. "step": 3,
    39. "type": "uses_entity",
    40. "from": "order",
    41. "to": "payment"
    42. }
    43. ],
    44. "order_assertions": [
    45. {
    46. "after_step": 1,
    47. "before_step": 2,
    48. "depends_on": "create_order.success"
    49. }
    50. ],
    51. "final_assertions": [
    52. {
    53. "type": "state_path",
    54. "path": "erp.order.status",
    55. "equals": "paid"
    56. },
    57. {
    58. "type": "state_path",
    59. "path": "billing.payment.status",
    60. "equals": "success"
    61. },
    62. {
    63. "type": "cross_env_entity",
    64. "entity": "order",
    65. "env": "crm",
    66. "path": "crm.order.notes",
    67. "contains": "payment completed"
    68. }
    69. ]
    70. }
    71. }

    Verification scripts should cover at least:

    • Step-by-step assertions: Whether step i inputs satisfy the output contract of step i-1, and whether key fields are non-empty and correctly typed.
    • Terminal state assertions: Whether key fields in the final state are correctly modified.
    • Order assertions: Whether dependencies are satisfied beforehand, for example, the order must be created before payment.
    • Cross-environment consistency assertions: Whether the same entity is self-consistent across ERP, billing, CRM, and other environments.
    • Replay failure handling: Samples that cannot be replayed should not enter the training pool in principle; if repairable, log the difference, retry once, and reject if it still fails.

    6. Difficulty, Filtering, and Training/Evaluation Exits

    Difficulty can be characterized by a combination of metrics:

    • Chain length: number of call steps.
    • Cross-environment count: how many systems or tool domains are involved.
    • Branch count: whether there are conditional judgments, retries, or compensation paths.
    • Failure recovery requirement: whether recovery from an error state is needed.
    • Prompt explicitness: whether the user instruction is explicit or the steps must be inferred from the business goal.

    On the training side, synthesis output can produce both supervised fine-tuning trajectories and reinforcement learning environments. Environments need engineering packaging: running inside containers, state snapshots, task isolation, and controlled reset overhead; otherwise sampling throughput becomes the bottleneck.

    On the evaluation side, the same synthesis and filtering mechanism can construct higher-difficulty benchmarks: longer workflows, more cross-system state handoffs, and fewer explicit prompts. The value of such benchmarks lies in testing continuous execution ability rather than single-step tool selection.

    Regarding effect claims, adhere to the verifiability principle. If citing specific improvements, provide the public technical report name, link, sample size, and measurement method; when verification is impossible, remove specific numbers and say “improvements observed on some long-horizon benchmarks.” When comparing models, avoid vague claims that cannot be located; instead say “comparable to some strong baselines within the scope of verifiable reports.”

    7. Engineering Implementation and Troubleshooting Checklist

    Minimal Directory Template

    1. tool-first-env/
    2. ├── graphs/
    3. │ ├── tool_graph.json
    4. │ └── edge_weights.csv
    5. ├── trajectories/
    6. │ ├── raw/
    7. │ └── cleaned/
    8. ├── tasks/
    9. │ ├── templates/
    10. │ └── generated/
    11. ├── verifiers/
    12. │ ├── assertion_schema.json
    13. │ └── replay_logs/
    14. ├── sandbox/
    15. │ ├── snapshots/
    16. │ └── credentials/
    17. ├── scripts/
    18. │ ├── build_tool_graph.py
    19. │ ├── sample_chain.py
    20. │ └── verify_task.py
    21. └── configs/
    22. ├── deps.lock
    23. └── permissions.yaml

    Engineering Troubleshooting Table

    Problem Possible cause Check
    Walk deadlocks Current state satisfies no outgoing edge precondition Check state fields, whether side effects were written, and whether repair edges exist
    Cross-environment failure Entity ID not passed or environment binding missing Check entity_mapping, cross-environment assertions, and call parameter paths
    Assertion false positives Assertions too strict or hard-coded answers Sample assertions to see whether reasonable variants are allowed; keep golden samples for calibration
    Replay failure External dependencies nondeterministic or snapshots incomplete Check random seed, time, third-party responses, and state snapshots
    Sparse edge weights Insufficient trajectories or threshold too high Lower threshold, add manual trajectories, rebuild a weakly supervised graph
    Sample not trainable Verification script cannot cover the task goal Add terminal state, order, and cross-environment consistency assertions

    8. Limitations and Cold-Start Recommendations

    This approach depends heavily on trajectory coverage. In cold-start domains lacking real trajectories, tool graph edge weights are unreliable, and walks skew toward a few high-frequency transitions, producing a skewed difficulty distribution.

    Cold-start recommendations:

    • Start with 30 to 50 manual trajectories, prioritizing core business processes.
    • A weakly supervised tool graph can be assembled from tool documentation, interface definitions, and a small number of call logs, but should be labeled with low confidence.
    • Domain experts should focus on reviewing key edges, preconditions, and cross-environment entity mappings.
    • After tool version upgrades, interface field changes, or business rule adjustments, rebuild the tool graph and run regression checks on old samples.
    • Apply time decay to edge weights to prevent old trajectories from dominating the current distribution long-term.

    But the direction is clear: the environment is data, and tools are the index. When the organization of training environments shifts from “data tables” to “tool execution dependencies,” cross-environment long-horizon tasks can become a routine product that is synthesizable, verifiable, and replayable, rather than a few hard problems assembled manually.