agent-tool-routing
Use this skill when implementing tool selection for AI agents. Activate when the user needs agents to choose the right tools, implement dynamic tool routing, integrate MCP servers, design tool selection logic, or build agents that can use external services effectively.
What this skill does
# Agent Tool Routing
Design intelligent systems for agents to select and use the right tools at the right time.
## When to Use
- Agents need to choose between multiple tools
- Implementing MCP (Model Context Protocol) integrations
- Building agents with external API access
- Designing tool fallback strategies
- Optimizing tool usage for cost/performance
## Tool Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ AGENT │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ TOOL ROUTER │
│ ┌─────────────┐ ┌──────────────┐ ┌────────────────────┐ │
│ │ Classifier │ │ Capabilities │ │ Cost/Latency │ │
│ │ │ │ Matcher │ │ Optimizer │ │
│ └─────────────┘ └──────────────┘ └────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────────────────┼─────────────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Tool A │ │ Tool B │ │ Tool C │
│ (Local) │ │ (API) │ │ (MCP) │
└─────────┘ └─────────┘ └─────────┘
```
## Tool Definition
```typescript
interface Tool {
name: string;
description: string;
category: string;
// Schema
inputSchema: JSONSchema;
outputSchema: JSONSchema;
// Capabilities
capabilities: string[];
limitations: string[];
// Execution
execute: (input: unknown) => Promise<ToolResult>;
// Metadata
metadata: {
costPerCall?: number;
avgLatencyMs?: number;
rateLimit?: RateLimit;
requiresAuth?: boolean;
supportsBatching?: boolean;
};
}
interface ToolResult {
success: boolean;
data?: unknown;
error?: {
code: string;
message: string;
retryable: boolean;
};
metadata: {
durationMs: number;
tokensUsed?: number;
};
}
```
## Tool Registry
```typescript
class ToolRegistry {
private tools = new Map<string, Tool>();
private capabilityIndex = new Map<string, Set<string>>();
register(tool: Tool): void {
this.tools.set(tool.name, tool);
// Index by capability
for (const cap of tool.capabilities) {
if (!this.capabilityIndex.has(cap)) {
this.capabilityIndex.set(cap, new Set());
}
this.capabilityIndex.get(cap)!.add(tool.name);
}
}
findByCapability(capability: string): Tool[] {
const toolNames = this.capabilityIndex.get(capability) || new Set();
return Array.from(toolNames).map(name => this.tools.get(name)!);
}
getAll(): Tool[] {
return Array.from(this.tools.values());
}
// Generate tool descriptions for LLM
getToolDescriptions(): string {
return this.getAll()
.map(t => `- ${t.name}: ${t.description}`)
.join('\n');
}
}
```
## Router Strategies
### Strategy 1: LLM-Based Selection
Let the model choose based on descriptions.
```typescript
class LLMToolRouter {
async route(
task: string,
availableTools: Tool[]
): Promise<RoutingDecision> {
const response = await this.llm.complete({
system: `You are a tool routing assistant.
Given a task and available tools, select the best tool to use.
Available tools:
${availableTools.map(t => `
- ${t.name}
Description: ${t.description}
Capabilities: ${t.capabilities.join(', ')}
Cost: ${t.metadata.costPerCall || 'free'}
Latency: ${t.metadata.avgLatencyMs || 'unknown'}ms
`).join('\n')}
Respond with JSON: { "tool": "tool_name", "reasoning": "why", "input": {...} }`,
user: `Task: ${task}`
});
return JSON.parse(response);
}
}
```
### Strategy 2: Rule-Based Selection
Deterministic routing based on patterns.
```typescript
class RuleBasedRouter {
private rules: RoutingRule[] = [];
addRule(rule: RoutingRule): void {
this.rules.push(rule);
this.rules.sort((a, b) => b.priority - a.priority);
}
route(task: string, context: Context): RoutingDecision {
for (const rule of this.rules) {
if (rule.matches(task, context)) {
return {
tool: rule.targetTool,
reasoning: rule.description
};
}
}
return { tool: 'default', reasoning: 'No specific rule matched' };
}
}
// Example rules
const rules: RoutingRule[] = [
{
priority: 100,
description: 'Use web search for current information',
matches: (task) => /current|latest|today|news|2024|2025|2026/.test(task),
targetTool: 'web_search'
},
{
priority: 90,
description: 'Use code execution for calculations',
matches: (task) => /calculate|compute|sum|average|math/.test(task),
targetTool: 'code_interpreter'
},
{
priority: 80,
description: 'Use file reader for document analysis',
matches: (task, ctx) => ctx.hasAttachments && /read|analyze|extract/.test(task),
targetTool: 'file_reader'
}
];
```
### Strategy 3: Cost-Optimized Selection
Choose based on cost/performance trade-offs.
```typescript
class CostOptimizedRouter {
async route(
task: string,
capableTools: Tool[],
budget: Budget
): Promise<RoutingDecision> {
// Score each tool
const scored = capableTools.map(tool => ({
tool,
score: this.calculateScore(tool, budget)
}));
// Sort by score (higher is better)
scored.sort((a, b) => b.score - a.score);
return {
tool: scored[0].tool.name,
reasoning: `Best cost/performance ratio within budget`
};
}
private calculateScore(tool: Tool, budget: Budget): number {
const cost = tool.metadata.costPerCall || 0;
const latency = tool.metadata.avgLatencyMs || 1000;
// Can't use if over budget
if (cost > budget.remaining) return -Infinity;
// Score: lower cost and latency = higher score
const costScore = 1 - (cost / budget.max);
const latencyScore = 1 - Math.min(latency / 5000, 1);
return costScore * budget.costWeight + latencyScore * budget.latencyWeight;
}
}
```
## MCP Integration
### MCP Server Connection
```typescript
interface MCPServer {
name: string;
transport: 'stdio' | 'http' | 'websocket';
config: MCPConfig;
}
class MCPToolProvider {
private clients = new Map<string, MCPClient>();
async connect(server: MCPServer): Promise<void> {
const client = new MCPClient(server.transport, server.config);
await client.connect();
// Discover tools
const tools = await client.listTools();
// Register each tool
for (const tool of tools) {
registry.register({
name: `${server.name}:${tool.name}`,
description: tool.description,
inputSchema: tool.inputSchema,
execute: (input) => client.callTool(tool.name, input),
metadata: {
source: 'mcp',
server: server.name
}
});
}
this.clients.set(server.name, client);
}
async disconnect(serverName: string): Promise<void> {
const client = this.clients.get(serverName);
if (client) {
await client.close();
this.clients.delete(serverName);
}
}
}
```
### MCP Configuration
```json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"filesystem": {
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem"],
"env": {
"ALLOWED_PATHS": "/Users/dev/projects"
}
},
"database": {
"transport": "http",
"url": "http://localhost:3001/mcp",
"auth": {
"type": "bearer",
"token": "${DB_MCP_TOKEN}"
}
}
}
}
```
## Tool Execution
### With Retry Logic
```typescript
async function executeWithRetry(
tool: Tool,
input: unknown,
options:Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.