### Define and Use a Tool with Python Agent Source: https://www.strands-agents.com Define a custom tool for searching logs and then create an agent that utilizes this tool. This example shows the basic setup for agent interaction. ```python from strands import Agent, tool @tool def search_logs(query: str, hours: int = 24) -> list: """Search application logs by keyword.""" return log_api.search(query, hours) agent = Agent( tools=[search_logs], ) agent("Find all timeout errors from the last 6 hours") ``` -------------------------------- ### Implement Query Quality Steering Handler Source: https://www.strands-agents.com Use a `SteeringHandler` to guide agent behavior before tool execution. This example enforces query quality by checking for WHERE clauses and limiting joins. ```python from strands.vended_plugins.steering import ( SteeringHandler, Guide, Proceed, ) class QueryQualityPolicy(SteeringHandler): async def steer_before_tool( self, *, agent, tool_use, **kwargs ): sql = tool_use["input"].get("query", "").upper() if "SELECT" in sql and "WHERE" not in sql: return Guide( reason="Add a WHERE clause and LIMIT." ) if sql.upper().count("JOIN") > 3: return Guide( reason="4+ joins. Break into smaller queries." ) return Proceed(reason="Query looks good.") agent = Agent( tools=[query_database], plugins=[QueryQualityPolicy()], ) ``` -------------------------------- ### Define and Use a Tool with TypeScript Agent Source: https://www.strands-agents.com Define a custom tool for searching logs using Zod for schema validation and then create an agent that utilizes this tool in TypeScript. This example shows the basic setup for agent interaction. ```typescript import { Agent, tool } from '@strands-agents/sdk' import z from 'zod' const searchLogs = tool({ name: 'search_logs', description: 'Search logs by keyword.', inputSchema: z.object({ query: z.string(), hours: z.number().default(24), }), callback: ({ query, hours }) => logApi.search(query, hours), }) const agent = new Agent({ tools: [searchLogs] }) await agent.invoke( 'Find all timeout errors from the last 6 hours' ) ``` -------------------------------- ### TypeScript Daily Briefing Agent Source: https://www.strands-agents.com This TypeScript snippet shows how to build a research agent that generates a daily briefing on AI agent frameworks. It utilizes Zod for schema definition and the `httpRequest` tool for web searches, similar to the Python example. ```typescript import { Agent } from '@strands-agents/sdk' import { httpRequest } from '@strands-agents/tools' import z from 'zod' import { writeFileSync } from 'fs' const BriefingSchema = z.object({ headline: z.string().describe('Summary'), developments: z.array(z.string()) .describe('Key developments'), sources: z.array(z.string()) .describe('URLs consulted'), }) const agent = new Agent({ systemPrompt: 'Research assistant. ' + 'Search the web. Cite sources.', tools: [httpRequest], }) const result = await agent.invoke( 'AI agent frameworks: what happened yesterday?', { structuredOutputSchema: BriefingSchema }, ) const briefing = result.structuredOutput writeFileSync('briefings/daily.md', `# ${briefing.headline}\n\n` + briefing.developments .map((d: string) => `- ${d}`) .join('\n') ) ``` -------------------------------- ### Classify and Route Leads with Python Agent Source: https://www.strands-agents.com This Python snippet defines tools for classifying leads based on email and company, and routing them to the appropriate sales rep. It then instantiates an agent with these tools and invokes it to process a new lead. ```python from strands import Agent, tool @tool def classify_lead(email: str, company: str) -> dict: """Score and classify an inbound lead.""" firmographics = crm.lookup(company) return { "score": compute_icp_score(firmographics), "segment": firmographics["industry"], } @tool def route_to_rep(lead_id: str, region: str) -> str: """Assign a lead to the right sales rep.""" rep = crm.get_rep_for_region(region) crm.assign(lead_id, rep) return f"Assigned to {rep}" agent = Agent( tools=[classify_lead, route_to_rep], ) agent("New lead: jane@acme.com, Acme Corp, US-West") ``` -------------------------------- ### Generic MCP server configuration Source: https://www.strands-agents.com This JSON snippet represents a general MCP server configuration, likely for a `mcp.json` file, to set up the `strands-agents` server using the `uvx` command. ```json { "servers": { "strands-agents": { "command": "uvx", "args": ["strands-agents-mcp-server"] } } } ``` -------------------------------- ### Python Daily Briefing Agent Source: https://www.strands-agents.com This Python snippet demonstrates how to create a research agent that fetches daily developments in AI agent frameworks and outputs a structured briefing. It uses Pydantic for defining the output schema and the `http_request` tool for web searching. ```python from pydantic import BaseModel, Field from strands import Agent from strands_tools import http_request from pathlib import Path class Briefing(BaseModel): headline: str = Field(description="One-line summary") developments: list[str] = Field( description="Key developments" ) sources: list[str] = Field( description="URLs consulted" ) agent = Agent( system_prompt="Research assistant. Search the web, " "find developments from the last 24 hours, " "and produce a briefing with citations.", tools=[http_request], ) result = agent( "What happened in AI agent frameworks yesterday?", structured_output_model=Briefing, ) briefing = result.structured_output Path("briefings/daily.md").write_text( f"# {briefing.headline}\n\n" \ + "\n".join(f"- {d}" for d in briefing.developments) ) ``` -------------------------------- ### Cursor IDE MCP server configuration Source: https://www.strands-agents.com This JSON configuration snippet is for the Cursor IDE's `mcp.json` file. It sets up the `strands-agents` MCP server to use the `uvx` command. ```json { "mcpServers": { "strands-agents": { "command": "uvx", "args": ["strands-agents-mcp-server"] } } } ``` -------------------------------- ### Python Support Agent with Refund Approval Source: https://www.strands-agents.com This Python snippet shows how to create a support agent that uses a knowledge base and requires human approval for refund operations. It utilizes Strands' tool and hook system for custom logic. ```python from strands import Agent, tool from strands.tools.mcp import MCPClient from strands.hooks import BeforeToolCallEvent from strands.agent import SlidingWindowConversationManager from mcp import stdio_client, StdioServerParameters kb = MCPClient(lambda: stdio_client( StdioServerParameters(command="uvx", args=["kb-server"]) )) @tool def issue_refund(order_id: str, amount: float) -> str: """Process a customer refund.""" return payments.refund(order_id, amount) def approve_refunds(event: BeforeToolCallEvent): """Pause for human approval before processing refunds.""" if event.tool_use["name"] == "issue_refund": response = event.interrupt( "refund_approval", reason=event.tool_use["input"] ) if response != "APPROVE": event.cancel_tool = "Refund not approved." agent = Agent( system_prompt="Support assistant. Use the KB. " "Refunds require approval.", tools=[kb, issue_refund], hooks=[approve_refunds], conversation_manager=SlidingWindowConversationManager( window_size=20 ), ) ``` -------------------------------- ### Python Agent with Save Report Tool and Source Citation Hook Source: https://www.strands-agents.com This Python snippet demonstrates how to define a custom tool `save_report` and a hook `require_sources` that ensures the tool includes source citations. It then initializes an `Agent` with these components and invokes it to research AI agent frameworks. ```python from strands import Agent, tool from strands.hooks import BeforeToolCallEvent from pathlib import Path @tool def save_report(title: str, content: str) -> str: """Save a research report to disk.""" path = f"reports/{title}.md" Path(path).write_text(content) return f"Saved {path}" def require_sources(event: BeforeToolCallEvent): name = event.tool_use["name"] inp = str(event.tool_use["input"]) if name == "save_report" and "[source]" not in inp: event.cancel_tool = "Add source citations." agent = Agent( tools=[save_report], hooks=[require_sources], ) agent("Research AI agent frameworks") ``` -------------------------------- ### Kiro IDE MCP server configuration Source: https://www.strands-agents.com This JSON configuration is for Kiro IDE's `mcp.json` file, enabling the `strands-agents` MCP server with specific auto-approval settings for documentation-related actions. ```json { "mcpServers": { "strands-agents": { "command": "uvx", "args": ["strands-agents-mcp-server"], "disabled": false, "autoApprove": ["search_docs", "fetch_doc"] } } } ``` -------------------------------- ### Agent with Summarizing Conversation Manager in Python Source: https://www.strands-agents.com Instantiate an agent with a SummarizingConversationManager to enable automatic summarization of conversations. This enhances context management for longer interactions. ```python from strands.agent import SummarizingConversationManager # Same agent, now with summarization. agent = Agent( tools=[search_logs], conversation_manager=SummarizingConversationManager(), ) ``` -------------------------------- ### TypeScript Support Agent with Refund Cancellation Source: https://www.strands-agents.com This TypeScript snippet demonstrates creating a support agent with a knowledge base and a mechanism to cancel refund operations. It uses the Strands SDK for TypeScript. ```typescript import { Agent, tool, McpClient, BeforeToolCallEvent, SlidingWindowConversationManager, } from '@strands-agents/sdk' import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js' import z from 'zod' const kb = new McpClient({ transport: new StdioClientTransport({ command: 'npx', args: ['kb-server'], }), }) const issueRefund = tool({ name: 'issue_refund', description: 'Process a refund.', inputSchema: z.object({ orderId: z.string(), amount: z.number(), }), callback: ({ orderId, amount }) => payments.refund(orderId, amount), }) const agent = new Agent({ systemPrompt: 'Support assistant. ' + 'Use KB. Refunds require approval.', tools: [kb, issueRefund], conversationManager: new SlidingWindowConversationManager({ windowSize: 20, }), }) // Cancel refunds (interrupt coming soon to TS) agent.addHook(BeforeToolCallEvent, (event) => { if (event.toolUse.name === 'issue_refund') { event.cancel = 'Refund approval required.' } }) ``` -------------------------------- ### Log Tool Calls in Python Source: https://www.strands-agents.com This Python snippet demonstrates how to define a hook function to log the name of a tool and the status of its result after a tool call. It's useful for debugging and monitoring agent execution. ```python from strands import Agent from strands.hooks import AfterToolCallEvent def log_tool_calls(event: AfterToolCallEvent): """Log every tool call.""" print(f"Tool: {event.tool_use['name']}") print(f"Result: {event.result['status']}") agent = Agent( tools=[search_logs, query_database], hooks=[log_tool_calls], trace_attributes={ "service": "ops-agent", "env": "production", }, ) ``` -------------------------------- ### Implement Read-Only Guard for Agents Source: https://www.strands-agents.com Use a `BeforeToolCallEvent` hook to block write operations on a database. This is useful for agents that should only read data. ```python from strands import Agent from strands.hooks import BeforeToolCallEvent WRITE_OPS = ["INSERT", "UPDATE", "DELETE", "DROP"] def read_only_guard(event: BeforeToolCallEvent): """Block writes. This agent is read-only.""" if event.tool_use["name"] == "query_database": sql = event.tool_use["input"].get("query", "") if any(kw in sql.upper() for kw in WRITE_OPS): event.cancel_tool = "Read-only access." agent = Agent( tools=[query_database], hooks=[read_only_guard], ) ``` -------------------------------- ### Classify and Route Leads with TypeScript Agent Source: https://www.strands-agents.com This TypeScript snippet defines tools for classifying leads and routing them to sales reps using the Strands Agents SDK. It utilizes Zod for input validation and demonstrates agent invocation for lead processing. ```typescript import { Agent, tool } from '@strands-agents/sdk' import z from 'zod' const classifyLead = tool({ name: 'classify_lead', description: 'Score and classify a lead.', inputSchema: z.object({ email: z.string(), company: z.string(), }), callback: ({ email, company }) => { const data = crm.lookup(company) return { score: computeIcpScore(data), segment: data.industry, } }, }) const routeToRep = tool({ name: 'route_to_rep', description: 'Assign a lead to a rep.', inputSchema: z.object({ leadId: z.string(), region: z.string(), }), callback: ({ leadId, region }) => { const rep = crm.getRepForRegion(region) crm.assign(leadId, rep) return `Assigned to ${rep}` }, }) const agent = new Agent({ tools: [classifyLead, routeToRep], }) await agent.invoke( 'New lead: jane@acme.com, Acme Corp, US-West' ) ``` -------------------------------- ### Agent with Summarizing Conversation Manager in TypeScript Source: https://www.strands-agents.com Instantiate an agent with a SummarizingConversationManager in TypeScript to enable automatic summarization of conversations. This enhances context management for longer interactions. ```typescript import { SummarizingConversationManager, } from '@strands-agents/sdk' // Same agent, now with summarization. const agent = new Agent({ tools: [searchLogs], conversationManager: new SummarizingConversationManager(), }) ``` -------------------------------- ### TypeScript Agent with Save Report Tool and Source Citation Hook Source: https://www.strands-agents.com This TypeScript snippet shows how to define a custom tool `save_report` using the Strands SDK and implement a hook `BeforeToolCallEvent` to enforce source citations. It initializes an `Agent` and invokes it to research AI agent frameworks. ```typescript import { Agent, tool, BeforeToolCallEvent } from '@strands-agents/sdk' import z from 'zod' import { writeFileSync } from 'fs' const saveReport = tool({ name: 'save_report', description: 'Save a research report.', inputSchema: z.object({ title: z.string(), content: z.string(), }), callback: ({ title, content }) => { writeFileSync(`reports/${title}.md`, content) return `Saved ${title}.md` }, }) const agent = new Agent({ tools: [saveReport] }) agent.addHook(BeforeToolCallEvent, (event) => { const inp = String(event.toolUse.input) if (event.toolUse.name === 'save_report') { if (!inp.includes('[source]')) { event.cancel = 'Add source citations.' } } }) await agent.invoke('Research AI agent frameworks') ``` -------------------------------- ### Terminal command to add Strands Agents MCP server Source: https://www.strands-agents.com This command-line instruction adds the Strands Agents MCP server using `claude mcp add`. It's used for integrating the Strands Agents toolkit with your development environment. ```bash claude mcp add strands uvx strands-agents-mcp-server ``` -------------------------------- ### Log Tool Calls in TypeScript Source: https://www.strands-agents.com This TypeScript snippet shows how to add a hook to an agent to log the tool name and result status. This is beneficial for observing agent interactions with tools in a JavaScript/TypeScript environment. ```typescript import { Agent, AfterToolCallEvent, } from '@strands-agents/sdk' const agent = new Agent({ tools: [searchLogs, queryDatabase], traceAttributes: { service: 'ops-agent', env: 'production', }, }) agent.addHook(AfterToolCallEvent, (event) => { console.log(`Tool: ${event.toolUse.name}`) console.log(`Status: ${event.result.status}`) }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.