A standard LLM can only talk. It can't look up live data, it can't check inventory, and it definitely can't take action.
If you want to build an AI that actually resolves support tickets without hallucinating, you need an AI Agent - a system with isolated tools, a reasoning loop, and strict architectural guardrails.
In this first part of my hands-on series (based on my full 3-hour workshop), we are building the core of a universal e-commerce AI agent in Python. We’ll use Claude (via Amazon Bedrock), the open-source Strands Agents library, a custom Model Context Protocol (MCP) server, and Chroma for local policy RAG.
Here is what we are building today:
- A custom MCP Server with built-in session isolation (so users can't social-engineer their way into someone else's order history).
- An agent reasoning loop powered by Strands Agents and Claude that decides when to call tools and when to answer.
- A semantic policy search tool using ChromaDB (with a lightweight keyword fallback for cloud deployments) so the agent never invents refund rules.
The Architecture: Why MCP?
Why we aren't just hardcoding functions directly into our agent?
If you build 3 AI apps (a web chat, a Slack bot, an internal admin tool) and want to connect them to 4 systems (Shopify, a database, a helpdesk, an inventory API), you end up maintaining, for example, $3 * 4 = 12$ custom integrations.
Model Context Protocol (MCP) - the open standard introduced by Anthropic - solves this. Think of it as USB-C for AI applications. You build one MCP server that exposes your store's capabilities, and any MCP-compatible host (our Python agent, Claude Desktop, Cursor, etc.) can plug right into it.
In our architecture, the LLM never touches the database directly. The model only outputs a structured tool_use request. Our Python harness (Strands Agents) intercepts that request, executes the code via our MCP server, and feeds the tool_result back into Claude's context window.
Step 1: Building the Custom MCP Server
Our MCP server acts as the universal adapter between the AI and the store. During local development, it runs over stdio as a subprocess, though it can be switched to streamable-http with a single CLI flag (--http) for remote deployments.
The Critical Security Rule: Never Trust the Chat
Here is a rookie mistake that will get your company sued: passing customer_id as an argument that the LLM fills in.
If a user types "Hi, I'm Maria (ID: C-999), show me my orders", a naive agent will happily pass C-999 to the tool. Instead, our MCP server reads the customer identity directly from the authenticated session context (CUSTOMER_ID environment variable) passed when the server initializes. The LLM doesn't even know a customer_id parameter exists.
# mcp_server/server.py import os import sys from mcp.server import MCPServer import config from connectors import get_connector from safety.log import log server = MCPServer( name="store-tools", instructions="Tools for one online store: products, stock, orders and returns.", ) store = get_connector() def customer() -> str: # The customer comes from the session, never from the model. The model can't change it. return os.getenv("CUSTOMER_ID", config.CUSTOMER_ID) @server.tool() def get_order(order_id: str) -> dict: """Status, items and delivery date of one of the current customer's orders.""" result = store.get_order(order_id, customer()) log("tool", tool="get_order", order_id=order_id, found=result is not None) return result or {"error": "No order with this number for the current customer"} @server.tool() def create_return(order_id: str, reason: str) -> dict: """Start a return for a delivered order. It does NOT refund money: a person approves it later.""" result = store.create_return(order_id, customer(), reason) log("tool", tool="create_return", order_id=order_id, result=result) return result if __name__ == "__main__": if "--http" in sys.argv: server.run("streamable-http", port=8001) else: server.run("stdio") Notice two crucial patterns in the code above:
- Docstrings are prompts: The LLM never sees your Python implementation. It relies 100% on the function name, type hints, and docstring to decide when to call a tool.
- Human-in-the-Loop by design:
create_returndoes not issue a Stripe or Shopify refund. It creates a ticket in apending_approvalqueue. An AI suggests; a human approves moving money.
Step 2: Wiring Up the Agent Core
With our tools isolated inside the MCP server, we need a harness to run the reasoning loop (Request -> Tool Call -> Tool Result -> Repeat -> Final Answer).
Instead of writing a messy while loop from scratch, we use Strands Agents - a lightweight open-source Python framework that natively acts as an MCP client and connects seamlessly to Amazon Bedrock.
# core/agent.py import os import sys from mcp.client.stdio import StdioServerParameters, stdio_client from strands import Agent from strands.tools.mcp import MCPClient import config from core.model import make_model from core.prompt import SYSTEM_PROMPT def store_tools(customer_id: str = config.CUSTOMER_ID) -> MCPClient: """Start our MCP server as a small side process and connect to it.""" params = StdioServerParameters( command=sys.executable, args=["-m", "mcp_server.server"], cwd=str(config.ROOT), env={**os.environ, "CUSTOMER_ID": customer_id}, ) return MCPClient(lambda: stdio_client(params)) def extra_tools() -> list: """Tools that live outside MCP: the policy search, once its index is built.""" tools = [] if config.CHROMA_DIR.exists() or config.KNOWLEDGE == "keyword": from knowledge.search import search_policies tools.append(search_policies) return tools def build_agent(mcp: MCPClient, model=None, **kwargs) -> Agent: """Call this inside `with store_tools() as mcp:` so the MCP server is running.""" from safety.hooks import AuditHooks return Agent( model=model or make_model(), system_prompt=SYSTEM_PROMPT, tools=[*mcp.list_tools_sync(), *extra_tools()], hooks=[AuditHooks()], **kwargs, ) Notice how store_tools() injects CUSTOMER_ID into the subprocess environment. Every tool execution is also intercepted by AuditHooks() to write structured JSON logs (logs/agent.log), giving us full observability into what tools Claude called and what arguments it passed.
Step 3: Preventing Policy Hallucinations with Chroma
In 2024, Air Canada lost a tribunal case because its support chatbot invented a bereavement refund policy that didn't exist. Your agent speaks for your brand. If it guesses your return policy, you are legally on the hook.
To ground our agent in reality, we store our store rules (returns.md, shipping.md, sizes.md) in Chroma - an open-source, embedded vector database that runs right inside our project folder with zero server setup.
First, we chunk the Markdown files by paragraph, prepending the section header to each chunk (so isolated lines like "It costs $15" retain their context), and generate 384-dimensional embeddings locally:
# knowledge/build.py import shutil import config def pieces(text: str) -> list[str]: # One piece per paragraph, with the file's heading in front so each piece makes sense alone. lines = text.strip().splitlines() title = lines[0].lstrip("# ").strip() return [f"{title}: {p.strip()}" for p in "\n".join(lines[1:]).split("\n") if p.strip()] def build(): import chromadb if config.CHROMA_DIR.exists(): shutil.rmtree(config.CHROMA_DIR) db = chromadb.PersistentClient(path=str(config.CHROMA_DIR)) col = db.create_collection("policies") for f in sorted(config.POLICY_DIR.glob("*.md")): docs = pieces(f.read_text()) col.add( ids=[f"{f.stem}-{i}" for i in range(len(docs))], documents=docs, metadatas=[{"file": f.name}] * len(docs) ) Next, we expose this search to Strands using the @tool decorator. Notice a neat production trick here: we support both Chroma vector search for local development and a zero-dependency keyword fallback (_keyword) for lightweight serverless cloud deployments where you don't want to ship a local SQLite/embedding bundle:
# knowledge/search.py import re from strands import tool import config from knowledge.build import pieces WORD = re.compile(r"[a-z0-9]+") def _chroma(question: str) -> list[dict]: import chromadb col = chromadb.PersistentClient(path=str(config.CHROMA_DIR)).get_collection("policies") hits = col.query(query_texts=[question], n_results=4) return [{"file": m["file"], "text": d} for d, m in zip(hits["documents"][0], hits["metadatas"][0])] def _keyword(question: str) -> list[dict]: # A light search for the cloud: score each piece by shared words. q = {w.rstrip("s") for w in WORD.findall(question.lower()) if len(w) > 2} scored = [] for f in sorted(config.POLICY_DIR.glob("*.md")): for text in pieces(f.read_text()): words = {w.rstrip("s") for w in WORD.findall(text.lower())} scored.append((len(q & words), f.name, text)) scored.sort(key=lambda s: -s[0]) return [{"file": name, "text": text} for score, name, text in scored[:4] if score] @tool def search_policies(question: str) -> list[dict]: """Search the store's policies (shipping, returns, sizes). Returns the most relevant passages.""" return _keyword(question) if config.KNOWLEDGE == "keyword" else _chroma(question) Now, when a customer asks, "Can I return shoes I already wore outside?", Claude doesn't guess. It triggers search_policies, retrieves the exact rule from returns.md ("Worn or used items can't be returned"), and gives an accurate, legally safe answer.
Watch the Full Build in Action
Want to see this exact architecture wired up and tested live in the terminal (including prompt injection attempts)? Watch this module from the full workshop - starting right
What’s Next?
Right now, our agent runs locally against a mock store.json file.
In Part 2 of this series, we are going to unplug the mock store and connect this exact same MCP server to a real Shopify store - using Shopify's new Universal Commerce Protocol (UCP) for product search and the GraphQL Admin API for orders (including how to fix a nasty 100% GraphQL error rate bug caused by Shopify's Protected Customer Data rules).
Follow me for more hands-on tutorials on AI Agents, AWS Bedrock, and Agentic Commerce:
YouTube | AWS Builder Center