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:
- 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". - Compatibility between two distinct tools: An output field of producer
Asatisfies an input parameter of consumerBif and only ifA["name"] != B["name"], both fields have equalcanonical_namestrings, and their"type"strings are identical. - Graph edges (
"edges"): Whenever producerAsupplies at least one compatible field (whetherrequiredisTrueorFalse) to consumerB, 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 byfrom_tool, thento_tool. Order"matches"inside each edge lexicographically byinput_field, breaking ties byoutput_field. - Unsatisfied mandatory parameters (
"unresolved_inputs"): Return a dictionary containing every tool's"name"mapped to a lexicographically sorted list of its"required": Trueinput 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
0and50input fields and between0and50output fields. - Every
"type"value is one of"string","integer","boolean", or"number". - Tool
"name"strings are unique acrosstools, and self-edges (from_tool == to_tool) are never allowed.
Step-by-step walkthrough
Clarify the matching and formatting rules
When an orchestration system links API tools together, an output field emitted by producer
Acan feed an input parameter of consumerBwhenever three conditions hold simultaneously:- 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"- Exact type match:
"integer"matches only"integer"—so"total_cents"("integer") and"totalCents"("number") do not match even though both canonicalize to"totalcents". - Distinct tools (
A != B): A tool may never satisfy its own input parameter.
Three output conventions make the returned dictionary deterministic: -
unresolved_inputslists every tool name intools, 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 insideunresolved_inputs. -edgessort lexicographically by(from_tool, to_tool), andmatchesinside an edge sort byinput_field(withoutput_fieldbreaking ties when one producer has multiple matching output paths).- Equal canonical name: Take only the leaf segment after the final
Why nested all-pairs scanning does unnecessary work
A direct brute-force comparison uses four nested loops: for every producer
A, every consumerB != A, every output ofA, and every input ofB, normalize both field names and compare their types.At the upper limits (
T = 200tools withF = 50inputs and50outputs each), that runs:200 * 199 * 50 * 50 ≈ 99,500,000 field-pair checksNearly all of those 100 million checks compare unrelated fields like
"account_code"and"receipt_url"while repeatedly re-normalizing the same strings.Key idea: hash-index outputs by (canonical_name, type)
Because field compatibility is an exact equality test on both
canonical_nameandtype, we can replace the nested loops with a hash join—building a dictionary over all outputs once, then probing each consumer input inO(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 rawoutput_fieldstring ("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_indexProbe consumer inputs and block self-satisfaction
Next, iterate through each consumer tool and look up every input's
(canonical_name, type)key inoutput_index. Every bucket entry(producer_name, output_field)withproducer_name != consumer_nameappends 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}Order edges and field pairs with tuple sorting
Python sorts tuples lexicographically from left to right: - Sorting
edge_matcheskeys(producer_name, consumer_name)orders edges byfrom_tool, thento_tool. - Storing each match tuple as(input_field, output_field)—withinput_fieldfirst—meanssorted(...)orders matches byinput_fieldand breaks ties byoutput_fieldautomatically!We then unpack each sorted tuple into
{"output_field": output_field, "input_field": input_field}.Trace Example 1 end to end
Let's walk through Example 1 (
createInvoiceandchargeCard):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"]}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): Buildingoutput_indexvisits each output field once and performs oneO(1)-average dictionary append (O(N)). Scanning consumer inputs performs oneO(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 theMreported matches or one of theSskipped self-matches. SortingEedges takesO(E log E), sortingMmatch tuples across all edges takes at mostO(M log M), and sorting unresolved lists takes at mostO(N log N). - Space complexity —
O(N + M):output_indexstores one(tool_name, output_field)pair per output field (O(N)),unresolved_inputsholds every tool name and unsatisfied required input (O(N)), andedge_matchesstores one tuple per matched pair (O(M)).
Edge cases
- Tools with empty inputs or outputs: Using
tool.get("inputs", {})andtool.get("outputs", {})handles empty schemas cleanly while still initializingunresolved_inputs[tool_name] = [](as withopenSessionin Example 2). - Self-matching output on the same tool: In Example 2,
rotateSecretboth requires and outputsvault_key: string; skippingproducer_name == consumer_namebefore settingis_satisfied_by_other_tool = Trueguaranteesvault_keystays unresolved unless an external tool supplies it. - Optional parameters (
required: False): Optional inputs still create dependency edges when matched (likeinvoiceIdin Example 1), yet never appear inunresolved_inputswhen unmatched. - Multiple compatible outputs on one producer: When tool
pemitsHost,data.host, andnet.h_ost(string) and toolcacceptshost: string, all three pairs group under a singlep -> cedge sorted by(input_field, output_field). - Dotted input parameter names: Applying
canonical_namesymmetrically to inputs and outputs allowsctx.ticket-noto matcha.b.ticket_no. - Numeric type strictness:
total_cents: integernever matchestotalCents: numberbecause type strings must be identical.
Common mistakes
- Stripping dots from the full path instead of taking the leaf: Deleting
.across the whole string turnsbilling.invoice_idintobillinginvoiceid, breaking the match withinvoiceId(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_indexto 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") andemail_address("emailaddress") have distinct canonical keys and must never match.
Alternative approaches
- All-pairs nested loops: Check every output of tool
Aagainst every input of toolBdirectly inO(T^2 * F^2)time andO(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 inO(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_inputsreport 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 (preferringcreateInvoice.invoice.idoverlistRefunds.refund.idwhen fillingsendInvoice.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 -> ... -> T1where every operation waits on another operation inside the loop. You can find a cycle inO(V + E)time using depth-first search (DFS) (walking forward along edges as deep as possible before backtracking) with three visitation states (unvisited,activeon the current recursion path, anddone), or list every mutually dependent group inO(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 backingrequiredinputs 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
- When several upstream tools emit a compatible field for the same parameter, how would you rank or disambiguate them?
- How would you adapt the matcher when inputs and outputs are nested JSON objects that may only partially overlap?
- How would you identify and surface dependency cycles across the resulting tool graph?
Similar questions
- Dynamic Dynasty Succession Without an Initial Monarch
- DOM Button Click Listener and Event Target
- Catalog Search, Filtering, and Pagination
- Case-Insensitive Ticket Queue Filtering and UI State Debugging
- Library Hold-Queue and Loan Reminder Notification Manager
- Transactional Shopping Cart with Nested Scopes