Part 8, Native tools & A2A handoff โ
Knowledge-share outline โ
- Tool calling without MCP, a native function tool is just a typed function the agent may call.
- When a local function tool is enough vs when MCP is better, small and self-contained vs shared and evolving.
- The A2A mental model, specialized agents delegating bounded tasks with explicit contracts.
- Task boundaries, handoff contracts, returned artifacts, the three things every handoff names.
- The example, the
RegionalManagerAgentdelegates label parsing to thePackageLabelParser. - Why not one giant agent? Keeping agents focused is what makes the system testable and safe.
At a glance โ
| Start state | End state | Fallback baseline |
|---|---|---|
| The Part 7 first MCP-connected agent with MCP tools | An agent with a native function tool plus an explicit A2A handoff to a specialist agent | baseline/08-1-a2a-agent.py |
Learning goals โ
- Do tool calling without MCP: add a native function tool (a plain function the agent may call).
- Reason about when a local function tool is enough and when MCP (Model Context Protocol), a standard interface for serving tools, is the better choice.
- Learn the A2A (Agent-to-Agent) mental model: agents delegating bounded tasks through explicit contracts to specialized agents.
- Place a capability with a clear rubric: native tool, MCP tool, or agent handoff.
Why it matters โ
In Part 7 your agent reached real data through MCP tools served by the Part 6 server. But not every capability needs a server. Parsing a messy shipping label is a small, self-contained job, making it a native function tool is simpler than standing up an MCP endpoint. Some jobs, though, need their own specialist with a different boundary. You don't cram those into one giant agent; you hand them off. At Dunder Mifflin, the RegionalManagerAgent shouldn't itself become a label-parsing expert; it should delegate that bounded task to a PackageLabelParser and get a clean artifact back. Clear boundaries keep each piece testable and safe.
What you will build โ
A native parse_label function tool, then an explicit handoff contract that lets the RegionalManagerAgent delegate label parsing to the PackageLabelParser. You build both in one working file and see the native-vs-MCP-vs-handoff decision play out end to end.
Native tool vs MCP tool vs agent handoff โ
Use this decision rubric to place a capability. Walk it down the list and stop at the first match:
| If the capability is | Make it a | Why |
|---|---|---|
| A small, self-contained function used by one agent | Native function tool | No server overhead; cheapest path |
| A tool many agents need, or deployed/evolved on its own | MCP tool | One server backs many agents |
| Its own bounded job needing a different boundary or specialist judgment | Agent handoff (A2A) | Keep agents focused; delegate, don't merge |
Worked examples: parse a label, native (small, local). Look up order/route status, MCP (shared, already served in Part 6). Decide an exception and produce a parsed-and-validated result a manager can act on, handoff to a specialist.
The same tool contract checklist applies to every shape, a native tool still needs a clear description, typed inputs, validation, predictable output, and a read-only/write marker:
Tool contract checklist โ
Run each tool against this checklist before you trust it, or hand it to an agent.
- Clear description: one sentence stating what the tool does and when to use it. This is how a client (and a model) selects the right tool; vague descriptions cause wrong calls.
- Typed inputs: every input has a name and a type, declared in the tool's schema.
- Input validation: invalid input (unknown id, wrong type, missing field) is rejected with a clear reason. The tool never guesses.
- Predictable output: a documented, consistent output shape for valid input.
- Honest read-only vs write marker: note whether the tool only reads or also changes data. Writes need extra care; today's package-manager tools are read-only.
- Validated both paths: you have run one successful call (documented output) and one failed call (clear error), and confirmed both behave as designed.
Lab steps โ
You work in a single file for this whole part. Each step gives you a ready-to-paste snippet to drop over the matching TODO in your working file.
Start from the Part 7 agent. Open
starter/08-1-a2a-agent.pyas your working file for this part. It contains the completed Part 7 connected agent with TODO stubs for the native tool and the A2A handoff already in place.bashcopy starter\08-1-a2a-agent.py a2a_agent.pybashcp starter/08-1-a2a-agent.py a2a_agent.pyExpected output:
a2a_agent.pyis in your root folder in the dm-ws repo. The TODO stubs confirm which parts are not yet implemented: theparse_labelbody, its registration inall_tools, its in-process dispatch, and the two handoff classes.Add the native
parse_labeltool. There are threeTODO (step 2)markers to resolve.a. Implement the body. Paste the snippet below over the
parse_labelbody.pythonimport re _ORDER_RE = re.compile(r"\b(?:DM|PKG)-[\w-]+", re.IGNORECASE) _ROUTE_RE = re.compile(r"\b(?:rte|route)\s*((?:R|ROUTE)-[\w-]+)", re.IGNORECASE) _FRAGILE_RE = re.compile(r"\b(?:fragile|frgile|frgl|frg)\b", re.IGNORECASE) def parse_label(raw_label: str) -> str: """Parse a raw shipping label into structured fields (orderId, fragile, route, confidence).""" order_match = _ORDER_RE.search(raw_label) route_match = _ROUTE_RE.search(raw_label) fragile_match = _FRAGILE_RE.search(raw_label) if not order_match: return json.dumps({"error": "unparseable", "rawLabel": raw_label}) order_id = order_match.group(0).upper() route = route_match.group(1).upper() if route_match else None fragile = fragile_match is not None confidence = 1.0 if not route: confidence -= 0.15 if fragile_match and fragile_match.group(0).lower() not in ("fragile",): confidence -= 0.08 # fuzzy spelling return json.dumps({ "orderId": order_id, "fragile": fragile, "route": route, "confidence": round(confidence, 2), })b. Register the tool with the LLM. Find the
TODO (step 2)aboveall_tools = mcp_toolsand make the native tool part of the offered tool list:pythonall_tools = mcp_tools + [PARSE_LABEL_TOOL]c. Dispatch it in-process. Find the
TODO (step 2)inside the tool-call loop and routeparse_labelcalls to your local function instead of the MCP server:python# Dispatch native tool in-process; MCP tools go to the server. if tc.function.name == "parse_label": tool_text = parse_label(**args) else: result = await session.call_tool(tc.function.name, args) tool_text = result.content[0].text if result.content else ""(This replaces the existing two lines that always call
session.call_tool. This is the native-vs-MCP difference in one screenful: same contract for the model, different dispatch.)See the tools and compare them. Confirm the native tool registered, then read the side-by-side comparison of the two shapes.
powershellpython a2a_agent.py --show-tools python a2a_agent.py --compare-toolsbashpython a2a_agent.py --show-tools python a2a_agent.py --compare-toolsExpected output:
--show-toolslists both the MCP tools from Part 7 and the new nativeparse_labelfunction tool.--compare-toolsprintsparse_label(native, in-process) next to an MCP tool, with hosting, ownership, maintenance cost, and when each wins. You should be able to name one reason to prefer each shape.Let the LLM call the native tool. Pass a raw shipping label to the agent. The model reads it, calls
parse_labelto extract the structured fields, then uses the returnedorderIdto call an MCP tool (e.g.lookup_package) and fetch the real package data. Use--show-stepsto see both dispatches, native tool first, MCP tool second.Before you run, check the backend is up
The agent auto-starts
mcp_server.pyas a subprocess (no manual start needed), but the MCP server needs the backend API to respond. Confirm it is running before continuing:powershellcurl http://localhost:8000/healthbashcurl http://localhost:8000/healthA
200response means you are good. If it is not running, see Running the app.bashpython a2a_agent.py --order "PKG-2024-013 frgile rte ROUTE-20260706-309DD0" --show-stepsbashpython a2a_agent.py --order "PKG-2024-013 frgile rte ROUTE-20260706-309DD0" --show-stepsExpected output:
--show-stepsprints each tool call. You should seeparse_labelfirst, the LLM chose it, not your code, then an MCP tool call using the extractedorderId, followed by the agent's recommendation based on both results.Write the handoff contract. A handoff is only trustworthy if it is written down as an explicit artifact (see Handoff contract template). Find the
TODO (steps 4-6)comment and confirm the filled-in contract reads:python# Handoff contract: RegionalManagerAgent -> PackageLabelParser # Input data : rawLabel (str) - the raw shipping label text. # Artifact : {orderId, fragile, route, confidence} on success. # Failure : {error: "unparseable", rawLabel} - never guesses, never writes. # Boundary : parses text only; does not decide routes or act on systems.Why it matters: this comment is the contract. Every field names something the caller and callee agreed on: what crosses the handoff, what comes back, and what happens on failure.
Implement the two agent classes. These are the callee and caller sides of the handoff. Both snippets sit inside their class, so keep the indentation exactly as shown.
a. The specialist
PackageLabelParser.run. It does exactly one thing: turn a label into the structured artifact.pythondef run(self, raw_label: str) -> dict[str, Any]: """Parse the label and return the structured artifact (or an error artifact).""" return json.loads(parse_label(raw_label))b. The caller
RegionalManagerAgent.handle_label. It delegates to the parser, then makes an operational decision from the returned artifact.pythondef handle_label(self, raw_label: str, show_handoff: bool = False) -> None: if show_handoff: print("RegionalManagerAgent -> PackageLabelParser") print(f" Sending : rawLabel={raw_label!r}") artifact = self._parser.run(raw_label) # the handoff if show_handoff: print(f" Received: {json.dumps(artifact)}") print(f"RegionalManagerAgent -> PackageLabelParser -> {json.dumps(artifact)}") if "error" in artifact: print("Decision: label unparseable - hold package; request re-labelling.") else: action = ( "handle with care; verify fragile label before loading" if artifact["fragile"] else "route normally" ) route = artifact.get("route") or "unknown route" print(f"Decision: {action} for {artifact['orderId']} on {route}.")Why it matters: the parser reuses the already-tested
parse_labeland returns a plain dict, a concrete artifact, not a conversation. The manager never parses the label itself: it delegates, receives the artifact, and only then decides. That separation of "delegate" from "decide" is the whole point of A2A.Run the delegation. Have the
RegionalManagerAgentdelegate a messy label to thePackageLabelParserand return the parsed artifact. (This lab uses a deterministic local run, not a network simulation, so the output is reproducible for everyone.)bashpython a2a_agent.py --handoff --label "DM-1037 frgile rte R-2"bashpython a2a_agent.py --handoff --label "DM-1037 frgile rte R-2"Expected output: the manager agent delegates, and the parser returns a structured artifact, e.g.
RegionalManagerAgent -> PackageLabelParser -> {"orderId": "DM-1037", "fragile": true, "route": "R-2", "confidence": 0.92}, followed by the manager's decision line.Capture the failure behavior. Inspect exactly what crossed the handoff, and what happens when parsing fails.
bashpython a2a_agent.py --handoff --label "???" --show-handoffbashpython a2a_agent.py --handoff --label "???" --show-handoffExpected output: the data sent (
rawLabel="???"), the artifact returned on failure ({"error": "unparseable", "rawLabel": "???"}), and confirmation that the parser made no change to any system: it returns an error, it does not act.
Handoff contract template โ
Write every handoff down as an explicit artifact, input data, returned artifact, and failure behavior, never a vague "ask the other agent." Use this reusable template (you confirmed it for the RegionalManagerAgent -> PackageLabelParser handoff in lab step 5):
Handoff contract template โ
Before one agent delegates to another, write the handoff down as an explicit artifact โ not a vague "ask the other agent." Fill in every line. A delegation you cannot describe this precisely is one you cannot validate.
- Caller โ callee โ who delegates to whom. Example: "
RegionalManagerAgentโPackageLabelParser." - Task โ the one bounded job being handed off. Example: "Parse a messy shipping label into structured fields."
- Input data โ exactly what is sent, with types. Example: "
rawLabel: stringโ the raw label text, e.g."DM-1037 frgile rte R-2"." - Returned artifact โ exactly what comes back, with shape. Example:
{ orderId: "1037", fragile: true, route: "R-2", confidence: 0.82 }. - Failure behavior โ what the callee returns when it cannot do the job. Example: "If the label cannot be parsed, return
{ error: "unparseable", rawLabel }โ never guess, never write to any system." - Boundary โ what the callee must NOT do. Example: "
PackageLabelParserparses text only; it does not decide priorities, reroute, or act on any system."
Expected output โ
- Native tool:
--show-toolslists the in-processparse_labelnative tool alongside the Part 6 MCP tools, and--compare-toolsprints the side-by-side. - Agent call:
--show-stepsshowsparse_labelfirst (native), then an MCP tool call using theorderIdextracted from the label to fetch real package data. - Delegation run:
RegionalManagerAgentsendsrawLabel, thePackageLabelParserreturns a structured artifact, and the captured handoff shows the data sent and the artifact returned. - Failure behavior: an unparseable label returns an explicit error artifact and changes nothing, no autonomous write.
Validate the handoff quality โ
Check your delegation against this list before you trust it:
- Explicit input, the data sent is named and typed (e.g.
rawLabel: string). - Returned artifact, the callee returns a concrete, documented result shape, not a chat.
- Failure behavior, an unparseable/invalid input returns a clear error, never a guess.
- Boundary respected, the callee does only its one job and writes to nothing.
The PackageLabelParser boundary โ
PackageLabelParser parses label text into structured fields, nothing more. It does not reason about priorities, decide routes, or act on any system. If a label is unparseable it returns an error; the calling RegionalManagerAgent decides what to do next. Keeping the parser this narrow is exactly what makes the handoff safe to trust.
Checkpoint โ
- You added a native
parse_labelfunction tool and can name one reason to prefer native and one reason to prefer MCP. - You saw the LLM call it via
--show-steps, native tool first, then an MCP tool. - You wrote an explicit handoff contract (input, artifact, failure behavior).
- You ran the delegation and captured the data sent and artifact returned, including the unparseable failure path.
See How checkpoints work.
Fallback baseline โ
Try the build yourself first, then copy the fallback if you run out of time:
copy baseline\08-1-a2a-agent.py a2a_agent.pycp baseline/08-1-a2a-agent.py a2a_agent.pyThe baseline includes the completed native parse_label tool and the working RegionalManagerAgent -> PackageLabelParser handoff so you can adopt it and still be ready to add human oversight in Part 9.
Apply it: De LeesLantaarn โ
Apply it to your own solution
Think about the De LeesLantaarn library platform from the case. When would a member-facing agent handle a job natively (a small, local calculation like "how many loans are left this month for a standard subscription?"), when would it call an MCP tool (reading live stock from the unreliable BMS), and when should it hand off to a separate specialist or admin agent (approving an age-restricted title, or overriding a quota)? Sketch one handoff contract: what data crosses, what artifact comes back, and what happens on failure.
Troubleshooting โ
- Native tool not listed, confirm
parse_labelis registered with the agent; re-run--show-tools. More help on Troubleshooting. - Agent call fails or returns no tool steps, the MCP server auto-starts but needs the backend API running. Check with
curl http://localhost:8000/healthand see Running the app if it is not up. - Delegation returns nothing (empty/failed handoff), the parser must always return either a structured artifact or an explicit error, never silence. Re-run with
--show-handoff. - Parser does too much, if it tries to decide routes or act, tighten its boundary; it should only parse and return.
- Out of time, copy
baseline/08-1-a2a-agent.pyand move on.
Optional stretch task โ
Add a second specialist handoff (for example a RouteValidatorAgent) and have the RegionalManagerAgent choose which specialist to delegate to based on the input, keeping each contract explicit. Notice how adding specialists stays manageable precisely because each handoff is bounded. This sets up adding human oversight in the next part.
Source-backed background โ
- Native tools & workflows: the official Microsoft Agent Framework documentation on Microsoft Learn and its official repository, for defining native function tools and multi-agent workflows.
- Agent-to-Agent (A2A): the official A2A project and specification (a2a-protocol.org) for what an agent-to-agent handoff is and what a handoff contract names.
- MCP comparison: modelcontextprotocol.io for how MCP tools differ from native function tools.
For the full source list, see References.
What we will not cover โ
- Autonomous write actions, the native tool and the parser return artifacts and errors; they never act on a system.
- A large or complex agent network, we build one bounded handoff, not an orchestration mesh.
- Treating A2A as required, it is one option among native tools and MCP tools; reach for the smallest that fits.
You finish with a clear decision rubric, a native tool, and one validated, bounded A2A handoff, and you are ready to add human oversight to these actions in Part 9.
Previous: Part 7, Agent Framework & first MCP-connected agent ยท Next: Part 9, Human-in-the-loop & condition checker