MP-301a · Module 1
Conditional Routing
3 min read
Conditional routing is the pattern where a tool inspects its input or an intermediate result and takes different code paths based on the value. The simplest form is a "smart dispatcher" tool that examines the request and delegates to the right handler — similar to a switch statement, but operating at the tool level. This reduces the number of tools the LLM has to choose from while still providing specialized handling for different cases.
The danger of conditional routing is hidden complexity. A tool that says "process this document" but internally handles PDFs, spreadsheets, images, and emails differently is five tools pretending to be one. The LLM cannot see the internal routing, so its description must enumerate every supported type, or the model will send unsupported inputs and get opaque errors. The rule of thumb: if each branch has different error modes, different performance characteristics, or different output schemas, they should be separate tools. If they share the same contract and differ only in implementation, routing is fine.
// Conditional routing — one tool, multiple handlers
const handlers: Record<string, (content: string) => Promise<string>> = {
pdf: extractPdfText,
csv: parseCsvToJson,
markdown: renderMarkdownToHtml,
json: validateAndFormat,
};
async function processDocument(args: { content: string; format: string }) {
const handler = handlers[args.format];
if (!handler) {
return {
isError: true,
content: [{
type: "text" as const,
text: `Unsupported format: "${args.format}". ` +
`Supported formats: ${Object.keys(handlers).join(", ")}. ` +
`Use detect_format tool if the format is unknown.`,
}],
};
}
const result = await handler(args.content);
return {
content: [{ type: "text" as const, text: result }],
metadata: { format: args.format, handler: handler.name },
};
}
Do This
- Use routing when branches share the same input/output contract
- List all supported routes in the tool description with explicit enum constraints
- Surface which route was taken in the response metadata
- Provide a fallback with a helpful error listing valid routes
Avoid This
- Route when branches have fundamentally different error modes or output schemas
- Hide the routing options — the LLM must know what formats are supported
- Return a generic error for unsupported routes without listing valid alternatives
- Let the router silently pick a default when the input is ambiguous