Claude API: Tool Chain — Function Reference
Source files: composer.js (1042 LOC), selector.js (891 LOC), engine.js (848 LOC), index.js
Exported Functions — engine.js
createChain(config): ChainObject
Purpose: Define and store a new tool chain with execution mode, nodes, error strategy, and timeout. Parameters:
id(string, optional): Chain ID (auto-generated UUID if omitted)name(string): Chain namedescription(string): Description-
mode(ChainMode): sequentialparallel conditional loop dag nodes(ChainNode[]): Ordered list of node definitions-
errorStrategy(ErrorStrategy): stopcontinue retry fallback skip maxRetries(number): Retry attempts on node failure (default: 3)retryDelay(number): Delay between retries in ms (default: 1000)timeout(number): Overall chain timeout in ms (default: 30000)variables(object): Initial variable bindings
Returns: Stored ChainObject
Notes for rewrite: Validates that all nodes have id + type, TOOL nodes have tool name. Stores in module-level Map.
executeChain(chainId, context, toolExecutor): Promise<ExecutionResult>
Purpose: Run a stored chain with given context. Dispatches to mode-specific executor. Parameters:
chainId(string): Stored chain IDcontext(object): Execution context —{ variables: {} }toolExecutor(Function):async (toolName, params) => result
Returns: { success, executionId, chainId, status, results, variables, errors, duration }
Notes for rewrite: Wraps execution in a Promise.race against timeout. Stores all executions in chainExecutions Map.
getChain(chainId): ChainObject|null
Purpose: Retrieve stored chain by ID.
listChains(): ChainSummary[]
Purpose: List all chains with metadata.
Returns: [{ id, name, description, mode, nodeCount, runCount, created }]
deleteChain(chainId): boolean
getExecutionStatus(executionId): ExecutionStatus|null
Purpose: Lightweight execution summary.
Returns: { id, chainId, status, startTime, endTime, currentNode, resultCount, errorCount }
getExecutionDetails(executionId): ExecutionObject|null
Purpose: Full execution state including all results.
listExecutions(chainId): ExecutionSummary[]
Purpose: All executions for a given chain.
stopExecution(executionId): boolean
Purpose: Immediately mark a running execution as “stopped”.
cloneChain(chainId, overrides): ChainObject
Purpose: Deep-copy chain with new ID, optionally overriding properties. Parameters:
chainId(string): Source chainoverrides(object): Any chain properties to override
exportChain(chainId): string
Purpose: Serialize chain to JSON string.
importChain(json): ChainObject
Purpose: Deserialize chain from JSON and store with new ID.
Constants: ChainMode
| Value | Description |
|——-|————-|
| SEQUENTIAL | Execute nodes one after another |
| PARALLEL | Execute all nodes concurrently (respects concurrency limit) |
| CONDITIONAL | Execute nodes with condition checks per node |
| LOOP | Execute all nodes in a loop until maxIterations |
| DAG | Directed acyclic graph execution respecting dependsOn |
Constants: ErrorStrategy
| Value | Description |
|——-|————-|
| STOP | Halt on first node failure |
| CONTINUE | Skip failed nodes, continue |
| RETRY | Retry failed nodes up to maxRetries |
| FALLBACK | Use fallback value from node config |
| SKIP | Skip failed node silently |
Constants: NodeType
TOOL, CONDITION, LOOP, PARALLEL, TRANSFORM, DELAY
Exported Functions — composer.js
createComposition(config): CompositionObject
Purpose: Define a tool composition (richer than a chain — supports input/output schema validation and advanced node types). Parameters:
id(string, optional)name(string)description(string)nodes(ComposerNode[]): Ordered pipeline nodesinputSchema(object): JSON schema for composition inputoutputSchema(object): JSON schema for composition output
Returns: Stored CompositionObject
executeComposition(compositionId, input, toolExecutor): Promise<CompositionResult>
Purpose: Execute composition with input data. Validates input/output against schemas. Passes data through nodes sequentially. Parameters:
compositionId(string)input(object): Input data (validated againstinputSchema)toolExecutor(Function):async (toolName, params) => result
Returns: { success, executionId, compositionId, data, executionPath, nodeCount } or error shape.
Notes for rewrite: Supports onError per node: “stop” (default), “fallback” (uses node.fallback), or “continue”. Node output stored in context.outputs Map for downstream access.
getComposition(compositionId): CompositionObject|null
listCompositions(): CompositionSummary[]
Returns: [{ id, name, description, nodeCount, runCount, created }]
deleteComposition(compositionId): boolean
composeTools(toolNames, config): CompositionObject
Purpose: Convenience factory — create a sequential composition from a list of tool names with optional I/O mappings. Parameters:
toolNames(string[]): e.g.["web_search", "analysis_search"]config(object):{ name, description, mappings: [{input, output}], inputSchema, outputSchema }
createValidationChain(validators): CompositionObject
Purpose: Build a composition of VALIDATE nodes from a list of JSON schemas. Parameters:
validators(Array):[{ schema, required }]
createTransformPipeline(transforms): CompositionObject
Purpose: Build a composition of TRANSFORM nodes. Parameters:
transforms(Array):[{ type: TransformType, config }]
Constants: ComposerNodeType
TOOL, MAP, FILTER, REDUCE, TRANSFORM, VALIDATE, BRANCH, MERGE, CONDITIONAL
Constants: TransformType
MAP, FILTER, REDUCE, FLAT_MAP, GROUP_BY, SORT, PICK, OMIT, MERGE, RENAME, CUSTOM
Input/Output Mapping Syntax (composer nodes)
Node inputMapping and outputMapping support path references:
$input.fieldName— from composition input$var.varName— from execution context variables$output.nodeId— from a previous node’s output- Literal string value if none of the above prefixes match
Exported Functions — selector.js
initializeSelector(tools): void
Purpose: Populate the internal tool registry with available tools. Must be called before selectTools.
Parameters:
tools(ToolDefinition[]): Array of{ name, description, category, inputSchema, ... }
selectTools(query, options): SelectionResult
Purpose: Select relevant tools based on a natural-language query using the specified matching strategy. Parameters:
query(string): Natural language query or intent-
strategy(SelectionStrategy): exactfuzzy semantic intent hybrid (default: hybrid) maxResults(number): Max tools to return (default: 5)threshold(number): Minimum score to include (default: 0.3)context(object): Context hints —{ recentTools: [] }excludeTools(string[]): Tool names to exclude
Returns: { success, query, strategy, results: [{name, description, score, matches, category, inputSchema}], totalMatches, detectedIntent }
Notes for rewrite: Hybrid strategy weights: exact 35%, fuzzy 25%, semantic 25%, intent 15%. Usage success rate boosts score by ±20%.
Constants: SelectionStrategy
| Value | Description | |——-|————-| | EXACT | Substring match on name + description | | FUZZY | Levenshtein distance ≤2 word matching | | SEMANTIC | TF-IDF bag-of-words Jaccard similarity | | INTENT | Keyword→intent→tool pattern matching | | HYBRID | Weighted combination of all four |
INTENT_PATTERNS (internal, not exported)
Pre-defined intents: search, read, write, analyze, execute, manage, monitor — each mapped to expected tool names.
Key Data Structures
| Structure | Fields | Purpose |
|---|---|---|
| ChainObject | id, name, mode, nodes, errorStrategy, maxRetries, timeout, variables, metadata | Stored chain definition |
| ChainNode | id, type, tool?, condition?, outputVar?, onSuccess?, onError?, fallback? | Single chain step |
| CompositionObject | id, name, nodes, inputSchema, outputSchema, metadata | Composition definition |
| ComposerNode | id, type, tool?, inputMapping?, outputMapping?, schema?, branches?, condition?, then?, otherwise? | Composition step |
| ExecutionResult | success, executionId, chainId, status, results, variables, errors, duration | Chain run outcome |
External Dependencies
uuid—v4()for ID generation- No Anthropic SDK calls — orchestration layer only
Notes for Rewrite
- The semantic matching is bag-of-words Jaccard (not embedding-based) — suitable to replace with real embeddings.
- Chain/composition state is held entirely in module-level Maps (memory-only, lost on restart).
- The DAG executor (
executeDAG) traversesnode.dependsOn[]to determine execution order. - LOOP mode tracks
iterationin execution variables; nodes may read$var.iteration. validateAgainstSchemain composer.js is a hand-rolled JSON schema validator covering type, required, minLength, maxLength, pattern, minimum, maximum, minItems, maxItems.