Build a Tool Dependency Graph via Schema Matching

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Problem Statement

An orchestration engine wires API operations into multi-step pipelines by feeding fields returned by an upstream operation into parameters expected by a downstream operation. Given a list of tool definitions describing their input and output field schemas, construct the directed dependency graph across the catalog and identify unsatisfied mandatory inputs.

Each entry in tools is a dictionary with three keys:

  • "name": Unique string identifier of the tool.
  • "inputs": Dictionary mapping each raw input parameter name (str) to {"type": str, "required": bool}.
  • "outputs": Dictionary mapping each raw output field path (str) to {"type": str}.

Implement canonical_name(field: str) -> str and generate_dependency_graph(tools: List[dict]) -> dict according to the following rules:

  1. Canonical field key (canonical_name): Take the final segment after the last . (or the full string when no . is present), strip all _ and - characters, and lowercase the result. For instance, "billing.invoice_id", "Invoice-ID", and "invoiceId" all map to "invoiceid".
  2. Compatibility between two distinct tools: An output field of producer A satisfies an input parameter of consumer B if and only if A["name"] != B["name"], both fields have equal canonical_name strings, and their "type" strings are identical.
  3. Graph edges ("edges"): Whenever producer A supplies at least one compatible field (whether required is True or False) to consumer B, include one directed edge dictionary {"from_tool": str, "to_tool": str, "matches": [{"output_field": str, "input_field": str}]} preserving the raw un-normalized field names. Order "edges" lexicographically by from_tool, then to_tool. Order "matches" inside each edge lexicographically by input_field, breaking ties by output_field.
  4. Unsatisfied mandatory parameters ("unresolved_inputs"): Return a dictionary containing every tool's "name" mapped to a lexicographically sorted list of its "required": True input names that have zero compatible outputs among all other tools ([] if every mandatory parameter is covered or the tool has none). Optional parameters ("required": False) are never included here.

Examples

Example 1

Input:

tools = [
    {
        "name": "createInvoice",
        "inputs": {
            "account_code": {"type": "string", "required": True},
        },
        "outputs": {
            "billing.invoice_id": {"type": "integer"},
            "total_cents": {"type": "integer"},
        },
    },
    {
        "name": "chargeCard",
        "inputs": {
            "payment_method": {"type": "string", "required": True},
            "invoiceId": {"type": "integer", "required": False},
            "totalCents": {"type": "number", "required": True},
        },
        "outputs": {
            "receipt_url": {"type": "string"},
        },
    },
]

Output:

{
  "edges": [
    {
      "from_tool": "createInvoice",
      "to_tool": "chargeCard",
      "matches": [
        {"output_field": "billing.invoice_id", "input_field": "invoiceId"}
      ]
    }
  ],
  "unresolved_inputs": {
    "createInvoice": ["account_code"],
    "chargeCard": ["payment_method", "totalCents"]
  }
}

Explanation: "billing.invoice_id" and "invoiceId" both normalize to "invoiceid" with type "integer", creating a directed edge from "createInvoice" to "chargeCard" even though "invoiceId" is optional. Meanwhile, "total_cents" ("integer") does not match "totalCents" ("number") because type strings must match strictly, leaving "payment_method" and "totalCents" unresolved on "chargeCard".

Example 2

Input:

tools = [
    {
        "name": "rotateSecret",
        "inputs": {
            "auth-token": {"type": "string", "required": True},
            "vault_key": {"type": "string", "required": True},
        },
        "outputs": {
            "vault_key": {"type": "string"},
        },
    },
    {
        "name": "openSession",
        "inputs": {},
        "outputs": {
            "session.Auth_Token": {"type": "string"},
        },
    },
]

Output:

{
  "edges": [
    {
      "from_tool": "openSession",
      "to_tool": "rotateSecret",
      "matches": [
        {"output_field": "session.Auth_Token", "input_field": "auth-token"}
      ]
    }
  ],
  "unresolved_inputs": {
    "rotateSecret": ["vault_key"],
    "openSession": []
  }
}

Explanation: "openSession" supplies "session.Auth_Token" to "rotateSecret"'s "auth-token" (both canonicalize to "authtoken" with type "string"). Because a tool cannot satisfy its own inputs, "rotateSecret"'s own "vault_key" output is ignored for "rotateSecret", leaving "vault_key" unresolved, while "openSession" maps to [].

Constraints

  • 1 <= len(tools) <= 200
  • Every tool defines between 0 and 50 input fields and between 0 and 50 output fields.
  • Every "type" value is one of "string", "integer", "boolean", or "number".
  • Tool "name" strings are unique across tools, and self-edges (from_tool == to_tool) are never allowed.

Step-by-step walkthrough

  1. Clarify the matching and formatting rules

    When an orchestration system links API tools together, an output field emitted by producer A can feed an input parameter of consumer B whenever three conditions hold simultaneously:

    1. Equal canonical name: Take only the leaf segment after the final . (if present), strip every _ and -, and convert to lowercase:
    Raw schema path           Leaf after last '.'   Strip '_' and '-'   Lowercase (canonical)
    -----------------------------------------------------------------------------------------
    "billing.invoice_id" -->  "invoice_id"     -->  "invoiceid"    -->  "invoiceid"
    "invoiceId"          -->  "invoiceId"      -->  "invoiceId"    -->  "invoiceid"   (MATCH!)
    "meta.Invoice-ID"    -->  "Invoice-ID"     -->  "InvoiceID"    -->  "invoiceid"   (MATCH!)
    "account_code"       -->  "account_code"   -->  "accountcode"  -->  "accountcode"
    
    1. Exact type match: "integer" matches only "integer"—so "total_cents" ("integer") and "totalCents" ("number") do not match even though both canonicalize to "totalcents".
    2. Distinct tools (A != B): A tool may never satisfy its own input parameter.

    Three output conventions make the returned dictionary deterministic: - unresolved_inputs lists every tool name in tools, mapped to [] whenever all of its mandatory parameters are satisfied (or when it has none). - Optional parameters ("required": False) still produce directed edges when matched, yet never appear inside unresolved_inputs. - edges sort lexicographically by (from_tool, to_tool), and matches inside an edge sort by input_field (with output_field breaking ties when one producer has multiple matching output paths).

  2. Why nested all-pairs scanning does unnecessary work

    A direct brute-force comparison uses four nested loops: for every producer A, every consumer B != A, every output of A, and every input of B, normalize both field names and compare their types.

    At the upper limits (T = 200 tools with F = 50 inputs and 50 outputs each), that runs:

    200 * 199 * 50 * 50  ≈  99,500,000 field-pair checks
    

    Nearly all of those 100 million checks compare unrelated fields like "account_code" and "receipt_url" while repeatedly re-normalizing the same strings.

  3. Key idea: hash-index outputs by (canonical_name, type)

    Because field compatibility is an exact equality test on both canonical_name and type, we can replace the nested loops with a hash join—building a dictionary over all outputs once, then probing each consumer input in O(1) average time:

    Producer outputs                               output_index dictionary
    -----------------------------------            -------------------------------------------------------------------
    createInvoice: billing.invoice_id (integer) -> ("invoiceid", "integer")  : [("createInvoice", "billing.invoice_id")]
    createInvoice: total_cents        (integer) -> ("totalcents", "integer") : [("createInvoice", "total_cents")]
    chargeCard:    receipt_url        (string)  -> ("receipturl", "string")  : [("chargeCard", "receipt_url")]
    

    Notice what each bucket records: (producer_name, output_field) keeping the raw output_field string ("billing.invoice_id"), while the normalized tuple is used solely as the lookup key so final matches report exact schema paths.

    def canonical_name(field: str) -> str:
        """Leaf name after the last '.', with '_' and '-' removed, lowercased."""
        # Take only the leaf segment after the final dot (returns the whole string if no dot exists)
        leaf_segment = field.rsplit(".", 1)[-1]
        # Strip snake_case and kebab-case separators, then normalize case so invoiceId == invoice_id
        cleaned_leaf = leaf_segment.replace("_", "").replace("-", "")
        return cleaned_leaf.lower()
    
    
    def index_outputs(tools: List[dict]) -> Dict[tuple, List[tuple]]:
        """Build a lookup table mapping (canonical_name, type) -> [(tool_name, raw_output_field), ...]."""
        # output_index: e.g. {("invoiceid", "integer"): [("createInvoice", "billing.invoice_id")]}
        # Keeps raw_output_field alongside tool_name so final edges report exact schema paths.
        output_index: Dict[tuple, List[tuple]] = {}
        for tool in tools:
            producer_name = tool["name"]
            for output_field, output_spec in tool.get("outputs", {}).items():
                match_key = (canonical_name(output_field), output_spec["type"])
                if match_key not in output_index:
                    output_index[match_key] = []
                output_index[match_key].append((producer_name, output_field))
        return output_index
    
  4. Probe consumer inputs and block self-satisfaction

    Next, iterate through each consumer tool and look up every input's (canonical_name, type) key in output_index. Every bucket entry (producer_name, output_field) with producer_name != consumer_name appends a match onto edge (producer_name, consumer_name).

    Pay close attention to Example 2's trap when computing unresolved_inputs: "rotateSecret" requires "vault_key" (string) as an input and emits "vault_key" (string) as an output, while no other tool emits a vault key:

    output_index[("vaultkey", "string")]  -->  [("rotateSecret", "vault_key")]   (bucket is non-empty!)
    
    Buggy check:   if bucket is empty -> unresolved   (WRONG: lets rotateSecret satisfy itself!)
    Correct check: skip producer == consumer FIRST; set is_satisfied_by_other_tool = True
                   only when at least one EXTERNAL tool matches!
    

    Here is the consumer pass enforcing that rule:

    def generate_dependency_graph(tools: List[dict]) -> dict:
        # Phase 1: index every tool output once by (canonical_name, type) for O(1) average lookup
        output_index = index_outputs(tools)
    
        # edge_matches: maps (from_tool, to_tool) -> [(input_field, output_field), ...]
        # Putting input_field first in the tuple lets sorted() order by input_field, then output_field.
        edge_matches: Dict[tuple, List[tuple]] = {}
        # unresolved_inputs: maps every consumer tool_name -> sorted list of unsatisfied required inputs
        unresolved_inputs: Dict[str, List[str]] = {}
    
        # Phase 2: check every input of every consumer tool against the output index
        for tool in tools:
            consumer_name = tool["name"]
            missing_required: List[str] = []
    
            for input_field, input_spec in tool.get("inputs", {}).items():
                match_key = (canonical_name(input_field), input_spec["type"])
                is_satisfied_by_other_tool = False
    
                for producer_name, output_field in output_index.get(match_key, []):
                    # A tool cannot satisfy its own input (A != B); skip before marking satisfied!
                    if producer_name == consumer_name:
                        continue
                    is_satisfied_by_other_tool = True
                    edge_pair = (producer_name, consumer_name)
                    if edge_pair not in edge_matches:
                        edge_matches[edge_pair] = []
                    edge_matches[edge_pair].append((input_field, output_field))
    
                # Only required inputs with zero valid external producers count as unresolved
                if input_spec.get("required", False) and not is_satisfied_by_other_tool:
                    missing_required.append(input_field)
    
            unresolved_inputs[consumer_name] = sorted(missing_required)
        return {"edges": [], "unresolved_inputs": unresolved_inputs}
    
  5. Order edges and field pairs with tuple sorting

    Python sorts tuples lexicographically from left to right: - Sorting edge_matches keys (producer_name, consumer_name) orders edges by from_tool, then to_tool. - Storing each match tuple as (input_field, output_field)—with input_field first—means sorted(...) orders matches by input_field and breaks ties by output_field automatically!

    We then unpack each sorted tuple into {"output_field": output_field, "input_field": input_field}.

  6. Trace Example 1 end to end

    Let's walk through Example 1 (createInvoice and chargeCard):

    Step 1 — Populate output_index:
      createInvoice.outputs["billing.invoice_id"] (integer) -> ("invoiceid", "integer")  -> [("createInvoice", "billing.invoice_id")]
      createInvoice.outputs["total_cents"]        (integer) -> ("totalcents", "integer") -> [("createInvoice", "total_cents")]
      chargeCard.outputs["receipt_url"]           (string)  -> ("receipturl", "string")  -> [("chargeCard", "receipt_url")]
    
    Step 2 — Probe consumer inputs:
      1. createInvoice.inputs["account_code"] (string, required=True)
         -> key ("accountcode", "string") -> absent
         -> unresolved_inputs["createInvoice"] = ["account_code"]
    
      2. chargeCard.inputs["payment_method"] (string, required=True)
         -> key ("paymentmethod", "string") -> absent -> added to missing_required
    
      3. chargeCard.inputs["invoiceId"] (integer, required=False)
         -> key ("invoiceid", "integer") -> hits [("createInvoice", "billing.invoice_id")]
         -> "createInvoice" != "chargeCard" -> adds ("invoiceId", "billing.invoice_id") under ("createInvoice", "chargeCard")
    
      4. chargeCard.inputs["totalCents"] (number, required=True)
         -> key ("totalcents", "number") -> misses ("totalcents", "integer")! -> added to missing_required
    
    Step 3 — Assemble sorted output:
      edges = [{"from_tool": "createInvoice", "to_tool": "chargeCard",
                "matches": [{"output_field": "billing.invoice_id", "input_field": "invoiceId"}]}]
      unresolved_inputs = {"createInvoice": ["account_code"],
                           "chargeCard": ["payment_method", "totalCents"]}
    
  7. Assemble the complete solution

    Here is the full implementation ready for the test suite:

    from typing import Dict, List
    
    
    def canonical_name(field: str) -> str:
        """Leaf name after the last '.', with '_' and '-' removed, lowercased."""
        # Take only the leaf segment after the final dot (returns the whole string if no dot exists)
        leaf_segment = field.rsplit(".", 1)[-1]
        # Strip snake_case and kebab-case separators, then normalize case so invoiceId == invoice_id
        cleaned_leaf = leaf_segment.replace("_", "").replace("-", "")
        return cleaned_leaf.lower()
    
    
    def index_outputs(tools: List[dict]) -> Dict[tuple, List[tuple]]:
        """Build a lookup table mapping (canonical_name, type) -> [(tool_name, raw_output_field), ...]."""
        # output_index: e.g. {("invoiceid", "integer"): [("createInvoice", "billing.invoice_id")]}
        # Keeps raw_output_field alongside tool_name so final edges report exact schema paths.
        output_index: Dict[tuple, List[tuple]] = {}
        for tool in tools:
            producer_name = tool["name"]
            for output_field, output_spec in tool.get("outputs", {}).items():
                match_key = (canonical_name(output_field), output_spec["type"])
                if match_key not in output_index:
                    output_index[match_key] = []
                output_index[match_key].append((producer_name, output_field))
        return output_index
    
    
    def generate_dependency_graph(tools: List[dict]) -> dict:
        # Phase 1: index every tool output once by (canonical_name, type) for O(1) average lookup
        output_index = index_outputs(tools)
    
        # edge_matches: maps (from_tool, to_tool) -> [(input_field, output_field), ...]
        # Putting input_field first in the tuple lets sorted() order by input_field, then output_field.
        edge_matches: Dict[tuple, List[tuple]] = {}
        # unresolved_inputs: maps every consumer tool_name -> sorted list of unsatisfied required inputs
        unresolved_inputs: Dict[str, List[str]] = {}
    
        # Phase 2: check every input of every consumer tool against the output index
        for tool in tools:
            consumer_name = tool["name"]
            missing_required: List[str] = []
    
            for input_field, input_spec in tool.get("inputs", {}).items():
                match_key = (canonical_name(input_field), input_spec["type"])
                is_satisfied_by_other_tool = False
    
                for producer_name, output_field in output_index.get(match_key, []):
                    # A tool cannot satisfy its own input (A != B); skip before marking satisfied!
                    if producer_name == consumer_name:
                        continue
                    is_satisfied_by_other_tool = True
                    edge_pair = (producer_name, consumer_name)
                    if edge_pair not in edge_matches:
                        edge_matches[edge_pair] = []
                    edge_matches[edge_pair].append((input_field, output_field))
    
                # Only required inputs with zero valid external producers count as unresolved
                if input_spec.get("required", False) and not is_satisfied_by_other_tool:
                    missing_required.append(input_field)
    
            unresolved_inputs[consumer_name] = sorted(missing_required)
    
        # Phase 3: sort directed edges by (from_tool, to_tool) and field matches by input_field
        edges: List[dict] = []
        for producer_name, consumer_name in sorted(edge_matches):
            sorted_pairs = sorted(edge_matches[(producer_name, consumer_name)])
            formatted_matches = []
            for input_field, output_field in sorted_pairs:
                formatted_matches.append({
                    "output_field": output_field,
                    "input_field": input_field,
                })
            edges.append({
                "from_tool": producer_name,
                "to_tool": consumer_name,
                "matches": formatted_matches,
            })
    
        return {
            "edges": edges,
            "unresolved_inputs": unresolved_inputs,
        }
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture wiring API operations together like patching studio racks in a broadcast booth: every output port and input socket carries a label written in a slightly different naming style (billing.invoice_id vs. invoiceId) alongside a strict connector shape (integer vs. number). Rather than testing every cable from every rack against every socket on every other rack, we map each field label to its canonical form (a single standardized spelling—here the lowercased leaf segment with _ and - stripped, such as invoiceid) and organize all output ports in a dictionary keyed by (canonical_name, type). This strategy is a hash join—an algorithm that indexes one collection in a hash map so items from a second collection find all exact matches in O(1) average time.

The naive method runs four nested loops comparing every output of every producer A against every input of every consumer B. At 200 tools with 50 inputs and 50 outputs apiece, that executes nearly 200 * 199 * 50 * 50 ≈ 100 million checks, wasting over 99% of its work comparing non-matching fields like account_code and receipt_url while repeatedly re-normalizing strings.

Walk through Example 1 (createInvoice and chargeCard): 1. Index outputs: createInvoice's billing.invoice_id (integer) hashes to ("invoiceid", "integer") -> [("createInvoice", "billing.invoice_id")]; total_cents (integer) hashes to ("totalcents", "integer"); chargeCard's receipt_url (string) hashes to ("receipturl", "string"). 2. Probe createInvoice inputs: Required parameter account_code (string) probes ("accountcode", "string"), finds nothing, and lands in unresolved_inputs["createInvoice"] = ["account_code"]. 3. Probe chargeCard inputs: Optional invoiceId (integer) probes ("invoiceid", "integer"), hits ("createInvoice", "billing.invoice_id"), verifies "createInvoice" != "chargeCard", and records the match under edge createInvoice -> chargeCard. Required totalCents (number) probes ("totalcents", "number"), misses ("totalcents", "integer"), and joins payment_method in unresolved_inputs["chargeCard"] = ["payment_method", "totalCents"].

Complexity

Let N be the total number of input and output fields across all tools (at most 200 * (50 + 50) = 20,000), M be the total number of matched field pairs in the result, S be the number of skipped self-matches where a tool's own output shares a key with its own input, and E be the number of directed edges. Because field names are short identifiers, normalizing one field name runs in constant time relative to catalog size.

  • Time complexity — O(N + M + S + E log E + M log M): Building output_index visits each output field once and performs one O(1)-average dictionary append (O(N)). Scanning consumer inputs performs one O(1)-average lookup per input (O(N)) and loops only over bucket entries sharing the exact (canonical_name, type) key—each yielding either one of the M reported matches or one of the S skipped self-matches. Sorting E edges takes O(E log E), sorting M match tuples across all edges takes at most O(M log M), and sorting unresolved lists takes at most O(N log N).
  • Space complexity — O(N + M): output_index stores one (tool_name, output_field) pair per output field (O(N)), unresolved_inputs holds every tool name and unsatisfied required input (O(N)), and edge_matches stores one tuple per matched pair (O(M)).

Edge cases

  • Tools with empty inputs or outputs: Using tool.get("inputs", {}) and tool.get("outputs", {}) handles empty schemas cleanly while still initializing unresolved_inputs[tool_name] = [] (as with openSession in Example 2).
  • Self-matching output on the same tool: In Example 2, rotateSecret both requires and outputs vault_key: string; skipping producer_name == consumer_name before setting is_satisfied_by_other_tool = True guarantees vault_key stays unresolved unless an external tool supplies it.
  • Optional parameters (required: False): Optional inputs still create dependency edges when matched (like invoiceId in Example 1), yet never appear in unresolved_inputs when unmatched.
  • Multiple compatible outputs on one producer: When tool p emits Host, data.host, and net.h_ost (string) and tool c accepts host: string, all three pairs group under a single p -> c edge sorted by (input_field, output_field).
  • Dotted input parameter names: Applying canonical_name symmetrically to inputs and outputs allows ctx.ticket-no to match a.b.ticket_no.
  • Numeric type strictness: total_cents: integer never matches totalCents: number because type strings must be identical.

Common mistakes

  • Stripping dots from the full path instead of taking the leaf: Deleting . across the whole string turns billing.invoice_id into billinginvoiceid, breaking the match with invoiceId (invoiceid).
  • Reporting normalized keys inside matches: Returning {"output_field": "invoiceid", ...} instead of "billing.invoice_id" discards the exact extraction path downstream runners need.
  • Testing if match_key in output_index to mark a required input satisfied: A non-empty bucket might contain only the consumer's own output, silently hiding an unsatisfied requirement.
  • Emitting duplicate (from_tool, to_tool) edge objects: Appending a fresh edge dict per matched field pair instead of grouping under (producer_name, consumer_name) produces duplicate edges whenever two fields connect the same pair of tools.
  • Matching prefixes or substrings: email ("email") and email_address ("emailaddress") have distinct canonical keys and must never match.

Alternative approaches

  • All-pairs nested loops: Check every output of tool A against every input of tool B directly in O(T^2 * F^2) time and O(1) extra indexing space. Too slow for large catalogs, though handy as a compact reference oracle in randomized tests.
  • Sort-merge join: A sort-merge join sorts both the flat list of outputs and the flat list of inputs by (canonical_name, type) and advances two cursors in lockstep in O(N log N + M) time, avoiding hash tables when schemas stream from external disk storage.

Follow-up questions

  • When several upstream tools emit a compatible field for the same parameter, how would you rank or disambiguate them? Keep all valid candidate edges in the static graph (since static analysis captures every feasible connection), and attach an ambiguous_inputs report for any (tool, input_field) matched by two or more external producers. During workflow planning, score competing producers using exact raw-name matches ahead of canonical-only matches, parent-segment alignment (preferring createInvoice.invoice.id over listRefunds.refund.id when filling sendInvoice.id), description embedding similarity, and historical execution reliability—asking an agent or user to break ties when top confidence scores stay close.
  • How would you adapt the matcher when inputs and outputs are nested JSON objects that may only partially overlap? Recursively flatten nested object schemas into leaf dot-paths (customer: {id: int, tier: str} -> customer.id, customer.tier) and include the immediate parent entity alongside the leaf (customer.id) to prevent cross-entity collisions. When a downstream parameter expects a composite object, compute a subfield coverage score (matched_required_leaves / total_required_leaves, potentially combining multiple upstream producers) and label edges "full" (coverage == 1.0) or "partial" (0 < coverage < 1.0).
  • How would you identify and surface dependency cycles across the resulting tool graph? A directed cycle is a closed loop T1 -> T2 -> ... -> T1 where every operation waits on another operation inside the loop. You can find a cycle in O(V + E) time using depth-first search (DFS) (walking forward along edges as deep as possible before backtracking) with three visitation states (unvisited, active on the current recursion path, and done), or list every mutually dependent group in O(V + E) time via strongly connected components (SCCs) (maximal node subsets where every node can reach every other node, using Tarjan's algorithm)—filtering specifically to edges backing required inputs so optional-only loops do not trigger false deadlocks.
def find_cycle(edges):
    """Return one directed cycle as [a, b, ..., a], or None if the graph has no cycle."""
    adjacency = {}
    for edge in edges:
        adjacency.setdefault(edge["from_tool"], []).append(edge["to_tool"])

    state = {}  # tool_name -> "active" (on current DFS stack) or "done" (fully explored)
    current_path = []

    def dfs(node):
        state[node] = "active"
        current_path.append(node)
        for neighbor in adjacency.get(node, []):
            if state.get(neighbor) == "active":
                cycle_start = current_path.index(neighbor)
                return current_path[cycle_start:] + [neighbor]
            if neighbor not in state:
                found = dfs(neighbor)
                if found is not None:
                    return found
        current_path.pop()
        state[node] = "done"
        return None

    for tool_name in sorted(adjacency):
        if tool_name not in state:
            cycle = dfs(tool_name)
            if cycle is not None:
                return cycle
    return None

Follow-up questions

Similar questions

More Composio interview questions

All 1 Composio questions →