Part 7, Agent Framework & first MCP-connected agent โ
Knowledge-share outline โ
- What an agent adds beyond a chat completion (instructions + tools + loop).
- The agent-loop mental model (what frameworks like Agent Framework automate): instructions, registered tools, run loop.
- Tool-calling fundamentals: the model decides when to call; you define the contract.
- Connecting tools and MCP capabilities: native function tools vs tools served over MCP.
- Why instructions must define role, boundaries, and escalation, and never hidden behavior.
- The example: an order comes in, and Darryl needs the next action.
- What goes wrong when tool results are ignored or over-trusted (ungrounded answers).
- What you will build and validate in this segment.
At a glance โ
| Start state | End state | Fallback baseline |
|---|---|---|
Your mcp_server.py from Part 6 (or copy it from baseline/06-1-mcp-server.py), no agent in front of it | A first package manager agent that uses the MCP server to investigate an order and propose the next step | baseline/07-1-connected-agent.py |
Learning goals โ
- Explain what an agent adds beyond a single model (chat-completion) call.
- Understand the agent-loop mental model that frameworks like Microsoft Agent Framework automate โ by building the loop yourself.
- Learn tool-calling fundamentals and how to connect an agent to MCP (Model Context Protocol) capabilities.
- Understand why an agent's instructions must define its role, boundaries, and escalation, and why every answer must be validated against tool output.
Agent Framework mental model โ
A plain model call takes text in and returns text out, it cannot look anything up. An agent wraps a model with three things: instructions (its role and boundaries), tools it may call, and a loop that lets it decide when to call a tool, read the result, and answer.
Frameworks like Microsoft Agent Framework package exactly that: you give them instructions, register the tools the agent can use (including tools served by an MCP server), and run it against a question. In this lab you hand-build that loop yourself with the OpenAI SDK and the MCP client, so you see every moving part a framework would otherwise hide: how tools are offered to the model, how the model asks for a call, and how results flow back in. Once you have built the loop once, the framework's abstractions map one-to-one onto what you wrote. (Agent-Framework specifics come from the official documentation; see Source-backed background.)
Agent vs tool vs MCP server โ
Four levels, each adding capability over the one before:
- Model call, text in, text out. No memory of your data, no ability to look anything up.
- Agent, a model plus instructions and a loop. It can follow a role, but still cannot reach real data on its own.
- Tool-enabled agent, an agent that can call tools (functions) to fetch facts or take actions. Now it can ground answers in real data.
- MCP-connected agent, a tool-enabled agent whose tools come from an MCP server over a standard interface. The same server can back many agents, and you can add capabilities without rewriting the agent.
Connecting the Part 6 package manager MCP server moves your agent to level 4: it can now look up packages, orders, and routes through the server you validated, instead of having those baked in. This is also the setup for later comparing MCP tools with native function tools.
Why it matters โ
In Part 6 you built and validated the package manager MCP server standalone. Now we put an agent in front of it. An order comes in, and Darryl needs to know what the warehouse should do next. The agent should inspect the package/order details through the MCP server and propose the next operational step, never pretending it has physically moved, shipped, or rerouted anything. That split, propose, don't act, is what makes a first agent useful and safe.
What you will build โ
A first package manager agent โ a hand-built agent loop on the OpenAI SDK, the same loop frameworks like Microsoft Agent Framework automate โ connected to at least one capability of the Part 6 MCP server. You give it a role and boundaries, run an order-investigation scenario, capture the tool calls it makes, and check that its answer is grounded in what the tools returned.
Lab steps โ
Remember to keep the API backend running
As Michael Scott once said: "I'm running this company, and I have to be on all the time." Your API backend feels the same way, keep it running in the background before starting the lab steps.
Create the agent file.
a. Confirm the packages are installed. You need
openaiandmcpfromrequirements.txt. If you have not installed dependencies yet, run this from the root of your fork with your virtual environment active:powershellpip install -r requirements.txtbashpip install -r requirements.txtb. Create the file. In the root of your fork, create a new file called
connected_agent.py.c. Add the imports and OpenAI client. The agent uses the same
.envvariables as the MCP server:pythonimport asyncio import json import os from openai import AzureOpenAI from dotenv import load_dotenv load_dotenv() client = AzureOpenAI( api_key=os.getenv("AZURE_OPENAI_KEY"), api_version=os.getenv("AZURE_OPENAI_API_VERSION", "2024-05-01-preview"), azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), ) MODEL = os.getenv("AZURE_OPENAI_DEPLOYMENT", "gpt-5.5")d. Add a bare
ask()function that calls the model without any tools, just to confirm the connection works:pythondef ask(question: str) -> None: response = client.chat.completions.create( model=MODEL, messages=[{"role": "user", "content": question}], ) print(response.choices[0].message.content) if __name__ == "__main__": ask("What is Michael Scotts role?")e. Verify the connection:
powershellpython connected_agent.pybashpython connected_agent.pyExpected output: the model answers with some answer on Michaels role (or words to that effect). If you see an authentication error, check your
.envvalues against the setup guide.Give the agent a role and boundaries.
An agent that answers any question freely will guess and over-step. Add a system prompt that defines the agent's role, what it may do, and what it must never do. The full template is in
snippets/agent-instructions.md; here it is filled in for the package manager:a. Add the
INSTRUCTIONSconstant after the imports, just above the load_env call:pythonINSTRUCTIONS = """\ You help Darryl, a warehouse lead, decide the next operational step for an incoming package or order. Allowed actions: look up package, order, and route details through the package manager MCP server, then propose a next step. Boundaries: never claim you physically moved, shipped, or rerouted anything; never act on real systems; only propose. Grounding rule: base every factual claim on a tool result. If you have not looked something up, say so rather than guessing. Escalation: if an order is missing a route or needs a manager's decision, ask for clarification rather than guessing.\ """Every line has a purpose: role sets scope, allowed actions limit capability, boundaries prevent false claims, grounding rule forces tool use, and escalation tells the agent when to stop and ask.
b. Pass instructions as the system message in
ask():pythondef ask(question: str) -> None: response = client.chat.completions.create( model=MODEL, messages=[ {"role": "system", "content": INSTRUCTIONS}, {"role": "user", "content": question}, ], ) print(response.choices[0].message.content)c. Verify the role. Temporarily change the call to
ask("Can you order me a pizza?")and run it.Expected output: the agent declines politely, staying within its warehouse-operations scope. Change the call back to
ask("What is Michael Scotts role?")before the next step.Connect to the MCP server and discover tools.
The agent needs to know which tools the Part 6 MCP server exposes before it can call them. The MCP SDK provides a client that launches the server as a subprocess and lists its capabilities.
a. Add the MCP import and server parameters after the existing imports:
pythonfrom mcp import ClientSession, StdioServerParameters from mcp.client.stdio import stdio_client SERVER_PARAMS = StdioServerParameters(command="python", args=["mcp_server.py"])StdioServerParameterstells the MCP client how to start your server: runpython mcp_server.pyin the current directory and communicate over stdin/stdout. This is the same stdio transport the MCP Inspector used in Part 6.b. Write an async function that connects and lists tools:
pythonasync def get_mcp_tools() -> list[dict]: async with stdio_client(SERVER_PARAMS) as (read, write): async with ClientSession(read, write) as session: await session.initialize() result = await session.list_tools() return [ { "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.inputSchema, }, } for t in result.tools ]Each MCP tool has a
name,description, andinputSchema(a JSON Schema object). The loop converts them into the{"type": "function", ...}shape the OpenAI SDK expects โ the MCP tool contract and the OpenAI tool contract are the same idea, just wrapped differently.c. Print the tools to confirm. Temporarily update
if __name__ == "__main__"::pythonif __name__ == "__main__": tools = asyncio.run(get_mcp_tools()) for t in tools: print(t["function"]["name"], "โ", t["function"]["description"])powershellpython connected_agent.pybashpython connected_agent.pyExpected output: one line per tool from your Part 6 server, for example:
list_packages โ Return all package IDs in the system... lookup_package โ Look up a package by its ID... lookup_order_status โ Return the current delivery status... lookup_route โ Return route information for a given route ID...If you see nothing or an error, confirm
mcp_server.pyis in the root of your fork and the backend API is running.Implement the tool-calling loop.
The bare
ask()sends one message and returns one reply. To use tools, the agent needs a loop: call the model โ if it requests a tool, dispatch it via MCP and feed the result back โ repeat until the model gives a plain text answer.a. Replace
ask()withrun_agent():pythonasync def run_agent(question: str, show_steps: bool = False) -> None: async with stdio_client(SERVER_PARAMS) as (read, write): async with ClientSession(read, write) as session: await session.initialize() tools_result = await session.list_tools() tools = [ { "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.inputSchema, }, } for t in tools_result.tools ] messages = [ {"role": "system", "content": INSTRUCTIONS}, {"role": "user", "content": question}, ] step = 0 while True: response = client.chat.completions.create( model=MODEL, messages=messages, tools=tools, tool_choice="auto", ) msg = response.choices[0].message messages.append(msg) if msg.tool_calls: for tc in msg.tool_calls: step += 1 args = json.loads(tc.function.arguments) if show_steps: print(f"{step}) calling {tc.function.name}({args})") result = await session.call_tool(tc.function.name, args) tool_text = result.content[0].text if result.content else "" if show_steps: print(f" โ {tool_text}") messages.append({ "role": "tool", "tool_call_id": tc.id, "content": tool_text, }) else: print(msg.content) breakThree things to notice in this loop:
tool_choice="auto"lets the model decide whether a tool call is needed.- Each
tool_callis dispatched to the MCP server viasession.call_tool(name, args). - The result is appended as a
"tool"role message so the model sees it on the next turn. - The loop exits only when the model returns a response with no tool calls โ that is the final answer.
b. Update the entry point:
pythonif __name__ == "__main__": asyncio.run(run_agent("What should I do with order PKG-2024-003?"))c. Run it:
powershellpython connected_agent.pybashpython connected_agent.pyExpected output: the agent calls an MCP tool, reads the result, and proposes a next step, for example:
Order PKG-2024-003 is fragile and currently in transit. I recommend hand-sorting and verifying the fragile label before loading.It proposes โ it does not claim to have done anything physical.Add observability: capture the tool calls.
A grounded answer is only trustworthy if you can see which tools were called. Pass
--show-stepsto trace the agent's reasoning before the final answer.a. Add argument parsing, replacing the entry point:
pythonif __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument("--order", default="PKG-2024-003", help="Package/order ID to investigate") parser.add_argument("--show-steps", action="store_true", help="Print each tool call") args = parser.parse_args() asyncio.run( run_agent(f"What should I do with order {args.order}?", show_steps=args.show_steps) )b. Run with
--show-steps:powershellpython connected_agent.py --order PKG-2024-003 --show-stepsbashpython connected_agent.py --order PKG-2024-003 --show-stepsExpected output: a numbered trace of tool calls followed by the final answer, for example:
1) calling lookup_package({'package_id': 'PKG-2024-003'}) โ Package PKG-2024-003: status=in_transit, destination=..., fragile=True, ... 2) calling lookup_route({'route_id': 'ROUTE-20260706-309DD0'}) โ {...} Order PKG-2024-003 is fragile and on route ROUTE-20260706-309DD0. Recommend hand-sorting and confirming the fragile label before loading.Every factual claim in the final answer should trace back to one of the numbered tool calls above it. If a claim has no supporting tool call, the agent has guessed or over-trusted its training data โ the exact failure this step is meant to catch.
Test an ambiguous order.
powershellpython connected_agent.py --order DM-9999 --show-stepsbashpython connected_agent.py --order DM-9999 --show-stepsExpected output: the MCP tool returns an error for
DM-9999. A well-instructed agent should ask for clarification or escalate rather than guess, for example:Order DM-9999 was not found in the system. Please confirm the order ID or check with your warehouse manager before proceeding.Name at least one such case โ this is exactly when a human (or the RegionalManagerAgent in Part 9) should be looped in.
Expected output โ
- Agent run: a proposed next operational step grounded in the order's real details, with no claim of physical action taken.
- Captured steps: an ordered list of tool calls (name, input, result) leading to the answer.
- Grounding check: every factual claim in the answer maps to a tool result; an unsupported claim is flagged.
Preview, Agent-to-Agent (A2A)
When an order needs a manager's decision, the package agent should hand off to the RegionalManagerAgent rather than decide alone. A2A (Agent-to-Agent) handoff is built in Part 9, here we only mark where it would happen.
Checkpoint โ
- The agent runs and calls at least one MCP capability.
- It has explicit role instructions and boundaries.
- It produced at least one tool-grounded answer (every claim backed by a tool call).
- You named at least one case where the agent should ask for clarification or escalate.
See How checkpoints work.
Fallback baseline โ
Try the build yourself first; if you run out of time, copy the completed agent:
copy baseline\07-1-connected-agent.py connected_agent.pycp baseline/07-1-connected-agent.py connected_agent.pybaseline/07-1-connected-agent.py is the completed connected agent. It connects to the mcp_server.py you built in Part 6. If you skipped Part 6, first copy the finished server into place: copy baseline\06-1-mcp-server.py mcp_server.py (macOS/Linux: cp baseline/06-1-mcp-server.py mcp_server.py).
Troubleshooting โ
- Agent can't reach the MCP server, confirm
mcp_server.pyis in the root of your fork and the backend API is running. Re-runpython connected_agent.pywithout--orderto confirm the MCP connection succeeds. More help on Troubleshooting. - Answer isn't grounded, the agent ignored or over-trusted the model; check it actually called a tool with
--show-stepsand tighten the instructions to require a lookup before answering. - Agent claims it did the work, strengthen the boundaries so it only proposes steps.
- Out of time, copy
baseline/07-1-connected-agent.pytoconnected_agent.py(andbaseline/06-1-mcp-server.pytomcp_server.pyif you don't have a server yet) and move on.
Optional stretch task โ
Add a second MCP capability (for example route or driver lookup) and have the agent use both in one order investigation, or write the agent's role/boundaries so it refuses an out-of-scope request and explains why, a preview of the boundaries mindset behind native tools in Part 8 and the A2A handoff in Part 9.
Source-backed background โ
- Agent Framework: primary source, the official Microsoft Agent Framework documentation on Microsoft Learn and its official repository, for the agent model, instructions, and tool registration.
- MCP concepts: modelcontextprotocol.io for how the agent discovers and calls capabilities served by the Part 6 MCP server.
- Agent-to-Agent (A2A): previewed here only; the handoff to the RegionalManagerAgent is built in Part 9.
For the full source list, see References.
Apply it: De LeesLantaarn โ
Apply it to your own solution
What is the De LeesLantaarn equivalent of this MCP-connected agent? Picture a member-facing lending assistant that answers "can I borrow this?" by calling your library MCP tools for stock, age category, and the member's remaining quota. Write its instructions and its boundaries: it may propose a loan or a backorder, but it must never claim it physically issued a book or charged a fine.
What we will not cover โ
- A complex or multi-agent system, A2A is only previewed; we build one agent today.
- Letting the agent update real systems or perform physical warehouse work, it only proposes.
- Hidden or implicit prompt behavior, the agent's role and tools are explicit and observable.
- Skipping tool-output validation, every answer is checked for grounding.
- A deep dive into memory, that was introduced in Part 3 and is not repeated here.
You finish with a working, bounded first agent and are ready to compare MCP tools with native function tools, the bridge into the rest of the afternoon.
Previous: Part 6, Build the MCP server ยท Next: Part 8, Native tools & A2A handoff