Connect an LLM to Your Own MCP Server: A Hands-On Tutorial with Amazon Bedrock and Python
Build a small MCP server in Python, then connect it to a foundation model on Amazon Bedrock so the model can discover and call your tools. Includes full code and security tips.
Most MCP articles explain the concept. In this one we'll build it: a tiny MCP server with two tools, and a client that lets a real LLM on Amazon Bedrock discover those tools and call them to answer a question.
What we're building
Your question
|
v
Python client ---- Converse API ----> LLM on Amazon Bedrock
| (decides to call a tool)
| MCP (stdio)
v
MCP server (your tools)The flow:
- The client starts the MCP server and asks which tools it has
- The tool list is passed to the model through Bedrock's Converse API
- The model decides whether it needs a tool and returns the tool name and arguments
- The client runs the tool on the MCP server and sends the result back
- The model writes the final answer
Prerequisites
- Python 3.10+
- An AWS account with model access enabled in Amazon Bedrock for a model that supports tool use
- AWS credentials configured locally (
aws configure)
- Packages:
pip install mcp boto3
Step 1: Create the MCP server
Create
server.py :from mcp.server.fastmcp import FastMCP
mcp = FastMCP("aws-learning-helper")
@mcp.tool()
def estimate_lambda_cost(
requests_per_month: int,
avg_duration_ms: int,
memory_mb: int,
price_per_gb_second: float = 0.0000166667,
price_per_million_requests: float = 0.20,
) -> dict:
"""Estimate monthly AWS Lambda compute cost.
Prices are example values. Pass current prices from the AWS
pricing page for your region for an accurate estimate.
"""
gb_seconds = requests_per_month * (avg_duration_ms / 1000) * (memory_mb / 1024)
compute_cost = gb_seconds * price_per_gb_second
request_cost = (requests_per_month / 1_000_000) * price_per_million_requests
return {
"gb_seconds": round(gb_seconds, 2),
"compute_cost_usd": round(compute_cost, 4),
"request_cost_usd": round(request_cost, 4),
"total_usd": round(compute_cost + request_cost, 4),
}
@mcp.tool()
def study_checklist(topic: str) -> list[str]:
"""Return a short beginner study checklist for a cloud or GenAI topic."""
return [
f"Read the official documentation overview for {topic}",
f"Find the pricing page for {topic} and note what keeps billing",
f"Complete one small hands-on exercise with {topic}",
f"Write down how to clean up everything you created for {topic}",
]
if __name__ == "__main__":
mcp.run(transport="stdio")Three things matter here:
-
@mcp.tool()turns a normal Python function into an MCP tool.
- The function name, type hints, and docstring become the tool's name, input schema, and description. The model chooses tools from these, so write them clearly.
- The server talks over stdio, so never use
print()for debugging inside it. Writing to standard output can corrupt the protocol messages. Log to a file or stderr instead.
Step 2: Create the client that connects the LLM
Create
client.py :import asyncio
import boto3
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
REGION = "us-east-1" # use your region
MODEL_ID = "YOUR_MODEL_ID" # a Bedrock model or inference profile ID that supports tool use
MAX_STEPS = 5 # safety limit on the tool loop
bedrock = boto3.client("bedrock-runtime", region_name=REGION)
server_params = StdioServerParameters(command="python", args=["server.py"])
def to_bedrock_tools(mcp_tools):
"""Convert MCP tool definitions into Bedrock Converse tool specs."""
return {
"tools": [
{
"toolSpec": {
"name": tool.name,
"description": tool.description or "",
"inputSchema": {"json": tool.inputSchema},
}
}
for tool in mcp_tools
]
}
async def ask(session: ClientSession, question: str) -> str:
listed = await session.list_tools()
tool_config = to_bedrock_tools(listed.tools)
messages = [{"role": "user", "content": [{"text": question}]}]
for _ in range(MAX_STEPS):
response = bedrock.converse(
modelId=MODEL_ID,
messages=messages,
toolConfig=tool_config,
)
message = response["output"]["message"]
messages.append(message)
# No tool requested: the model has produced its final answer
if response["stopReason"] != "tool_use":
return "".join(b.get("text", "") for b in message["content"])
# Otherwise run each requested tool through MCP
tool_results = []
for block in message["content"]:
if "toolUse" not in block:
continue
tool_use = block["toolUse"]
print(f"[tool call] {tool_use['name']}({tool_use['input']})")
result = await session.call_tool(tool_use["name"], tool_use["input"])
text = "\n".join(c.text for c in result.content if c.type == "text")
tool_results.append(
{
"toolResult": {
"toolUseId": tool_use["toolUseId"],
"content": [{"text": text}],
}
}
)
messages.append({"role": "user", "content": tool_results})
return "Stopped: too many tool steps."
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
question = (
"My Lambda function runs 2 million times a month, takes 300 ms "
"per run, and uses 512 MB. Estimate the monthly cost, and give "
"me a short study checklist for AWS Lambda."
)
print(await ask(session, question))
if __name__ == "__main__":
asyncio.run(main())Run it:
python client.pyYou should see
[tool call] lines showing the model chose to call your tools, followed by a final answer that uses their results.How the pieces connect
Part | Role |
|---|---|
FastMCP server | Exposes your functions as tools |
session.list_tools() | Discovers what the server offers |
to_bedrock_tools() | Translates MCP tool schemas to the Converse API format |
converse(..., toolConfig=...) | Lets the model see and request tools |
stopReason == "tool_use" | Signals the model wants a tool run |
session.call_tool() | Executes the tool on the MCP server |
toolResult message | Gives the output back to the model |
This is the same agent loop from earlier, with MCP as the standard way to plug in tools. Because your tools live in an MCP server, any MCP-compatible app could reuse them without rewriting the code.
Security habits for tool-using LLMs
- Cap the loop.
MAX_STEPSprevents runaway tool calls and cost.
- Least privilege. If a tool touches AWS resources, give it read-only credentials where possible.
- Approve risky actions. Add a confirmation step before any tool that writes, deletes, or spends money.
- Validate inputs. The model chooses the arguments, so check ranges and types in your tools.
- Treat tool output as untrusted. Text returned from external sources can contain instructions aimed at the model (prompt injection).
- Only run servers you trust. An MCP server runs code on your machine.
- Mind your costs. Every loop iteration is another model call.
Ideas to extend it
- Add a tool that reads a local notes file (read-only)
- Wrap an AWS SDK call, such as listing S3 buckets, with read-only permissions
- Use the Bedrock
converse_streamAPI to show answers as they are generated
- Connect the same server to another MCP-compatible app to see the reuse benefit
- Combine it with a Bedrock Knowledge Base for RAG plus tools
Conclusion
The real power of MCP appears when a model can decide to use your tools on its own. In about 100 lines of Python you built a tool server, exposed it over a standard protocol, and let an LLM on Bedrock use it. The same pattern scales from a toy calculator to real internal systems, as long as you design tools carefully and keep security in mind.
I'm learning GenAI engineering and sharing what I pick up along the way. Feedback and corrections are welcome in the comments.
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article