DEV Community

Cover image for Building Strands Agents with a few lines of code: Custom Tools and MCP Integration
Elizabeth Fuentes L for AWS

Posted on • Edited on • Originally published at builder.aws.com

Building Strands Agents with a few lines of code: Custom Tools and MCP Integration

🇻🇪🇨🇱 Dev.to Linkedin GitHub Twitter Instagram Youtube
Linktr

Getting Started with Strands Agents: Build Your First AI Agent - FREE course

GitHub repository

Discover how to create agents that can interact with your development environment using custom tools and Model Context Protocol (MCP) and with the Strands Agents.

In this post, you'll learn how to empowering agents with tools that allow them to interact with external systems, access data, and how to implement the Model Context Protocol (MCP) as a mechanism for extending agent capabilities.

Let's start building

Before diving into the implementation, let's set up the necessary dependencies and configuration.

Prerequisites

  1. Clone the repository:
git clone https://github.com/elizabethfuentes12/strands-agent-samples
cd notebook
Enter fullscreen mode Exit fullscreen mode
  1. Create and activate a virtual environment:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
Enter fullscreen mode Exit fullscreen mode
  1. Install required dependencies:
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

🌦️☀️ Building a Weather Agent

Strands agents offer an Example Tools Package. You can also create custom tools similar to MCP implementation, but without the need to run a dedicated server.

To create the weather agent, we use the http_request tool. This tool connects Strands agents with external web services and APIs, bridging conversational AI with data sources. The tool supports multiple HTTP methods (GET, POST, PUT, DELETE), handles URL encoding and response parsing, and returns structured data from web sources.

weather_agent

from strands import Agent
from strands_tools import http_request
from strands.models.anthropic import AnthropicModel
import os

# Define a weather-focused system prompt
WEATHER_SYSTEM_PROMPT = """You are a weather assistant with HTTP capabilities. You can:

1. Make HTTP requests to the National Weather Service API
2. Process and display weather forecast data
3. Provide weather information for locations in the United States

When retrieving weather information:
1. First get the coordinates or grid information using https://api.weather.gov/points/{latitude},{longitude} or https://api.weather.gov/points/{zipcode}
2. Then use the returned forecast URL to get the actual forecast

When displaying responses:
- Format weather data in a human-readable way
- Highlight important information like temperature, precipitation, and alerts
- Handle errors appropriately
- Convert technical terms to user-friendly language

Always explain the weather conditions clearly and provide context for the forecast.
"""

model = AnthropicModel(
    client_args={
         "api_key": api_key #os.getenv("api_key") #Here your credentials
    },
    # **model_config
    max_tokens=1028,
    model_id="claude-sonnet-4-20250514",
    params={
        "temperature": 0.7,
    }
)

# Create an agent with HTTP capabilities
weather_agent = Agent(
    model = model,
    system_prompt=WEATHER_SYSTEM_PROMPT,
    tools=[http_request],  # Explicitly enable http_request tool
)
Enter fullscreen mode Exit fullscreen mode

✅ Test the Weather agent

response = weather_agent("What's the weather like in Seattle?")
Enter fullscreen mode Exit fullscreen mode

🌦️☀️ Building a Weather Agent Weather agent with a custom tool (Python Tool)

One of the strengths of the Strands framework is the ability to create custom tools that extend agent capabilities.

weather_agent_tool

from strands import Agent
from strands_tools import http_request
from strands.models.anthropic import AnthropicModel
from strands.tools import tool
from typing import Dict, Any

# Define a function to convert Fahrenheit to Celsius
@tool
def fahrenheit_to_celsius(params: Dict[str, Any]) -> Dict[str, Any]:
    """
    Convert temperature from Fahrenheit to Celsius.

    Args:
        params: A dictionary containing:
            - fahrenheit: The temperature in Fahrenheit to convert

    Returns:
        A dictionary containing:
            - celsius: The temperature in Celsius
            - original_fahrenheit: The original Fahrenheit value
    """
    try:
        fahrenheit = float(params.get("fahrenheit"))
        celsius = (fahrenheit - 32) * 5/9
        return {
            "celsius": round(celsius, 2),
            "original_fahrenheit": fahrenheit
        }
    except (TypeError, ValueError):
        return {
            "error": "Invalid input. Please provide a valid number for fahrenheit."
        }


# Define a weather-focused system prompt
WEATHER_SYSTEM_PROMPT_C_TOOL = """You are a weather assistant with HTTP capabilities. You can:

1. Make HTTP requests to the National Weather Service API
2. Process and display weather forecast data
3. Provide weather information for locations in the United States
4. Use fahrenheit_to_celsius to convert temperatures between Fahrenheit and Celsius

When retrieving weather information:
1. First get the coordinates or grid information using https://api.weather.gov/points/{latitude},{longitude} or https://api.weather.gov/points/{zipcode}
2. Then use the returned forecast URL to get the actual forecast

When displaying responses:
- Format weather data in a human-readable way
- Highlight important information like temperature, precipitation, and alerts
- Handle errors appropriately
- Convert technical terms to user-friendly language

Always explain the weather conditions clearly and provide context for the forecast.
"""

model = AnthropicModel(
    client_args={
        "api_key": api_key, #Here your credentials
    },
    # **model_config
    max_tokens=1028,
    model_id="claude-sonnet-4-20250514",
    params={
        "temperature": 0.7,
    }
)

# Create an agent with HTTP capabilities
weather_agent_c_tool = Agent(
    model = model,
    system_prompt=WEATHER_SYSTEM_PROMPT_C_TOOL,
    tools=[http_request,fahrenheit_to_celsius],  # Explicitly enable http_request tool
)
Enter fullscreen mode Exit fullscreen mode

✅ Test the Weather agent

response_c_tool = weather_agent_c_tool("What is the weather like in Seattle? Please give me the answer in degrees Celsius")
Enter fullscreen mode Exit fullscreen mode

Let's create a Calculator MCP server.

In this section, we will do a walkthrough of selected code blocks, that have been used to build mcp_calculator.py to create a simple MCP server that provides limited calculator functionality.

calculator

The Model Context Protocol (MCP)

The Model Context Protocol (MCP) is an open protocol that standardized way to expose and consume tools across different systems.

This approach is ideal for creating reusable tool collections that can be shared across multiple agents or applications.

You can create your own MCP server to extend agent capabilities.

mcp

MCP Architecture Components

  • MCP Client: Integrated in Strands Agent Framework

  • MCP Server: Independent service hosting tools

  • MCP Tools: Specific functionalities (calculator, weather, etc.)

✅ Create the MCP server

from mcp.server import FastMCP

mcp = FastMCP("Calculator Server")

@mcp.tool(description="Add two numbers together")
def add(x: int, y: int) -> int:
"""Add two numbers and return the result."""
    return x + y

# Define a subtraction tool
@mcp.tool(description="Subtract one number from another")
def subtract(x: int, y: int) -> int:
        """Subtract y from x and return the result.

        Args:
            x: Number to subtract from
            y: Number to subtract

        Returns:
            The difference (x - y)
        """
    return x - y

# Define a multiplication tool
@mcp.tool(description="Multiply two numbers together")
def multiply(x: int, y: int) -> int:
        """Multiply two numbers and return the result.

        Args:
            x: First number
            y: Second number

        Returns:
            The product of x and y
        """
    return x * y

# Define a division tool
@mcp.tool(description="Divide one number by another")
def divide(x: float, y: float) -> float:
        """Divide x by y and return the result.

        Args:
            x: Numerator
            y: Denominator (must not be zero)

        Returns:
            The quotient (x / y)

        Raises:
            ValueError: If y is zero
        """
    if y == 0:
        raise ValueError("Cannot divide by zero")
    return x / y
Enter fullscreen mode Exit fullscreen mode

mcp_calculator.py uses Streamable HTTP as MCP Server Connection

mcp.run(transport="streamable-http")
Enter fullscreen mode Exit fullscreen mode

✅ Connecting the server to the Strands Agent

The following code shows how to create a Strands agent, and connect it to a MCP server:

from mcp.client.streamable_http import streamablehttp_client
from strands import Agent
from strands.tools.mcp.mcp_client import MCPClient
from strands.models.anthropic import AnthropicModel

model = AnthropicModel(
    client_args={
        "api_key": "<KEY>", #Here your credentials
    },
    # **model_config
    max_tokens=1028,
    model_id="claude-sonnet-4-20250514",
    params={
        "temperature": 0.7,
    }
)
    # Create a system prompt that explains the calculator capabilities
    system_prompt = """
    You are a helpful calculator assistant that can perform basic arithmetic operations.
    You have access to the following calculator tools:
    - add: Add two numbers together
    - subtract: Subtract one number from another
    - multiply: Multiply two numbers together
    - divide: Divide one number by another

    When asked to perform calculations, use the appropriate tool rather than calculating the result yourself.
    Explain the calculation and show the result clearly.
    """

def create_streamable_http_transport():
   return streamablehttp_client("http://localhost:8000/mcp/")

streamable_http_mcp_client = MCPClient(create_streamable_http_transport)

# Use the MCP server in a context manager
with streamable_http_mcp_client:
    # Get the tools from the MCP server
    tools = streamable_http_mcp_client.list_tools_sync()

    # Create an agent with the MCP tools
    agent = Agent(model=model,system_prompt=system_prompt,tools=tools)

Enter fullscreen mode Exit fullscreen mode

✅ Test the calculator agent

Go to the terminal and run the app


python3 mcp_calulator.py

Enter fullscreen mode Exit fullscreen mode

calculator

Best Practices

When building agents with MCP and custom tools, consider these best practices:

  1. Security First: Only grant access to necessary directories and resources
  2. Error Handling: Implement robust error handling in custom tools
  3. Resource Management: Monitor resource usage when processing large files
  4. Tool Composition: Design tools to work well together
  5. Documentation: Provide clear descriptions for all custom tools

What's Next?

This isn't everything I have for you! This is part of my ongoing series exploring the capabilities of Strands Agents, where I show you how to build powerful applications with just a few lines of code.

In upcoming posts, I'll demonstrate:

  • Strands Agents and Agent-to-Agent (A2A)
  • 🔍📊Observability with LangFuse and Evaluation with RAGAS

Stay tuned for more Strands Agent implementations!

Resources

Thanks for reading!


Gracias!

🇻🇪🇨🇱 Dev.to Linkedin GitHub Twitter Instagram Youtube
Linktr

Top comments (1)

Collapse
 
ensamblador profile image
ensamblador

wow a calculator 🤣
Jokes aside, this is a great tutorial, keep posting this kind of content.