Create or modify an agent tool: $ARGUMENTS
Before Starting
- Search OpenAI docs for latest tool patterns:
- Use
mcp__openai-docs__search_openai_docs with query "Agents SDK tool definition" for current tool() helper signature
- Use
mcp__openai-docs__search_openai_docs with query "Agents SDK function tools parameters" for parameter schema patterns
- Read existing tool implementations:
{{PROJECT_ROOT}}/{{AGENTS_DIR}}/ai-lab/tools/base.ts — search_books, file_search tools with caching + metrics
{{PROJECT_ROOT}}/{{AGENTS_DIR}}/seo-expert/tools.ts — 9-tool suite (analyze, research, score, optimize, generate)
{{PROJECT_ROOT}}/{{AGENTS_DIR}}/ai-lab/tools/utils.ts — executeToolWithMetrics(), timeout constants
- Read the shared tool infrastructure:
{{PROJECT_ROOT}}/src/services/toolCacheService.ts — param-based LRU caching with TTL
Tool Template
import { tool } from '@openai/agents';
import { z } from 'zod';
import type { RunContext } from '@openai/agents';
export const myTool = tool({
name: 'my_tool',
description: 'Clear, specific description of what this tool does and when the agent should use it.',
parameters: z.object({
query: z.string().describe('What to search for'),
maxResults: z.number().optional().default(5).describe('Maximum results to return'),
}),
strict: true,
execute: async (params, context?: RunContext<MyContext>) => {
// 1. Check cache (if applicable)
const cacheKey = `my_tool:${params.query}`;
const cached = await toolCacheService.get(cacheKey);
if (cached) return cached;
// 2. Execute with metrics and timeout
const { result } = await executeToolWithMetrics('my_tool', async () => {
// Tool implementation here
return { data: 'result' };
}, TOOL_TIMEOUTS.MEDIUM);
// 3. Cache result
toolCacheService.set(cacheKey, result).catch(() => {});
return result;
},
});
Patterns by Tool Type
Search / Retrieval Tools
- Return structured results with title, snippet, url/slug, relevance score
- Always include a
maxResults parameter with sensible default
- Gracefully degrade when external service is unavailable (return empty array, not error)
- Add citation metadata when results reference source material
Analysis / Computation Tools
- Accept content as string input
- Return structured analysis object (scores, categories, suggestions)
- Include confidence scores where applicable
- Keep descriptions prescriptive so the agent knows when to invoke
API Integration Tools
- Validate API keys exist before calling
- Set appropriate timeouts (TOOL_TIMEOUTS: SHORT=5s, MEDIUM=15s, LONG=30s)
- Return user-friendly error messages, not raw API errors
- Never expose API keys in tool results
Database Query Tools
- Use the service layer (never raw SQL in tools)
- Scope by
organizationId from context for multi-tenant safety
- Return only fields the agent needs, not entire rows
Registration
After creating the tool, register it with the target agent:
Static registration (simple agents):
// In the agent's index.ts
import { myTool } from './tools';
export const myAgent = new Agent({
tools: [myTool, existingTool1],
});
Dynamic registration (function-based agents):
// In the agent's tools/index.ts
export function getToolsForConfiguration(context: RunContext<MyContext>): Tool[] {
const tools = [...getBaseTools()];
if (context.context.someCondition) {
tools.push(myTool);
}
return tools;
}
Rules
- Tool names must be snake_case
- Descriptions should tell the agent WHEN to use the tool, not just what it does
- Parameters must use Zod schemas with
.describe() on every field
- Always handle errors gracefully — return error objects, never throw
- Cache results when the tool calls external services
- Wrap execution in
executeToolWithMetrics() for observability
- Tool results are sent to the LLM — keep payloads concise (truncate large results)
- Check OpenAI docs MCP for any SDK changes to the
tool() helper before generating code
1---2name: add-tool3description: Create or modify an agent tool — use when asked to add a new capability to an agent, build a search/retrieval/analysis/API integration tool, or wire a tool into an existing agent.4metadata:5 source: https://skillmd.com/skills/joshuashepherd/add-tool6---78Create or modify an agent tool: $ARGUMENTS910## Before Starting11121. Search OpenAI docs for latest tool patterns:13 - Use `mcp__openai-docs__search_openai_docs` with query "Agents SDK tool definition" for current `tool()` helper signature14 - Use `mcp__openai-docs__search_openai_docs` with query "Agents SDK function tools parameters" for parameter schema patterns152. Read existing tool implementations:16 - `{{PROJECT_ROOT}}/{{AGENTS_DIR}}/ai-lab/tools/base.ts` — search_books, file_search tools with caching + metrics17 - `{{PROJECT_ROOT}}/{{AGENTS_DIR}}/seo-expert/tools.ts` — 9-tool suite (analyze, research, score, optimize, generate)18 - `{{PROJECT_ROOT}}/{{AGENTS_DIR}}/ai-lab/tools/utils.ts` — `executeToolWithMetrics()`, timeout constants193. Read the shared tool infrastructure:20 - `{{PROJECT_ROOT}}/src/services/toolCacheService.ts` — param-based LRU caching with TTL2122## Tool Template2324```typescript25import { tool } from '@openai/agents';26import { z } from 'zod';27import type { RunContext } from '@openai/agents';2829export const myTool = tool({30 name: 'my_tool',31 description: 'Clear, specific description of what this tool does and when the agent should use it.',32 parameters: z.object({33 query: z.string().describe('What to search for'),34 maxResults: z.number().optional().default(5).describe('Maximum results to return'),35 }),36 strict: true,37 execute: async (params, context?: RunContext<MyContext>) => {38 // 1. Check cache (if applicable)39 const cacheKey = `my_tool:${params.query}`;40 const cached = await toolCacheService.get(cacheKey);41 if (cached) return cached;4243 // 2. Execute with metrics and timeout44 const { result } = await executeToolWithMetrics('my_tool', async () => {45 // Tool implementation here46 return { data: 'result' };47 }, TOOL_TIMEOUTS.MEDIUM);4849 // 3. Cache result50 toolCacheService.set(cacheKey, result).catch(() => {});5152 return result;53 },54});55```5657## Patterns by Tool Type5859### Search / Retrieval Tools60- Return structured results with title, snippet, url/slug, relevance score61- Always include a `maxResults` parameter with sensible default62- Gracefully degrade when external service is unavailable (return empty array, not error)63- Add citation metadata when results reference source material6465### Analysis / Computation Tools66- Accept content as string input67- Return structured analysis object (scores, categories, suggestions)68- Include confidence scores where applicable69- Keep descriptions prescriptive so the agent knows when to invoke7071### API Integration Tools72- Validate API keys exist before calling73- Set appropriate timeouts (TOOL_TIMEOUTS: SHORT=5s, MEDIUM=15s, LONG=30s)74- Return user-friendly error messages, not raw API errors75- Never expose API keys in tool results7677### Database Query Tools78- Use the service layer (never raw SQL in tools)79- Scope by `organizationId` from context for multi-tenant safety80- Return only fields the agent needs, not entire rows8182## Registration8384After creating the tool, register it with the target agent:8586**Static registration** (simple agents):87```typescript88// In the agent's index.ts89import { myTool } from './tools';90export const myAgent = new Agent({91 tools: [myTool, existingTool1],92});93```9495**Dynamic registration** (function-based agents):96```typescript97// In the agent's tools/index.ts98export function getToolsForConfiguration(context: RunContext<MyContext>): Tool[] {99 const tools = [...getBaseTools()];100 if (context.context.someCondition) {101 tools.push(myTool);102 }103 return tools;104}105```106107## Rules108109- Tool names must be snake_case110- Descriptions should tell the agent WHEN to use the tool, not just what it does111- Parameters must use Zod schemas with `.describe()` on every field112- Always handle errors gracefully — return error objects, never throw113- Cache results when the tool calls external services114- Wrap execution in `executeToolWithMetrics()` for observability115- Tool results are sent to the LLM — keep payloads concise (truncate large results)116- Check OpenAI docs MCP for any SDK changes to the `tool()` helper before generating code