Patterns Factory / Registry Pattern See in Code Tour

Factory Pattern

A central tool registry that produces Tool instances on demand โ€” enabling dynamic loading and MCP tool injection.

Factory Pattern โ€” Architecture Diagram
graph TD
    A[Tool Registry] --> B[findToolByName]
    B --> C{Built-in?}
    C -->|Yes| D[Return Built-in Tool]
    C -->|No| E{MCP Tool?}
    E -->|Yes| F[Wrap in MCPTool adapter]
    E -->|No| G[Return undefined]
    D --> H[StreamingToolExecutor]
    F --> H

Mermaid diagram definition

Deep Dive

The tool registry in src/tools.ts is a Factory: given a tool name from Claude's response, it produces the correct Tool object. This decouples the query engine (which needs to execute tools) from the tool implementations.

๐Ÿ”‘Key Insight

MCP tools are wrapped in a `MCPTool` adapter at registration time. The factory produces the same `Tool` interface regardless of whether the underlying tool is built-in TypeScript code or a remote MCP server.

โ„น๏ธInfo

`findToolByName()` supports aliases: a tool can have multiple names (for backwards compatibility when renamed). The registry resolves any alias to the canonical implementation.

KEY TAKEAWAYS
  • โ†’Registry pattern centralizes object creation logic
  • โ†’Alias support enables backwards-compatible tool renaming
  • โ†’MCP tools are wrapped at registration, not at call time
  • โ†’The factory is the only place tool enumeration happens

Source Code

findToolByName() and toolMatchesName() โ€” the factory lookup functions.

 */
export function toolMatchesName(
  tool: { name: string; aliases?: string[] },
  name: string,
): boolean {
  return tool.name === name || (tool.aliases?.includes(name) ?? false)
}

/**
 * Finds a tool by name or alias from a list of tools.
 */
export function findToolByName(tools: Tools, name: string): Tool | undefined {
  return tools.find(t => toolMatchesName(t, name))
}

export type Tool<
  Input extends AnyObject = AnyObject,
  Output = unknown,
  P extends ToolProgressData = ToolProgressData,
AI Assistant

Ask anything about Factory Pattern

Powered by Groq ยท Enter to send, Shift+Enter for newline