A hands-on walkthrough for designing an agent loop as a deterministic state machine, connecting tools with typed schemas and idempotency, separating planning from execution, persisting session-scoped memory, and testing hard guardrails. It also introduces MCP’s client/server model, enterprise tool and resource patterns, and controls for least privilege, data exposure, trusted servers, and human approval.
Last updated 2026-10-21 · 20 min read
Existing role and certification connections for this hands-on work.
Role track: MLOps Engineer
Role track: MLOps Engineer
Role track: MLOps Engineer
Exam domains: Implement knowledge mining & safety guardrails
Role track: MLOps Engineer
Role track: AI Agent Developer
Role track: AI Agent Developer
Role track: AI Agent Developer
Exam domains: Prompt engineering & evaluation, NVIDIA accelerated stack awareness
Exam domains: DeepLearning.AI Generative AI for Everyone course
MCP is an open protocol for connecting an AI application to external tools and data through a consistent client/server boundary. The host keeps the model and user interaction; an MCP client connects to a server, discovers what it offers, and sends only the requests allowed by the host and the server’s own permissions. MCP standardizes the exchange, but does not make a server trusted or grant it authority by itself.
A host’s client requests a capability from a particular server; the server returns bounded context or a tool result to the host.
The host is the AI app, such as an IDE assistant or internal IT agent. Its MCP client manages a connection to a particular server, learns that server’s available capabilities, and sends protocol requests on the host’s behalf.
A local process or remote service exposes a deliberate connection to one system or data domain, including capabilities such as tools and resources. It mediates requests using its own configuration and credentials; the client should connect only to servers your organization has reviewed.
A tool is a named operation with an input shape, such as searching selected tickets or drafting a change. A tool can change external state, so validate its arguments and enforce its authorization and approval rules outside the model.
A resource is a named or URI-addressed piece of context, such as an approved runbook, a specific ticket, or a service summary. Keep resource selection narrow, and treat returned text as untrusted input that may contain misleading instructions.
These are example patterns for IT and engineering teams; scope each one to your own approved systems and operating policies.
Read one incident ticket, an approved runbook, and a scoped service-health summary; suggest investigation steps without exposing unrelated tenant records or changing production.
Compare a deployment plan with service ownership and recent health signals, then draft a rollout or rollback plan for an operator to review before execution.
Search an explicitly selected repository and issue tracker for relevant code and history, then propose a patch or issue for a developer to inspect rather than merging automatically.
Retrieve approved architecture notes, policies, or on-call instructions and return the source identifiers with the summary so a professional can check the original context.
MCP provides a communication pattern. Your identity, authorization, data policy, and approval controls still decide what a server can do.
Start with read-only access. Give each server and tool a separate identity scoped to the required system, records, and operations; add write access only when the task needs it.
Approve the server source, owner, version, network destination, and update process. Review configuration changes and secrets handling; a familiar name or valid protocol handshake is not proof of trust.
Expose only the specific resources and fields needed, redact secrets, bound search results, and define retention. Do not hand an agent an entire production account, broad log stream, or credential store for convenience.
Pause before production changes, external messages, access changes, or other high-impact writes. Show the exact target and proposed action, then enforce approval in the trusted runtime or tool server—not in a prompt or model-generated flag.
Design an MCP connection that helps an on-call engineer summarize one sanitized incident and prepare the next safe check.
Sketch the agent loop on paper before any tool call fires. A production agent is a deterministic state machine wrapped around an LLM: each turn emits a structured decision, the runtime applies it within a hard iteration budget, and the loop only progresses when the prior action’s effect is observably consumed. The runtime enforces the contract — turn count, tool-call count, and dollar-ceiling per session — so the LLM cannot accidentally enable itself into a runaway. Start the loop stateless at idle and inject the conversation history at turn start so replicas do not fan out with divergent mental states.
# agent_loop.ts — deterministic turn machine around the Polsia AI proxy.
# Every iteration is validated against the budget BEFORE the next turn is
# scheduled, so a runaway prompt cannot outrun the runtime caps.
type AgentTurn = {
sessionId: string;
turnId: string;
plan: PlanStep[];
toolCallsRemaining: number;
spentUsd: number;
};
async function agentLoop(turn: AgentTurn, prompt: Prompt): Promise<Observation> {
const remainingSteps = MAX_TOOL_CALLS_PER_TURN - turn.toolCallsRemaining;
if (remainingSteps <= 0) throw new StuckLoopError('tool-call budget exhausted');
if (turn.spentUsd > MAX_SPEND_USD) throw new BudgetExceededError();
const decision = await generateObject({
model: AGENT_MODEL,
schema: AgentDecisionSchema,
prompt,
history: await loadSessionHistory(turn.sessionId),
});
if (decision.kind === 'final') return decision.observation;
if (decision.kind === 'tool') {
const observation = await invokeTool({
tool: decision.tool,
args: decision.args,
idempotencyKey: `${turn.turnId}:${decision.tool.name}`,
});
await appendTurn(turn, decision, observation);
return agentLoop(nextTurn(turn, decision, observation), followupPrompt);
}
throw new InvalidDecisionError(decision);
}Register each tool with a typed JSON schema, then route calls through the Polsia AI proxy — never call a model provider directly. `analyzeImage` covers vision-grounded reasoning for inputs that need object detection or OCR before any structured decision is made; structured `generateObject` is the right primitive for tool-call output because it forces the model to commit to a typed shape that the runtime can validate before invoking the side effect. Each tool invocation carries an idempotency key derived from `${turnId}:${toolName}` so retries never double-call a side-effectful endpoint like a payment or a Stripe checkout session.
# Python — typed tool registration on the Polsia Agent API. The schema below
# is what the runtime validates against BEFORE the side effect fires, so a
# model that emits an off-schema call ends the turn without invoking anything.
from polsia_agent import AgentClient, ToolSpec, generate_object, analyze_image
client = AgentClient()
tools: list[ToolSpec] = [
ToolSpec(
name='search_retrieval',
description='Search the RAG index and return the top-k chunks for a query.',
parameters={
'type': 'object',
'properties': {
'query': {'type': 'string'},
'top_k': {'type': 'integer', 'minimum': 1, 'maximum': 10},
},
'required': ['query'],
},
iam_principal='arn:aws:iam::123:role/agent-tool-search',
),
ToolSpec(
name='analyze_invoice_image',
description='OCR + structured extraction from a vendor invoice image.',
parameters={
'type': 'object',
'properties': {'image_url': {'type': 'string'}},
'required': ['image_url'],
},
requires=['analyzeImage'],
),
]
# The runtime rejects tool calls whose parameters do not match the schema
# and short-circuits to the planner with a validation_error observation.
result = generate_object(
client=client,
prompt='Extract the line items from this invoice into structured JSON.',
schema=InvoiceSchema,
tools=tools,
)Layer a planner in front of the executor instead of letting the loop improvise. Before any tool fires, the planner emits a step list using structured output (`generateObject` with a `Plan` schema: `id`, `reason`, `expectedEffect`, `fallback`), and the loop executes it deterministically. If a step’s predicted effect does not match the actual observation after the side effect lands, the planner re-enters planning mode with the diff as evidence — not just the failure string — so the next plan is grounded in what actually flowed back. Cap the planner’s replan depth per turn so a misbehaving planner cannot burn the entire budget on replanning.
# Python — planner emits a typed Plan before any tool fires; the executor
# walks the plan id-by-id and the planner re-plans only on observation diff.
from polsia_agent import generate_object, PlanStep, PlanSchema
def plan_and_execute(session_id: str, user_prompt: str) -> Observation:
plan = generate_object(
client=client,
prompt=user_prompt,
schema=PlanSchema,
history=load_session_history(session_id),
)
persist_plan(session_id, plan)
observations: list[Observation] = []
for step in plan.steps:
try:
obs = execute_step(step, idempotencyKey=f'{session_id}:{step.id}')
observations.append(obs)
if not matches_expected_effect(step.expectedEffect, obs):
diff = diff_observation(step.expectedEffect, obs)
plan = replan(session_id, original=plan, failed_step=step, diff=diff)
persist_plan(session_id, plan)
except ValidationError as err:
return final_response(session_id, error=err)
return final_response(session_id, observations=observations)All conversation state is durable, not in-memory. Persist each turn’s structured decision — the planner output, the tool call, and the post-action observation — into a session-scoped row keyed by `sessionId + turnId` so a replica restart picks up exactly where the previous one stopped, and so a long-running agent can survive a deploy window. Treat long-term memory as a separate concern from the working buffer: episodic events go into an append-only event log, semantic facts into a vector store, and user-scoped preferences into a row on the user-profile table. The working log rolls into long-term memory via an async projector so the agent never has to read the whole log into prompt context.
# Postgres — session-scoped turn log with append-only constraints; a stuck
# runtime cannot retroactively rewrite a prior turn without tripping the
# trigger, which is exactly what we want for offline replay auditing.
CREATE TABLE agent_turn (
session_id TEXT NOT NULL,
turn_id BIGINT NOT NULL,
plan_id TEXT,
decision JSONB NOT NULL,
observation JSONB,
spent_usd NUMERIC(10, 4) NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (session_id, turn_id)
);
CREATE INDEX agent_turn_session_idx ON agent_turn (session_id, created_at DESC);
-- Reject retroactively editing a prior turn; replays must append a new row.
CREATE OR REPLACE FUNCTION reject_turn_rewrite() RETURNS trigger AS $$
BEGIN
IF EXISTS (
SELECT 1 FROM agent_turn
WHERE session_id = OLD.session_id
AND turn_id = OLD.turn_id
AND created_at < OLD.created_at
) THEN
RAISE EXCEPTION 'agent_turn is append-only';
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER agent_turn_no_rewrite
BEFORE UPDATE ON agent_turn
FOR EACH ROW EXECUTE FUNCTION reject_turn_rewrite();Wire evaluations before any agent runs against a production user. The runtime records every turn to a structured event log with the planner’s plan, the tool call, and the post-action observation; an offline eval pipeline replays these logs through a labelled "stuck-loop" fixture set at every model upgrade and ships a regression gate into CI. Hard caps — turn count, tool-call count, and dollar spend per session — are enforced by the runtime itself, not by a prompt instruction; the eval fixtures pin cases where the model attempts to bypass those caps via prompt manipulation. A failing guardrail on a release branch must block the deploy, not just emit a Slack ping.
# pytest — stuck-loop regression gate. The fixture replays the same query
# twice and asserts the second run takes strictly fewer turns; a model
# upgrade that quietly doubles step count fails this gate before it ships.
import pytest
from polsia_agent import load_session_log
STUCK_LOOP_QUERIES = [
'summarize yesterday’s on-call handoffs',
'reconcile vendor invoices against the open PO list',
'find the root cause of the 500 spike from 14:02',
]
@pytest.mark.parametrize('query', STUCK_LOOP_QUERIES)
def test_no_stuck_loop_on_replay(query: str) -> None:
first_turns = run_agent_to_completion(query, session='fixture-1').turn_count
second_turns = run_agent_to_completion(query, session='fixture-2').turn_count
assert second_turns <= first_turns, (
f'second replay took {second_turns} turns (> first run {first_turns}); '
'model is regressing on stuck-loop recovery'
)
def test_runtime_caps_enforce_budget() -> None:
runaway = run_agent_to_completion(
'loop indefinitely on a no-op tool', session='budget-cap'
)
assert runaway.terminated_reason == 'budget_exceeded'
assert runaway.spent_usd <= MAX_SPEND_USD * 1.01 # allow 1% roundingBind every tool to a narrow invoking principal scoped to the specific function name and execution role — never grant the agent loop control over an entire AWS account or a wildcard on the Stripe Connect tenant. Issue tool-invocation tokens with a short TTL and rotate them out-of-band whenever the tool’s URL or signing key changes, so a leaked credential cannot stay valid across a deploy. Track each tool call’s `toolName + turnId` as the idempotency key so a duplicate event short-circuits to the prior result.
Place the tool runtime behind the same private-link posture used by the serving lab so agent traffic never reaches the public internet; expose a single relay per tool class with mTLS pinned to the agent runtime. Reserve a quota headroom budget per tool — concurrent calls plus per-second peak — so an autoscaling peak cannot 429 a tool that another agent has just enrolled. Pin egress paths to the same VPC as the working memory store, so retries cannot route through an unintended region.
# Bash — declarative tool catalog. The schema, the IAM principal, and the
# quota headroom ship together so a new tool ships the safety posture too.
cat > tools.yaml <<'YAML'
tools:
- name: search_retrieval
schema:
type: object
properties:
query: { type: string }
top_k: { type: integer, minimum: 1, maximum: 10 }
required: [query]
iam_principal: arn:aws:iam::123:role/agent-tool-search
quota:
concurrent_calls: 25
requests_per_second: 50
tls:
private_endpoint: vpce-0a1b2c-agent-runtime.sagemaker.runtime
mtls_required: true
- name: create_checkout
schema:
type: object
properties: { amountUsd: { type: integer, minimum: 1 } }
required: [amountUsd]
iam_principal: arn:aws:iam::123:role/agent-tool-stripe-connect
quota:
concurrent_calls: 5
requests_per_second: 10
require_human_in_the_loop: true # modally-priced side effect.
YAML
# Apply via the agent control plane.
polsia-agentctl tools sync --from tools.yaml --cluster agent-prodGrant the agent runtime write access to its own session-scoped turn log (insert only) and read access to a narrow slice of the long-term store scoped to the active user; never grant the runtime write access to long-term memory, because a corrupted episodic log should never silently rewrite a semantic fact. Rotate the session log’s signing key per session and bind it to the user id so log leaks across sessions are cryptographically distinguishable. Restrict the decryption principal to the active session id so memories do not bleed across user boundaries after a deploy.
Place the working turn log in the same region as the agent runtime for low-latency writes, and replicate long-term memory to a second region asynchronously so a region outage does not strand an in-flight session. Size the working log for `maxTurnsPerSession × averageBytesPerTurn` so the disk-cost surprise never arrives mid-conversation. Encrypt both stores at rest with a customer-managed key so a revoked key actually cuts off the agent’s access to its own memory.
-- The agent's working turn log is append-only and signed per session.
-- Long-term episodic memory is a separate projector table, not the working
-- log; offline replay and inspection never have to read the full log.
CREATE TABLE agent_long_term_memory (
user_id TEXT NOT NULL,
memory_id UUID NOT NULL DEFAULT gen_random_uuid(),
kind TEXT NOT NULL CHECK (kind IN ('episodic', 'semantic', 'preference')),
payload JSONB NOT NULL,
source_turn_ids BIGINT[] NOT NULL,
kg_consistency TIMESTAMPTZ NOT NULL DEFAULT NOW(),
PRIMARY KEY (memory_id)
);
-- Only the agent runtime INSERTs; the projector and the replay evaluator
-- read; no row is ever updated in place. A user-scoped grant cuts the
-- runtime's blast radius if one principal is revoked.
CREATE INDEX agent_long_term_user_idx ON agent_long_term_memory (user_id, kind);
GRANT INSERT ON agent_long_term_memory TO agent_runtime_role;
GRANT SELECT ON agent_long_term_memory TO agent_runtime_role;
GRANT USAGE ON agent_long_term_memory_memory_id_seq TO agent_runtime_role;
CREATE TABLE agent_memory_kg_consistency_report (
user_id TEXT NOT NULL,
report_period DATE NOT NULL,
contradictions INTEGER NOT NULL DEFAULT 0,
projector_lag_s INTEGER NOT NULL,
PRIMARY KEY (user_id, report_period)
);Grant the planner write access to the structured plan store and read access to the working session log; grant the executor only the tool calls its plan authorizes — never let the executor re-plan on its own. Both run as the same identity for audit clarity but bind to distinct signing keys so a leaked executor key cannot rewrite the plan store it just read from. Reserve a per-minute planner rate budget separately from the executor so a runaway planner cannot starve execution capacity.
Place the planner behind a separate autoscaling group from the executor so a planning spike does not starve execution capacity in a stuck-loop case. Pin the planner’s invocation path to a capacity-bounded endpoint with a fixed per-minute ceiling; an unbounded planner can rack up spend without ever executing a tool. Mirror the planner-executor handoff across the same private link used for the tool runtime, so the structured plan never traverses the public internet.
# Python — orchestration contract: planner emits a typed Plan, executor walks
# it id-by-id, replanner only fires on a real observation diff. Re-running
# the same plan after a transient network failure is safe because the
# executor is idempotent on plan id, not turn id.
from dataclasses import dataclass
from polsia_agent import generate_object, PlanSchema, Observation
@dataclass(frozen=True)
class OrchestrationContract:
session_id: str
max_replans: int = 3
max_executor_calls: int = 12
def orchestrate(contract: OrchestrationContract, user_prompt: str) -> Observation:
plan = generate_object(client, user_prompt, PlanSchema)
persist_plan(contract.session_id, plan)
replans_used = 0
for step in plan.steps:
observation = executor(
step,
idempotencyKey=f'{contract.session_id}:{step.id}',
bounded_calls=contract.max_executor_calls,
)
if not matches_expected_effect(step.expected_effect, observation):
if replans_used >= contract.max_replans:
raise StuckLoopError('replan budget exhausted')
diff = diff_observation(step.expected_effect, observation)
plan = generate_object(
client,
prompt={'original': plan, 'failed_step': step, 'diff': diff},
schema=PlanSchema,
)
persist_plan(contract.session_id, plan)
replans_used += 1
return final_response(contract.session_id, plan.steps)Grant the guardrail runtime read-only access to the agent event log so it can score replays; bind its paging policy to a dedicated chat-room and a deploy-window-only schedule so a stuck loop does not page the on-call at 3am for a development session. Restrict the guardrail’s ability to mutate state — it observes, it does not dispatch — so a compromised guardrail cannot quietly shut the agent loop down for production traffic. Never grant the guardrail write access to the turn log; the regression gate is a build-time artifact, not a runtime mutation.
Run the guardrail evaluator out-of-band against the same observability tenant as the agent events; pin a dashboard per agent class so a stuck-loop alarm can be correlated with the model-version tag the agent is running. Forward every guardrail signal to the evals pipeline so a stuck-loop rule that flipped from passing to failing has its regression gate fired before the next release. Pin a single egress path from the guardrail runtime to the eval cluster so a mis-routed alert cannot issue a self-referential firing loop.
# policies/guardrails.yaml — hard-runtime caps + stuck-loop regression
# fixtures. The runtime caps are enforced BY the runtime, not by a prompt
# instruction; the fixtures gate CI on a real replay score.
runtime_caps:
max_turns_per_session: 30
max_tool_calls_per_session: 60
max_tool_calls_per_turn: 8
max_spend_usd_per_session: 2.00
min_session_idle_seconds_before_cap_relax: 86400
regression_fixtures:
- name: no_stuck_loop_on_replay
type: replay_pair
queries:
- summarize yesterday's on-call handoffs
- reconcile vendor invoices against the open PO list
assertion: second_replay_turn_count <= first_replay_turn_count
- name: budget_cap_enforced
type: synthetic_run
prompt: loop indefinitely on a no-op tool
assertion: terminated_reason == 'budget_exceeded'
- name: tool_idempotency_holds
type: idempotency_replay
tool: create_checkout
assertion: exactly_one_side_effect_recordedBind the human-in-the-loop declaration to the tool itself, not to the prompt: mark a tool as `require_human_in_the_loop: true` in the catalog next to its schema and IAM principal so the safety posture travels with the tool as it moves between environments. Issue a signed `ConfirmationToken` from a pre-tool hook before the side effect can fire; the token bound to the exact `(toolName, argsHash, sessionId, expiresAt)` tuple so an approval cannot be replayed against a different invocation. Persist the approval row in an append-only `agent_approval` table the runtime can join on during replay auditing. Never grant any LLM principal write access to the approval table; only the human approver role and the runtime check principal can write or read.
Route confirmation requests to a dedicated pager or chat-room channel per session under a dedicated egress identity, so a guardrail signal does not share its page budget with the agent runtime that triggered it. Pin the escalation endpoint to a private link plus mTLS so a leaked URL cannot self-approve without the runtime’s signing key. Cap the escalation round-trips per session and the lifetime of a confirmation token so a stale escalation cannot be replayed after the user’s shift ended; the runtime treats the deadline as a hard cap, not a soft promise. Run the approval channel from a different region than the tool runtime so a region outage does not strand a confirmation mid-flight without falling back to denying the side effect.
# TypeScript — tool-declared human-in-the-loop gate. The runtime MUST refuse
# to call the side effect unless an approval record matches this token's
# `id` and has not expired; never trust the model emitting `approve=true`
# inside the tool's arguments — that is the canonical jailbreak of an HITL
# gate.
import { generateObject } from '@/lib/ai/client';
type ConfirmationToken = {
id: string;
toolName: string;
argsHash: string;
sessionId: string;
expiresAt: Date;
};
type Approval = {
tokenId: string;
approverId: string;
ack: 'acknowledged' | 'denied';
ackAt: Date;
};
const PROMPT_ESCALATION = `The agent is requesting approval before a high-stakes
side effect: <tool>. The runtime will NOT invoke the tool until you explicitly
acknowledge this token. Reply with the token id ONLY.`;
async function pauseForHumanApproval(
token: ConfirmationToken,
getApproval: (id: string) => Promise<Approval | null>,
): Promise<void> {
const prompt = PROMPT_ESCALATION.replace('<tool>', token.toolName);
await pageOncall({ channel: 'agent-hitl', subject: token.id, body: prompt });
const approval = await waitFor(
() => getApproval(token.id),
{ deadline: token.expiresAt },
);
const valid =
approval != null &&
approval.ack === 'acknowledged' &&
approval.tokenId === token.id &&
token.expiresAt > new Date();
if (!valid) {
throw new HumanApprovalRequiredError(
`side effect '${token.toolName}' blocked: no valid approval for token ${token.id}`,
);
}
}
async function invokeHighStakesTool(
decision: { tool: string; args: Record<string, unknown> },
sessionId: string,
) {
if (decision.tool !== 'create_checkout') {
return invokeToolDeterministic(decision, sessionId);
}
const token: ConfirmationToken = await issueConfirmationToken({
toolName: decision.tool,
argsHash: sha256(JSON.stringify(decision.args)),
sessionId,
expiresAt: new Date(Date.now() + 5 * 60_000), // 5 min
});
await pauseForHumanApproval(token, getApproval);
return invokeToolDeterministic(decision, sessionId, { confirmationToken: token.id });
}See what other learners are clarifying as they work through this walkthrough.
Pair this agents walkthrough with the evals pipeline lab so the stuck-loop regression fixtures and the runtime budget caps share the same golden set, and with the MLOps toolchain lab so the agent's tracked run ids feed the same hosted tracking server as the model training runs the gate is scoring against.
Connect hands-on practice with certification preparation by mapping lab work to exam domains.
Explore the certification roadmap