AIYINGFrom AI Awareness to Accomplishment
Showing posts with label Agent Orchestration. Show all posts
Showing posts with label Agent Orchestration. Show all posts

Friday, November 13, 2026

AI Engineering Active Concepts #010 — Agent Orchestration: Designing Reliable Multi-Step AI Workflows

AI ENGINEERING — ACTIVE CONCEPTS & PRACTICES | #010

Agent Orchestration: Designing Reliable Multi-Step AI Workflows



Chapter 2: Engineering AI Applications and Agents

AIYING — Accomplishing with AI

The Big Idea: Agent orchestration coordinates the sequence, dependencies, tools, decisions, state, and controls required to complete multi-step AI tasks.

An individual model response may be useful. An orchestrated workflow must deliver a verifiable outcome.

Engineering question: How do we make an AI workflow reliable when it involves multiple steps, external systems, failures, and human approvals?

Contents

  1. Why Agent Orchestration Matters
  2. UNDERSTAND — The Concept
  3. CONNECT — AI Engineering Relationships
  4. Agent Orchestration Architecture
  5. APPLY — Enterprise Procurement Workflow
  6. Worked Example: A Multi-Step Workflow
  7. Engineering Decisions and Trade-offs
  8. Active Industry Practices
  9. ACCOMPLISH — Practical Exercise
  10. Student and Practitioner Project
  11. Check Your Understanding
  12. Active Connections
  13. References and Further Reading

1. Why Agent Orchestration Matters

Consider an enterprise procurement manager asking:

"Check purchase order PO-1048. Verify whether the required material is available elsewhere. If delivery is delayed, recommend a recovery action and prepare the necessary follow-up."

This is not a single question. It is a sequence of dependent tasks.

The AI application may need to retrieve purchase-order information, inspect inventory, compare delivery alternatives, apply procurement policies, prepare a recommendation, and obtain approval before making changes.

Each step depends on information or decisions from previous steps.

What happens if the inventory service is unavailable? What if the purchase-order record is inconsistent? What if a human reviewer rejects the proposed action?

These are orchestration problems.

Agent orchestration is not simply connecting several AI calls. It is engineering the control flow that turns multiple operations into a dependable business outcome.

2. UNDERSTAND — The Concept

What is agent orchestration?

Agent orchestration is the coordination of AI models, tools, workflow steps, decisions, application state, and control mechanisms to accomplish a task.

The orchestrator may be implemented through conventional software logic, a workflow engine, an agent framework, or a combination of these.

Five essential responsibilities

ResponsibilityEngineering Question
PlanningWhich steps are required?
CoordinationWhat should run next, and what depends on what?
State managementWhat has already happened?
ControlWhich operations are permitted?
RecoveryWhat happens when a step fails?

Workflow versus agent

A workflow generally follows a predefined control structure. An agent may dynamically select actions and tools based on intermediate observations.

In practice, production systems often combine both approaches.

For example, an agent may analyze a supplier delay while a deterministic workflow controls approvals, record updates, and completion status.

Common orchestration patterns

  • Sequential: Execute dependent steps in order.
  • Parallel: Run independent operations concurrently.
  • Conditional routing: Choose a branch based on validated results.
  • Iterative: Repeat a bounded process until a condition is satisfied.
  • Supervisor-worker: Delegate specialized tasks to different components.
  • Human-in-the-loop: Pause for an authorized decision.
  • Event-driven: Resume when an external event occurs.

Not every problem needs multiple agents. A deterministic workflow with one model and a few tools may be simpler, cheaper, and easier to test.

3. CONNECT — AI Engineering Relationships

ConceptRelationship to Orchestration
Context EngineeringSupplies relevant information to each step
Token EconomicsControls the cost of repeated model calls
Retrieval EngineeringProvides external evidence
Context ManagementPreserves state and continuity
Structured OutputsDefines data contracts between steps
Tool CallingInvokes external capabilities
MCPProvides standardized access to external capabilities
EvaluationTests both individual steps and overall outcomes
ObservabilityTraces execution, latency, cost, and failures
GovernanceEstablishes accountability and approval controls

Active connection: Orchestration brings together the capabilities studied in earlier lessons into an operational AI application.

4. Agent Orchestration Architecture

User Request

↓

Workflow Controller / Orchestrator

↓

Task Planning and State Initialization

↓

Model and Tool Execution

↓

Result Validation

↓

Decision: Continue, Retry, Escalate, or Stop?

↓

Human Approval When Required

↓

Authorized Business Action

↓

Outcome Verification and Audit Record

State transitions

A workflow should have explicit states, such as:

CREATED
   |
   v
RUNNING
   |
   +--> WAITING_FOR_APPROVAL
   |           |
   |           v
   |        RUNNING
   |
   +--> FAILED
   |
   +--> COMPLETED

Real implementations may need additional states such as cancelled, timed out, rejected, or requiring manual intervention.

Why state matters

State enables a workflow to resume after interruptions, avoid repeating completed actions, and distinguish a pending operation from a successful one.

State should be stored in a durable application system when the workflow must survive process restarts or extended human approval delays.

5. APPLY — Enterprise Procurement Workflow

Scenario: Recovering from a Supplier Delay

A manufacturing company uses an AI assistant to investigate delayed material deliveries.

The assistant has access to fictional procurement, inventory, and supplier systems.

Step 1 — Retrieve purchase order

The system obtains the current order status through an authorized lookup tool.

Step 2 — Check inventory

The application retrieves stock availability from alternative locations.

Step 3 — Evaluate alternatives

The AI analyzes available evidence and prepares possible recovery options.

Step 4 — Apply business constraints

Deterministic checks verify inventory eligibility, policy requirements, and permitted actions.

Step 5 — Request approval

If a transfer or supplier change requires approval, the workflow pauses for the designated decision-maker.

Step 6 — Execute authorized action

The application invokes the approved operation and verifies its result.

Step 7 — Complete and record

The workflow reports the outcome and records the relevant execution history.

Important: The assistant should never describe an operation as completed merely because the model proposed it.

6. Worked Example: A Multi-Step Workflow

The following is a fictional design illustration, not a live enterprise integration.

Sample workflow state

{
  "workflow_id": "WF-1048",
  "po_id": "PO-1048",
  "status": "waiting_for_approval",
  "order_status": "delayed",
  "alternative_stock_available": true,
  "recommended_action": "internal_transfer",
  "approval_status": "pending",
  "execution_status": "not_started"
}

Illustrative orchestration pseudocode

async def process_order(po_id, user):
    order = await get_order(po_id, user)
    validate_order(order)

    if order["status"] != "delayed":
        return {"status": "completed",
                "action": "none"}

    inventory = await check_inventory(order, user)
    validate_inventory(inventory)

    proposal = await recommend_action(
        order, inventory
    )
    validate_proposal(proposal)

    approval_id = await request_approval(
        proposal, user
    )

    # Persist state and stop execution.
    # Resume only after a verified approval event.
    return {
        "status": "waiting_for_approval",
        "approval_id": approval_id,
        "execution_status": "not_started"
    }

This pseudocode illustrates a workflow boundary. A production implementation must authenticate the approver, persist state, resume through a controlled event, enforce authorization, and verify any eventual write operation.

What makes the workflow reliable?

  • Each step has defined inputs and outputs.
  • External results are validated.
  • State is recorded before suspension.
  • Approvals are explicit.
  • Retries are bounded and controlled.
  • Side-effecting actions use duplicate-prevention safeguards.
  • Completion is based on verified execution results.

7. Engineering Decisions and Trade-offs

DecisionBenefitTrade-off
Fixed workflowPredictability and testabilityLess flexibility
Dynamic agent planningAdapts to varied tasksHarder to constrain and evaluate
Parallel executionReduced latencyDependency and concurrency risks
Persistent stateResumabilityStorage and consistency complexity
Automatic retriesFailure recoveryCost and duplicate-action risks
Human approvalStronger oversightAdditional time
Multiple specialized agentsDivision of responsibilitiesCoordination overhead

Common failure modes

  • Infinite or excessive execution loops
  • Incorrect tool selection
  • Loss of workflow state
  • Contradictory intermediate results
  • Repeated actions after retries
  • Unauthorized execution
  • Unbounded token consumption
  • Incorrect completion reporting
  • Prompt injection through retrieved data or tool results

Recommended engineering controls

  • Maximum step and execution budgets
  • Timeouts and bounded retries
  • Checkpointing and durable state
  • Idempotency for operations with side effects
  • Structured contracts between components
  • Explicit approval boundaries
  • Least-privilege tool permissions
  • Execution tracing and audit records
  • Outcome-based evaluations
Reliable orchestration requires a controlled workflow, not merely a capable model.

8. Active Industry Practices

Established engineering approaches

  • State-machine and graph-based workflows
  • Task dependency management
  • Tool execution with validation
  • Human approval checkpoints
  • Persistent workflow state
  • Execution tracing and monitoring

Evolving AI engineering practices

  • Model-directed workflow routing
  • Supervisor and specialist-agent architectures
  • Agent evaluation using execution traces
  • Policy-aware tool orchestration
  • Adaptive planning with bounded autonomy
  • Durable execution for long-running agents

Relevant technologies

Developers may evaluate frameworks such as LangGraph, Microsoft Agent Framework, OpenAI Agents SDK, and conventional workflow engines.

These technologies have different architectures and operational characteristics. Framework selection should follow the requirements of the application rather than determine the architecture in advance.

Industry applications

Agent orchestration is relevant to customer support, software engineering, incident response, research assistants, enterprise operations, procurement, document processing, and multi-step business automation.

Practice status: Established workflow-engineering principles combined with evolving agentic AI architectures.

Reviewed: November 2026.

9. ACCOMPLISH — Practical Exercise

Exercise: Design a Procurement Recovery Workflow

Use this fictional scenario:

Purchase order: PO-2056

Status: Delayed

Required quantity: 500 units

Alternative location stock: 350 units

Proposed action: Partial internal transfer

Approval: Required

Your tasks

  1. Define the workflow objective.
  2. List the required tools and data sources.
  3. Identify sequential and parallel steps.
  4. Define workflow states and transitions.
  5. Specify validation checkpoints.
  6. Identify actions requiring approval.
  7. Design failure and retry handling.
  8. Define completion and escalation conditions.
  9. Explain how the remaining 150-unit shortage will be handled.

Reusable AI-assisted prompt

Act as an enterprise AI workflow architect.

Design an agent orchestration workflow
for a delayed purchase order.

Scenario:
- Order: PO-2056
- Required quantity: 500 units
- Alternative stock: 350 units
- Supplier delivery: delayed
- Internal transfer: approval required

Provide:
1. Workflow objective.
2. Required tools and data.
3. Step-by-step execution plan.
4. State transitions.
5. Validation rules.
6. Approval checkpoints.
7. Failure recovery strategy.
8. Cost and execution limits.
9. Observability requirements.
10. Completion and escalation criteria.

Distinguish AI-generated recommendations
from verified system actions.

Do not claim any real action was executed.

Accomplishment: Produce an orchestration design that can be reviewed for reliability, authorization, recovery, and measurable completion.

10. Student and Practitioner Project

Mini Project: Build a Stateful Procurement Agent

Objective: Prototype a multi-step AI workflow using simulated enterprise systems.

Project requirements

  1. Create fictional purchase-order and inventory datasets.
  2. Define lookup and simulated action tools.
  3. Implement a workflow controller.
  4. Persist workflow state between steps.
  5. Use structured inputs and outputs.
  6. Introduce an approval checkpoint.
  7. Simulate a tool timeout and a service failure.
  8. Test workflow resumption after interruption.
  9. Prevent duplicate side effects.
  10. Record execution traces and evaluate outcomes.

Suggested evaluation metrics

MetricWhat It Measures
Task completion rateSuccessful completion of authorized workflows
Step accuracyCorrect execution of required stages
Recovery successResumption after failures
State consistencyCorrectness of persisted workflow information
Approval complianceWhether required approvals are enforced
Duplicate action rateRepeated side effects after retries
Execution costModel and tool resource consumption
End-to-end latencyTotal workflow processing time

Project deliverable: A workflow diagram, working prototype or design, sample execution traces, evaluation results, and an engineering recommendation.

11. Check Your Understanding

  1. What is agent orchestration?
  2. How is orchestration different from tool calling?
  3. What is the difference between a fixed workflow and a dynamic agent?
  4. Why is persistent state important?
  5. When should workflow steps run in parallel?
  6. How should approval checkpoints be implemented?
  7. Why are retries dangerous for write operations?
  8. How would you measure end-to-end workflow reliability?

Reflection: If every individual AI step succeeds but the overall workflow performs an unauthorized action, has the system succeeded? What does this reveal about orchestration quality?

12. Active Connections

Coming next — #011: Agent Evaluation: Measuring Whether AI Workflows Actually Succeed.

13. References and Further Reading

  1. LangGraph — Overview
  2. OpenAI Agents SDK — Documentation
  3. Microsoft Agent Framework — Documentation
  4. Temporal — Durable Execution Documentation
  5. Model Context Protocol — Official Documentation

Framework capabilities and implementation guidance evolve. Verify the current documentation when building production systems.


Final Takeaway

A reliable AI workflow is not defined by how many agents or tools it uses. It is defined by whether it coordinates work correctly, handles failures, respects controls, and delivers a verified outcome.

AI Engineering — Active Concepts & Practices
Active Concept #010 — Agent Orchestration

AIYING — Accomplishing with AI

Understand → Connect → Apply → Accomplish

Thursday, November 12, 2026

AI Engineering Living Glossary #017 — Model Context Protocol (MCP): Connecting AI to Tools and Data

AI ENGINEERING | LIVING GLOSSARY | #017

MODEL CONTEXT PROTOCOL (MCP)

Standardizing Connections Between AI Applications and External Capabilities



Chapter 3: Connecting AI to Tools, Workflows, and Agents

Lesson 17 of 24

AIYING — Accomplishing with AI

Imagine an enterprise AI assistant that must answer:

"Find the latest customer support issues for Acme, check the relevant project documentation, and summarize what our team should investigate."

The information may be distributed across a customer relationship management system, a support platform, and a document repository.

Traditionally, engineers might build separate custom integrations for each system and each AI application.

What happens when another AI assistant needs the same integrations? Must the engineering team implement everything again?

Model Context Protocol (MCP) addresses this integration challenge by defining a common protocol through which compatible AI applications can discover and interact with external capabilities.

But interoperability is not the same as trust. A connection may be technically valid while still exposing the wrong data, invoking the wrong operation, or returning misleading information.

Central engineering insight: MCP standardizes how capabilities are exposed and accessed. The surrounding system remains responsible for security, authorization, correctness, and business outcomes.

1. What Is MCP?

Model Context Protocol (MCP) is an open protocol that standardizes communication between AI applications and systems that expose external tools, information, and reusable prompts.

Its purpose is to reduce the need for application-specific integration interfaces.

Through MCP, a compatible AI application can discover capabilities exposed by an MCP server and use those capabilities according to the protocol and the application's permissions.

MCP is not itself an AI model, an agent, a database, or a workflow engine.

It is a communication and integration protocol.

Also, MCP does not automatically make an external connection secure. Secure deployment depends on transport protection, identity, authorization, trusted configuration, and appropriate operational controls.

↑ Back to contents

2. Why MCP Matters

AI applications increasingly need access to external information and software capabilities.

Without a common integration approach, each application may require custom code for every external service.

Integration challengeWhat MCP can help with
Different connector interfaces.A shared protocol for exposing capabilities.
Repeated integration development.Potential reuse of compatible MCP servers.
Inconsistent capability discovery.Standardized discovery mechanisms.
Different ways to invoke tools.Common tool invocation structures.
Separate approaches to external context.Standardized resource access.
Application-specific prompt libraries.Reusable prompts exposed through servers.

These benefits are conditional. Applications must support MCP, servers must expose useful capabilities, and enterprise security requirements still need to be met.

Industry insight: Standardization can reduce integration friction, but it does not remove the need to engineer the underlying business integration.

↑ Back to contents

3. Core Components and Capabilities

A. MCP Host

The host is the AI application that manages the overall experience and its MCP connections.

Examples may include a compatible desktop AI application, development environment, or enterprise assistant.

B. MCP Client

The MCP client is a protocol component within the host that communicates with an MCP server.

A host can manage multiple client-server connections.

C. MCP Server

An MCP server exposes capabilities to connected clients.

It may wrap an existing API, database access layer, file system interface, or enterprise service.

D. Tools

Tools represent callable operations.

Examples:

  • Search support tickets.
  • Retrieve an order status.
  • Create a draft support ticket.
  • Query an approved business service.

Tool definitions include names, descriptions, and input schemas. Implementations may provide additional metadata.

E. Resources

Resources expose information that an application can read through defined resource interfaces.

Examples include documents, reference information, and other accessible content.

F. Prompts

Prompts expose reusable prompt templates or structured message content for supported applications.

G. Protocol messages

MCP uses structured communication, including JSON-RPC messages, to exchange requests, responses, and notifications.

H. Transport

Supported transports include local standard input/output communication and HTTP-based communication, depending on deployment and protocol version.

Remember: Host = application. Client = protocol connection component. Server = capability provider. Tools, resources, and prompts = different capabilities exposed through the protocol.
↑ Back to contents

4. How MCP Works

Consider a user asking an AI assistant to retrieve recent support tickets.

User Request
     |
     v
AI Application (MCP Host)
     |
     v
MCP Client
     |
     | Protocol communication
     v
MCP Server
     |
     v
Authorized Support API
     |
     v
Support Ticket Data
     |
     v
MCP Server Response
     |
     v
Host Validates and Processes
     |
     v
AI-Assisted User Response

Representative execution sequence

  1. The host establishes a connection with a configured MCP server.
  2. The client and server initialize their protocol session and negotiate supported capabilities.
  3. The application discovers relevant tools or other exposed capabilities.
  4. The user submits a request.
  5. The application may provide suitable tool descriptions to the model.
  6. The model may propose invoking a tool.
  7. The host applies validation, policy, and authorization controls.
  8. The MCP client sends an appropriate tool request to the server.
  9. The server validates the request and performs its authorized underlying operation.
  10. The result returns through the protocol.
  11. The host treats the result as external data and processes it appropriately.
  12. The model may use the result to produce a response.

The model does not directly gain unrestricted access to an enterprise system merely because an MCP server is available.

Actual access depends on the host, server implementation, identity, permissions, and the underlying service.

↑ Back to contents

5. MCP vs Tool Calling, APIs, RAG, and Agents

ConceptPrimary purpose
APIProvides an interface to software or data capabilities.
Tool CallingAllows a model to request an operation through an application.
MCPStandardizes how compatible applications connect to exposed tools, resources, and prompts.
RAGRetrieves relevant information to ground model responses.
WorkflowCoordinates a designed sequence or network of operations.
AI AgentUses model-guided decisions to pursue a goal.
Agent OrchestrationCoordinates agent execution, handoffs, and shared task state.

MCP can support several of these patterns.

For example, a RAG application may retrieve documents through an MCP resource or tool. An agent may use tools exposed by MCP servers. A workflow may invoke MCP-connected operations.

However, MCP does not itself perform retrieval ranking, manage an agent's goals, or orchestrate a complete business process.

↑ Back to contents

6. MCP Engineering Architecture

Consider an enterprise assistant connected to three systems.

       Enterprise AI Assistant
               (Host)
                  |
        +---------+---------+
        |         |         |
        v         v         v
     Client A  Client B  Client C
        |         |         |
        v         v         v
     MCP CRM   MCP Docs  MCP Support
      Server    Server     Server
        |         |         |
        v         v         v
     CRM API   Document   Ticket API
               Service

Cross-cutting controls:
Identity | Authorization | Validation
Audit | Monitoring | Error Handling

The host decides which servers to connect to and which capabilities are made available within its application.

Each server must protect access to its underlying systems.

Different servers may have different security requirements and data classifications.

The architecture should also define how the host handles unavailable servers, tool errors, and incompatible capability versions.

Important architectural boundaries

  • Application-to-server communication.
  • Server-to-underlying-service communication.
  • Model-to-application tool requests.
  • User identity and delegated permissions.
  • External data entering the model context.

These boundaries should be evaluated separately rather than assuming that protocol compatibility provides end-to-end security.

↑ Back to contents

7. Security and Trust Boundaries

Server trust

Connect only to servers that have been appropriately assessed and approved. A malicious server may expose misleading descriptions, request excessive permissions, or return hostile content.

Authentication and authorization

Apply the authentication and authorization mechanisms appropriate to the transport, server, and underlying service. Do not treat discovery as authorization.

Least privilege

Expose only the capabilities needed for the user's legitimate task.

Consent and approval

Use clear confirmation and approval mechanisms for consequential operations.

Prompt injection

Tool descriptions, resources, documents, and tool outputs can carry untrusted instructions. The host must not automatically promote external content into higher-priority instructions.

Data minimization

Avoid transmitting unnecessary customer, employee, financial, or confidential information.

Credential handling

Protect access tokens and secrets. Avoid passing credentials into model prompts or exposing them through tool results.

Tool validation

Validate arguments, access scope, and operation-specific constraints at trusted execution boundaries.

Auditability

Record relevant connection, authorization, and execution events without unnecessarily exposing sensitive data.

Failure handling

Handle unavailable servers, timeouts, malformed responses, and uncertain execution results.

Security principle: A standardized connection is not a trusted connection by default. MCP integrations require the same disciplined security engineering as other external integrations.
↑ Back to contents

8. Industry Applications

IndustryPotential MCP-enabled capability
Customer supportRetrieve tickets and authorized customer information.
Software engineeringAccess repositories, documentation, and approved development tools.
SalesQuery customer and opportunity records.
Human resourcesAccess permitted policy and employee service information.
OperationsRetrieve inventory and process status.
Knowledge managementAccess approved documents and reference content.
AnalyticsInvoke governed data-query capabilities.
Enterprise automationConnect controlled workflow operations to AI applications.

These are architectural possibilities, not guarantees that a particular enterprise application provides an MCP server.

↑ Back to contents

9. Engineering Design Decisions

  1. Does MCP provide a useful advantage over a direct API integration?
  2. Which MCP hosts and clients will be supported?
  3. Which servers are trusted and approved?
  4. Which tools, resources, and prompts should be exposed?
  5. Which capabilities are read-only?
  6. Which capabilities can change enterprise data?
  7. How will user identity and permissions be enforced?
  8. How will credentials and secrets be protected?
  9. What transport is appropriate for the deployment?
  10. How will external data be validated?
  11. How will prompt injection risks be addressed?
  12. Which operations require human confirmation?
  13. How will tool failures be detected and handled?
  14. How will server versions and compatibility be managed?
  15. How will integration quality be evaluated?
  16. How will the organization monitor and audit usage?

Engineering principle: Standardize the interface where it creates value, while retaining explicit responsibility for the security and correctness of the integrated operation.

↑ Back to contents

10. Practical Industry Case: The Enterprise Support Assistant

Scenario: A fictional enterprise wants an AI assistant to investigate a customer's unresolved support issues.

The assistant needs access to three approved systems:

  • CRM for customer account information.
  • Document repository for product support guidance.
  • Ticketing system for current incidents.

Proposed MCP architecture

The enterprise deploys or approves MCP servers that expose narrowly scoped capabilities for these systems.

The AI host connects to the relevant servers and discovers permitted operations.

Illustrative tools

crm.get_customer_summary
docs.search_support_guides
tickets.list_open_tickets

These are fictional tool names used for teaching. They are not standardized MCP tool names.

Execution sequence

  1. The user asks for a summary of Acme's unresolved support issues.
  2. The host verifies the user's identity and permitted customer access.
  3. The application selects relevant approved capabilities.
  4. The CRM tool retrieves an authorized customer summary.
  5. The ticketing tool retrieves open support cases.
  6. The documentation tool searches relevant support guidance.
  7. The host validates returned structures and handles errors.
  8. The AI model summarizes findings with references to available evidence.
  9. The application avoids presenting unsupported recommendations as verified facts.
  10. Any requested record modification follows separate authorization and approval controls.

Failure scenario A: Unauthorized customer access

The user requests records outside their assigned accounts.

The underlying authorization layer denies access even if the model requests the operation.

Failure scenario B: Untrusted document instructions

A retrieved support document contains text instructing the assistant to disclose unrelated customer information.

The application treats that text as untrusted document content, not as an authorized instruction.

Failure scenario C: Ticket server unavailable

The host reports that ticket information could not be retrieved rather than inventing a current ticket status.

Failure scenario D: Conflicting records

CRM and ticket data disagree on a customer identifier.

The assistant flags the inconsistency and avoids merging records without a reliable matching rule.

What this case demonstrates

MCP can simplify the interface between AI applications and external systems. It does not replace access controls, data quality checks, source verification, or operational accountability.

Industry insight: The value of MCP is interoperability. The value of AI engineering is making that interoperability useful, secure, and dependable.
↑ Back to contents

11. Hands-On Mini Project

Design a Read-Only MCP Support Server

Objective: Design or implement a simple MCP server that exposes fictional customer support information.

Use only synthetic data. No live enterprise credentials are required.

Step 1: Prepare sample data

Create five fictional support tickets with customer IDs, issue descriptions, statuses, and timestamps.

Step 2: Define capabilities

Design a read-only tool named get_ticket_status that accepts a ticket identifier.

Optionally expose a resource containing fictional support policy information.

Step 3: Define the tool schema

{
  "name": "get_ticket_status",
  "description": "Return the status of an authorized fictional support ticket",
  "inputSchema": {
    "type": "object",
    "properties": {
      "ticket_id": {
        "type": "string"
      }
    },
    "required": ["ticket_id"]
  }
}

This is an illustrative tool definition, not a complete MCP server implementation.

Step 4: Implement or simulate

Use an MCP-compatible SDK and local test environment, or document the request-response interactions if coding is not yet available.

Step 5: Apply authorization

Ensure the simulated user can retrieve only the tickets assigned to their fictional account.

Step 6: Test normal behavior

Request valid ticket statuses and verify the returned data against the sample dataset.

Step 7: Test failure behavior

  • Unknown ticket ID.
  • Missing required argument.
  • Unauthorized ticket request.
  • Simulated server timeout.
  • Malformed result.
  • Misleading text embedded in a ticket description.

Step 8: Evaluate

MetricWhat to measure
Discovery successCan the client identify the exposed tool?
Schema validityAre tool arguments correctly structured?
Authorization enforcementAre unauthorized requests denied?
Result fidelityDo results match the fictional records?
Failure handlingAre unavailable or invalid results handled correctly?
Prompt injection resistanceDoes hostile content remain untrusted data?
LatencyHow long do simulated tool calls take?
Audit completenessAre important operations traceable?

Success criteria

  • The tool can be discovered by a compatible client.
  • Valid requests return correct fictional data.
  • Unauthorized requests are rejected.
  • Invalid inputs do not trigger unintended operations.
  • Untrusted ticket text does not override application instructions.
  • Failures are communicated without fabricated results.

Reflection

What did MCP standardize? Which engineering responsibilities remained outside the protocol? Would a direct API integration be simpler for this particular application?

↑ Back to contents

12. Connected Glossary Terms

  • Tool Calling (#013): Allows a model to request an operation that may be exposed through MCP.
  • Workflows (#014): Can coordinate MCP-connected operations.
  • AI Agents (#015): Can use MCP-exposed capabilities when supported by their host.
  • Agent Orchestration (#016): Can coordinate agents that access tools through MCP.
  • RAG (#004): Can retrieve information through MCP-connected resources or tools.
  • Prompt Engineering (#006): Helps define model behavior when using external capabilities.
  • Evals (#007): Tests tool use and end-to-end task outcomes.
  • Grounding (#009): Connects responses to retrieved evidence.
  • Guardrails (#010): Enforces security and operational restrictions.
  • Observability (#011): Tracks tool execution and failures.
  • Human-in-the-Loop (#012): Provides oversight for consequential actions.

Previous lesson: #016 — Agent Orchestration: Coordinating Agent Execution and Handoffs

Next lesson: #018 — Structured Outputs: Making AI Responses Machine-Readable and Verifiable.

↑ Back to contents

13. Living Update

Editorial baseline: November 2026

MCP is an evolving protocol ecosystem. Implementations should be checked against the applicable published specification and SDK versions rather than assuming that all hosts and servers support identical capabilities.

Areas to monitor include:

  • Protocol version compatibility.
  • Transport and authorization guidance.
  • Server capability discovery.
  • Tool, resource, and prompt interoperability.
  • Enterprise server governance.
  • Trusted server distribution and approval.
  • Credential handling and delegated access.
  • Prompt injection and tool-output security.
  • Agent and workflow framework integration.
  • Testing, tracing, and operational monitoring.

Living Glossary note: Review this entry when the MCP specification or relevant implementation guidance changes.

↑ Back to contents

14. Key Takeaway

MCP standardizes how compatible AI applications connect to external tools, resources, and prompts. Reliable MCP integration still depends on security, validation, authorization, and outcome verification.

MCP can make AI integration more reusable and interoperable.

But the goal is not merely to connect more systems. It is to expose the right capabilities to the right users under the right controls.

Think like an AI engineer: If an MCP server exposes a powerful tool, what prevents an unauthorized user or model-generated request from misusing it?

↑ Back to contents

15. References and Further Reading

↑ Back to contents

AI Engineering — Living Glossary

One Term. One Industry Connection. One Practical Insight. One Action.

AIYING — Accomplishing with AI

Chapter 3 | Lesson 17 | MODEL CONTEXT PROTOCOL

Understand the Term. Connect the Technology. Apply the Knowledge.

↑ Return to top

AI Engineering Living Glossary #016 — Agent Orchestration: Coordinating Agent Execution and Handoffs

AI ENGINEERING | LIVING GLOSSARY | #016

AGENT ORCHESTRATION

Coordinating Agent Execution and Handoffs



Chapter 3: Connecting AI to Tools, Workflows, and Agents

Lesson 16 of 24

AIYING — Accomplishing with AI

At 10:15 AM, a software company's payment service begins failing.

Customers cannot complete transactions. The incident response team needs answers quickly.

Imagine an AI-enabled engineering system with three specialized agents:

  • A diagnostic agent that examines metrics and logs.
  • A code-analysis agent that inspects recent changes.
  • A verification agent that checks proposed fixes against available evidence and tests.

Each agent can contribute useful work. But who decides which agent acts first? What information should be passed between them? What happens if their conclusions conflict? Who authorizes a production change?

Simply connecting multiple agents does not answer these questions.

The system needs agent orchestration.

Central engineering insight: Agent orchestration coordinates responsibilities, execution, handoffs, state, and controls so that model-driven components contribute to one verifiable outcome.

1. What Is Agent Orchestration?

Agent orchestration is the coordination of one or more AI agents, tools, workflow operations, and human participants to accomplish a larger goal under defined execution and control rules.

It may manage:

  • Task assignment and delegation.
  • Execution order and dependencies.
  • Parallel and sequential operations.
  • Agent-to-agent handoffs.
  • Shared task state and context.
  • Validation of intermediate results.
  • Permissions and human approvals.
  • Retries, timeouts, and recovery.
  • Completion and outcome verification.

Orchestration does not necessarily require multiple agents. A single agent may be orchestrated alongside deterministic software and tools.

Likewise, a multi-agent system does not automatically need a separate AI-powered supervisor. Coordination can be implemented through conventional software.

Key distinction: Agents contribute decisions or specialized work. Orchestration determines how that work fits into the larger process.

↑ Back to contents

2. Why Agent Orchestration Matters

A collection of capable agents can still produce an unreliable system.

Consider these possible failures:

  • Two agents independently modify the same resource.
  • An analysis agent uses outdated information.
  • A verification agent receives an incomplete handoff.
  • One agent reports success while another reports failure.
  • An agent repeats a costly operation unnecessarily.
  • A production deployment begins without approval.
  • The overall process stops without recording its final state.

Orchestration addresses coordination problems that individual agent intelligence cannot reliably solve on its own.

Without explicit coordinationWith engineered orchestration
Responsibilities may overlap.Task ownership is defined.
Handoffs may be informal.Handoffs use structured contracts.
Agents may use inconsistent context.Relevant state is managed and versioned.
Execution may be difficult to trace.Steps and dependencies are recorded.
Failures may leave uncertain outcomes.Recovery and escalation paths are specified.
Local agent success may be mistaken for task completion.The overall business outcome is verified.

Orchestration makes coordination explicit. It does not eliminate the need to evaluate the underlying agents.

↑ Back to contents

3. Common Agent Orchestration Patterns

A. Sequential handoff

One agent completes a defined task and passes its result to the next.

Diagnostic Agent
       |
       v
Code Analysis Agent
       |
       v
Verification Agent
       |
       v
Human Review

Useful when later work depends on earlier findings.

B. Supervisor or coordinator pattern

A coordinator selects which specialized agent should perform the next task.

          Coordinator
          /    |    \
         v     v     v
      Agent A Agent B Agent C
          \    |    /
           v   v   v
          Integration

The coordinator may use deterministic rules, a model, or both.

C. Parallel specialization

Independent agents work concurrently on separate subtasks.

For example, one agent investigates logs while another examines recent code changes.

Their results must be synchronized before a dependent decision proceeds.

D. Planner-executor pattern

A planning component proposes tasks; execution components carry them out under application control.

Plans must remain revisable when observations contradict assumptions.

E. Review-and-revise pattern

One agent generates a candidate result and another evaluates it against defined criteria.

The review process requires stopping limits. Repeated agreement between models is not independent proof of correctness.

F. Human-gated orchestration

Automated investigation proceeds until an operation requires authorized human approval.

Approval must be enforced by the application, not inferred from conversational text.

Design principle: Choose the simplest coordination pattern that meets the task's requirements. More agents create more communication, integration, and failure points.
↑ Back to contents

4. How Agent Orchestration Works

A representative orchestration process is:

       Business Goal
             |
             v
    Validate Request
             |
             v
     Create Task State
             |
             v
   Select Coordination Plan
             |
             v
   Assign Agent Responsibilities
             |
             v
    Execute Permitted Tasks
             |
             v
  Validate Intermediate Results
             |
             v
    Handoff / Synchronization
             |
             v
  Integrate Findings and Evidence
             |
             v
     Approval if Required
             |
             v
    Verify Final Outcome
             |
             v
    Complete or Escalate

Some stages may repeat, branch, or execute in parallel.

The orchestrator should track what has completed, what is pending, which outputs are authoritative, and which operations remain blocked.

The model may recommend a next step, but trusted application controls must decide whether it is permitted to execute.

↑ Back to contents

5. Orchestration vs Workflows and Agents

ConceptMain roleIllustration
Tool CallingRequests an external capability.Read incident logs.
WorkflowDefines and executes a coordinated process.Incident intake, triage, review, closure.
AI AgentSelects actions toward a goal using model-guided decisions.Investigates an unfamiliar error.
Agent OrchestrationCoordinates agent tasks, dependencies, handoffs, and execution controls.Assigns investigation and verification to specialized agents.

These concepts overlap.

An agent can operate within a workflow. A workflow engine can orchestrate multiple agents. A single agent can coordinate tool use internally.

The terms describe different engineering responsibilities, not necessarily separate products or software layers.

↑ Back to contents

6. Engineering Architecture

A production-oriented agent orchestration architecture may include:

1. Task intake

Receives the goal, relevant inputs, identity, and execution constraints.

2. Orchestration controller

Schedules tasks, tracks dependencies, manages state transitions, and coordinates handoffs.

3. Agent registry

Defines agent capabilities, responsibilities, and allowed operations.

4. Agent execution environments

Run model-driven tasks with appropriate tool access and resource limits.

5. Tool gateway

Validates and authorizes access to APIs, data stores, and other capabilities.

6. Shared task state

Stores structured progress, artifacts, and relevant evidence.

7. Validation and integration layer

Checks agent outputs, resolves dependencies, and assembles results.

8. Policy and approval layer

Enforces business restrictions and required human decisions.

9. Observability layer

Tracks execution, latency, tool usage, failures, and costs.

10. Outcome verification

Confirms that the intended task was completed using appropriate evidence.

             User / Business Goal
                      |
                      v
             Orchestration Layer
                      |
          +-----------+-----------+
          |           |           |
          v           v           v
      Agent A      Agent B      Agent C
          |           |           |
          +-----------+-----------+
                      |
                      v
          Validated Handoff Results
                      |
                      v
           Integration and Review
                      |
                      v
             Approval Gate
                      |
                      v
           Verified Final Outcome

Across all stages:
State | Permissions | Monitoring | Recovery

Not every application requires all these components as separate services. Smaller systems can implement several responsibilities in one application.

↑ Back to contents

7. Handoffs and Shared State

A handoff transfers responsibility for a task or subtask from one component to another.

Reliable handoffs require more than forwarding a conversational transcript.

What should a handoff contain?

  • Task and correlation identifiers.
  • Sending and receiving component roles.
  • Clear objective and expected output.
  • Relevant validated inputs.
  • References to supporting evidence.
  • Current status and known uncertainties.
  • Permissions and execution constraints.
  • Output schema and completion criteria.

Illustrative handoff contract

{
  "task_id": "INC-204",
  "from": "diagnostic_agent",
  "to": "code_analysis_agent",
  "objective": "Inspect recent changes",
  "service": "payment-api",
  "evidence_refs": [
    "log-set-17",
    "metric-set-08"
  ],
  "suspected_area": "timeout handling",
  "confidence": "tentative",
  "allowed_actions": [
    "read_repository",
    "inspect_commits"
  ],
  "prohibited_actions": [
    "merge_code",
    "deploy"
  ],
  "expected_output": {
    "findings": "array",
    "evidence_refs": "array",
    "uncertainties": "array"
  }
}

This is an illustrative application-level contract, not a universal agent communication standard.

Shared state is not unrestricted shared memory

Different agents may need different subsets of information.

Use access controls, versioned artifacts, and clear ownership to prevent accidental exposure, conflicting updates, or stale decisions.

Handoff validation

The receiving component should validate the handoff structure and independently enforce its own permissions.

Claims generated by one agent should not automatically become trusted facts for another.

Handoff principle: Transfer the minimum sufficient context, preserve evidence and uncertainty, and reapply authorization at each execution boundary.
↑ Back to contents

8. Security, Reliability, and Recovery

Least privilege

Each agent receives only the tools and permissions needed for its responsibility.

Independent authorization

The orchestrator and tool gateway enforce access controls outside model-generated instructions.

Untrusted inputs

Logs, documents, repository files, and agent outputs may contain misleading content or prompt-injection attempts.

Structured validation

Check handoff schemas, required fields, artifact references, and permitted transitions.

Timeouts and budgets

Limit execution duration, tool calls, retries, and total resource consumption.

Concurrency control

Prevent agents from making conflicting updates to shared resources.

Idempotency

Protect state-changing operations against duplicate execution after retries or restarts.

Checkpointing

Persist sufficient state to resume or safely terminate interrupted tasks.

Human intervention

Route high-risk, uncertain, or conflicting outcomes to authorized reviewers.

Outcome verification

Use independent system evidence to verify consequential operations.

Traceability

Record which component performed each operation, which evidence it used, and what actually happened.

Important: If a deployment request times out, the orchestrator should check the deployment system's authoritative status before attempting another deployment.

↑ Back to contents

9. Industry Applications

DomainPotential orchestration pattern
Software engineeringDiagnosis, code analysis, testing, human review.
Customer supportIssue classification, specialist investigation, escalation.
Business researchSource gathering, evidence analysis, synthesis, verification.
Supply chainException detection, inventory analysis, replenishment recommendation.
Financial operationsDocument review, reconciliation, exception handling, approval.
Enterprise knowledgeRetrieval, comparison, summarization, factual review.
Security operationsAlert triage, evidence collection, analysis, authorized response.
Content productionResearch, drafting, editorial checking, publication approval.

Specialized agents may improve modularity, but the benefit should be measured against the additional cost, latency, and coordination complexity.

↑ Back to contents

10. Engineering Design Decisions

  1. Does this task require more than one agent?
  2. Could a single agent or deterministic workflow be simpler?
  3. Which responsibilities should be specialized?
  4. Which tasks depend on other tasks?
  5. Which tasks can run in parallel?
  6. Who decides the next agent to execute?
  7. What information must each handoff include?
  8. Where will authoritative state be stored?
  9. How will conflicting findings be resolved?
  10. Which tools may each agent access?
  11. Which actions require human approval?
  12. How will execution limits be enforced?
  13. How will interrupted tasks recover?
  14. How will intermediate results be evaluated?
  15. How will the final outcome be independently verified?
  16. How will the multi-agent design be compared with a simpler baseline?

Engineering decision: Use specialization only where it produces demonstrable improvements in quality, maintainability, or task success.

↑ Back to contents

11. Practical Industry Case: Coordinating a Production Incident

Scenario: A fictional software company experiences increased payment failures after a recent release.

An AI-assisted incident response system is allowed to investigate using read-only tools. Production changes require human authorization through the organization's deployment process.

Agent responsibilities

ComponentResponsibilityPermission boundary
OrchestratorAssign tasks, manage dependencies and state.Cannot bypass approvals.
Diagnostic agentInspect metrics, errors, and incident timelines.Read-only telemetry.
Code-analysis agentInspect relevant commits and code paths.Read-only repository access.
Verification agentAssess evidence and run permitted tests.Isolated test environment.
Human incident leadAuthorize consequential remediation.Established organizational authority.

Step-by-step execution

  1. Trigger: Monitoring reports an abnormal payment failure rate.
  2. Intake: The orchestrator creates incident task INC-204.
  3. Assignment: The diagnostic agent receives a bounded investigation request.
  4. Observation: Metrics show increased timeouts after a release.
  5. Handoff: The diagnostic agent passes evidence references and uncertainty to code analysis.
  6. Analysis: The code-analysis agent identifies a potentially relevant timeout configuration change.
  7. Verification: The verification agent evaluates the proposed explanation using approved tests and available evidence.
  8. Integration: The orchestrator assembles findings, conflicts, and unresolved questions.
  9. Review: The human incident lead examines the evidence and decides whether to approve remediation.
  10. Execution: If authorized, the organization's controlled deployment workflow performs the change.
  11. Verification: Operational monitoring checks whether the failure rate returns to an acceptable level.
  12. Closure: The incident is closed only after the required verification and record updates.

Failure scenario A: Conflicting conclusions

The diagnostic agent suspects a network problem, while the code-analysis agent suspects a configuration change.

The orchestrator records both hypotheses and requests additional evidence rather than treating either claim as established fact.

Failure scenario B: Missing handoff evidence

The code-analysis agent receives a conclusion without supporting logs or metrics.

The handoff fails validation, and the orchestrator requests the missing evidence.

Failure scenario C: Verification agent timeout

The orchestrator records the incomplete verification and follows a bounded retry or human escalation policy.

Failure scenario D: Unauthorized deployment request

An agent proposes deploying a fix directly.

The application blocks the operation because production deployment requires authorization through a separate controlled process.

What this case demonstrates

Individual agents can investigate different aspects of a problem. The orchestrator is responsible for ensuring that their work is coordinated, evidence is preserved, and operational boundaries remain intact.

Industry insight: Multi-agent coordination is successful only when the complete system produces a verified result. Three agents agreeing on an answer is not equivalent to proving that a production incident has been resolved.
↑ Back to contents

12. Hands-On Mini Project

Design a Simulated Multi-Agent Incident Response System

Objective: Build or document an orchestration system that coordinates specialized agents using fictional incident data.

No real production infrastructure or deployment permissions are required.

Step 1: Define the goal

Investigate a fictional payment service incident and produce an evidence-supported recommendation or escalation.

Step 2: Define three roles

  • Diagnostic agent.
  • Code-analysis agent.
  • Verification agent.

Step 3: Create fictional evidence

Prepare incident logs, performance metrics, and a small list of recent code changes.

Step 4: Define handoff schemas

Include task ID, objective, evidence references, uncertainties, permitted actions, and expected outputs.

Step 5: Implement orchestration

Coordinate diagnostic investigation, code analysis, verification, and final integration.

Step 6: Add policy boundaries

Permit read-only investigation and simulated testing. Prohibit actual production changes.

Step 7: Introduce failures

  • Missing evidence in a handoff.
  • Conflicting agent findings.
  • Tool timeout.
  • Duplicate task assignment.
  • Unauthorized deployment request.

Step 8: Evaluate

MetricEvaluation question
Task completion rateDid the system reach an appropriate verified outcome or escalation?
Handoff validityWere required fields and evidence references present?
Coordination accuracyWere tasks assigned to appropriate components?
Authorization violationsDid any prohibited operation execute?
Conflict handlingWere contradictory findings handled explicitly?
Recovery successCould the system resolve or safely escalate failures?
Execution efficiencyHow many model and tool calls were required?
End-to-end latencyHow long did the complete process take?
Evidence fidelityWere final conclusions supported by the available evidence?

Step 9: Compare with a simpler baseline

Design a single-agent or deterministic workflow for the same task.

Compare task success, cost, latency, failure handling, and implementation complexity.

Success criteria

  • Every agent has a defined responsibility.
  • Handoffs are validated.
  • Conflicting findings are not silently discarded.
  • No unauthorized operation executes.
  • All test runs terminate within defined limits.
  • The final report preserves evidence and uncertainty.
  • The design can be justified against a simpler alternative.

Reflection

Did specialization improve the result? Which coordination costs were introduced? When would a single-agent design be preferable?

↑ Back to contents

13. Connected Glossary Terms

  • Tool Calling (#013): Provides external capabilities to agents.
  • Workflows (#014): Define structured execution and process transitions.
  • AI Agents (#015): Perform model-guided tasks toward defined goals.
  • Prompt Engineering (#006): Helps specify agent responsibilities and instructions.
  • RAG (#004): Supplies relevant retrieved evidence.
  • Context Window (#005): Limits how much information can be passed to an agent in one model interaction.
  • Evals (#007): Tests component behavior and system-level outcomes.
  • Hallucination (#008): Can propagate unsupported claims through handoffs.
  • Grounding (#009): Connects findings to supporting evidence.
  • Guardrails (#010): Enforces permissions and execution restrictions.
  • Observability (#011): Makes multi-step execution traceable.
  • Human-in-the-Loop (#012): Provides approval and escalation mechanisms.

Previous lesson: #015 — AI Agents: Goal-Directed Systems That Use Tools and Make Decisions

Next lesson: #017 — Model Context Protocol (MCP): Standardizing Connections Between AI Applications and Tools.

↑ Back to contents

14. Living Update

Editorial baseline: November 2026

Agent orchestration continues to evolve through agent frameworks, durable execution systems, tool integration standards, and enterprise governance practices.

Areas to monitor include:

  • Structured agent-to-agent communication.
  • Agent interoperability protocols.
  • Model Context Protocol integration.
  • Durable orchestration and recovery.
  • Distributed tracing across agent boundaries.
  • Agent identity and delegated authorization.
  • Human approval and intervention patterns.
  • Multi-agent evaluation benchmarks.
  • Coordination cost and latency optimization.
  • Security risks arising from cross-agent instructions.

Living Glossary note: Revisit this entry as agent communication standards, orchestration frameworks, and evaluation practices mature.

↑ Back to contents

15. Key Takeaway

Agent orchestration turns individual agent capabilities into a coordinated process by managing responsibilities, handoffs, shared state, controls, and verified outcomes.

The aim is not to build the largest possible team of AI agents.

The aim is to design the simplest coordinated system that accomplishes the task reliably.

Think like an AI engineer: If three agents produce three different answers, what mechanism determines the next action—and what evidence is needed before the system can claim success?

↑ Back to contents

16. References and Further Reading

↑ Back to contents

AI Engineering — Living Glossary

One Term. One Industry Connection. One Practical Insight. One Action.

AIYING — Accomplishing with AI

Chapter 3 | Lesson 16 | AGENT ORCHESTRATION

Understand the Term. Connect the Technology. Apply the Knowledge.

↑ Return to top

Accomplish with AI

Powered by Blogger.

Featured post

AI Engineering Hands-On Lab #001 — Build an AI Answer Reliability Test Bench Without Code

AIYING | Daily 24 — Post 009 AI Engineering Hands-On Lab #001 Build an AI Answer Reliability Test Bench — Without Writing Code Lea...

Search This Blog

List of blogs

Search This Blog

About

Translate

Instant Stories

Read in Your Language

Test

share this

ShareThis

Popular Posts