How Claude Code is built, and how to apply the same design to an ITSM agent platform with 50+ MCP servers: vague queries, context across agents, huge tool results, tool overload, overlapping systems, parallel execution, failures and self-correction.
This guide is for engineers who already have an agent in production, want to understand how Claude Code works under the hood, and want to apply the same design to an ITSM platform built on ServiceNow, Zendesk, Jira and dozens of other MCP servers. It focuses on the problems that only show up at scale: too many tools, overlapping systems, huge tool results, context that leaks between agents, and mistakes that repeat. Each chapter takes one problem, explains why it happens, and gives patterns, trade-offs and code sketches you can adapt.
The model's context is the scarcest resource in the system. Every design choice below is a way to put fewer, better tokens in front of the model at each step. Data lives in the data plane; only what the model needs to decide the next step enters the context plane.
Separate the data plane from the context plane. Tool results go to a store; the model sees handles, schemas, counts and samples.
Move work out of the model when code can do it. Routing rules, filtering, joins, dedup, retries and arithmetic are deterministic. Use the model for judgement, not bookkeeping.
Every boundary gets a contract. Agent to agent, agent to MCP server, planner to executor: typed inputs, typed outputs, explicit errors, budgets.
Overview/How Claude Code works
Start here
How Claude Code works
4 min read
Claude Code is a small loop wrapped in a very careful harness. The model reasons; the harness decides what the model sees, which tools it has, what it may do without asking, and how work is split across contexts. Almost every hard problem in this guide has a Claude Code answer you can copy into an ITSM agent (How Claude Code works).
Claude Code's harness around the loop, and the ITSM component each part becomes
Claude Code works in three blended phases: gather context (search and read), take action (edit, run commands), and verify results (run tests, check output). The model picks the next tool from what it learned in the previous step, and the user can interrupt and steer at any point.
For ITSM the same loop becomes: gather (search tickets, CMDB, knowledge base, recent changes), act (update a ticket, run a runbook step, draft a reply), verify (re-read the record, confirm the SLA timer moved, ask the user). The verify phase is what most ITSM agents skip, and it is where most wrong answers could have been caught.
Checkpoints assume local, reversible changes. In ITSM almost every write is remote and visible to customers or engineers. Replace "undo" with "approve first, then write once, with an audit trail".
One user, one session. Claude Code serves a developer in a terminal. An ITSM platform serves many users and tenants at once, so memory, permissions and data must be scoped per tenant and per user.
Files as the universal interface. Code lives in files the agent can grep. ITSM data lives behind APIs with rate limits, pagination and inconsistent schemas, which is why chapters 3 and 6 exist.
Context/Vague queries and scope
Chapter 1
Understanding vague queries
7 min read
ITSM users do not write precise queries. They write "give me network jira changes done today", and almost every word needs resolving before any tool can run. "Network" is not a search keyword. It names a business domain that maps to a group of Jira projects. "Changes" could be an issue type, or simply "things that changed". "Done today" depends on whose today, and on what "done" means in each workflow. Get this step wrong and everything downstream is precise about the wrong thing. That is why scope resolution comes before routing, briefs and sub-agents.
A vague request becomes a resolved query: terms matched against a domain catalog, then a strategy and concrete filters
Parse the request into slots before touching any system. The model is good at this when it fills a fixed schema rather than writing free text:
python
class ParsedQuery(BaseModel):
intent: Literal["list", "count", "summarise", "trend", "detail", "action"]
entity: str | None # "change", "incident", "ticket", "request"...
systems: list[str] # named explicitly by the user, e.g. ["jira"]
domain_terms: list[str] # candidate scope words: ["network"]
keywords: list[str] # real free-text search terms, if any
time: str | None # raw phrase: "today", "last sprint", "since Monday"
filters: dict # status, priority, assignee phrases as written
For "give me network jira changes done today": intent list, entity change, systems ["jira"], domain_terms ["network"], keywords [], time "today", filters {"status": "done"}. Nothing is resolved yet. This step only separates the words by role.
The catalog maps the words people use to the concrete scopes each system understands. It is the single most valuable asset in an ITSM agent, because no model can guess that "network" means seven Jira projects and three ServiceNow assignment groups.
Each candidate word is either a scope (it narrows where to look) or a keyword (it narrows what text to match). Test each word against the catalog:
Catalog match
Treat as
Example
Exact alias, high confidence
Scope
"network" becomes the Network Platform projects
Near match from embeddings, one clear winner
Scope, stated in the answer
"networking team" becomes Network Platform
Several plausible domains
Ambiguous: see "clarify only when it matters"
"platform" could be Network Platform or Data Platform
No match
Keyword, searched in summary and description
"BGP flap" becomes text ~ "BGP flap"
Match plus extra words
Both
"network timeout": scope may be network, "timeout" is a keyword
When a word could be either, prefer the scope reading and keep the keyword as a fallback: if the scoped query returns nothing, retry as a text search and say so.
Time: "today" means the user's today. Resolve it in the user's time zone to an explicit range, and pass that range, not the word, to every system. Jira functions such as startOfDay() use the timezone of the account that runs the query, which may not be the user's.
Status: "done" means different states in different workflows. Map it through the catalog (Jira status category Done; ServiceNow closed or resolved).
Entity: "changes" maps to Jira issue types Change and Standard Change here. If a domain has no Change issue type, fall back to "issues updated in the range" and say so.
The resolved query for the example becomes one concrete Jira query:
python
resolved = ResolvedQuery(
system="jira",
scope={"domain": "network", "projects": ["NET", "NETOPS", "FW", "LB", "DNS", "WAN", "NETSEC"]},
entity={"issuetype": ["Change", "Standard Change"]},
time={"from": "2026-11-30T00:00:00+05:30", "to": "2026-11-30T14:30:00+05:30", "field": "status_change_to_done"},
interpretation="Changes moved to Done today (IST) in the 7 Network Platform projects",
confidence=0.9,
)
# JQL built from it:
# project in (NET, NETOPS, FW, LB, DNS, WAN, NETSEC) AND issuetype in (Change, "Standard Change")
# AND statusCategory = Done
# AND status CHANGED TO Done DURING ("2026-11-30 00:00", "2026-11-30 14:30")
Asking every time makes the agent useless; never asking makes it confidently wrong. Ask only when the interpretations would give materially different answers:
Resolve with the best interpretation and state it in one line at the top of the answer: "Changes moved to Done today in the 7 Network Platform projects (NET, NETOPS, FW, ...)."
Offer one-tap alternatives when there is a close second reading: "Only NET" or "All projects".
Ask before running only when confidence is low and the readings differ a lot, or when the action writes something.
Cheap disambiguation by data: if two domains match, count results in both. If one is empty, the answer is obvious and no question is needed.
#Who resolves scope when sub-agents and AI-enabled MCP servers are involved
Cross-system terms resolve centrally. "Network" means projects in Jira and assignment groups in ServiceNow. Only the orchestrator, with the shared catalog, can keep those consistent.
Sub-agents get the resolved scope and the original words. The brief carries scope, time and entity as concrete values, plus the user's phrase for context. The sub-agent does not re-guess the scope.
System-local refinement stays local. An AI-enabled Jira server may know component-level detail the catalog lacks. Let it narrow inside the given scope, never widen it, and return the interpretation it actually used.
Every answer echoes its interpretation, so the user and the verifier can see what was searched.
Claude Code has no ontology. It resolves vague requests by exploring: it searches the codebase for the words, reads the structure, and builds its own picture of what "the auth module" means. Project vocabulary that cannot be discovered goes in CLAUDE.md ("'the API' means services/api"). When the request is ambiguous it can ask you a question, and plan mode lets it propose an interpretation before acting.
For ITSM, exploring 50 live systems for every query is too slow and too rate-limited, so build the catalog ahead of time. Keep the exploring behaviour by giving the agent catalog tools such as resolve_scope(term), list_domains(parent) and count(scope). Then it can look things up when the catalog misses, much as Claude Code searches files. The ITSM.md plays the CLAUDE.md role for vocabulary the catalog cannot harvest, and the stated interpretation plays the role of plan mode.
Collect 200 or more real user queries and label the resolved scope, entity, time range and status for each. Measure exact-match on project sets, the clarification rate, and how often users override the stated interpretation. Every override goes back into the catalog as a new alias or a corrected mapping (chapter 9).
Context/Context across agents
Chapter 2
Context across servers and sub-agents
4 min read
When 50+ servers feed one agent, and some of those servers are agents themselves, context fails in three ways: it overflows (too much arrives), it leaks (one agent's reasoning pollutes another's), and it fragments (no one holds the full picture). The fix is to treat context like memory in a distributed system: scoped, owned, and passed by reference.
Each agent keeps its own context; only typed results and handles cross the boundary
#Treat AI-enabled MCP servers as sub-agents with a contract
An MCP server that runs its own LLM (say, a "Jira analyst" server that answers questions in natural language) is a sub-agent. Treat it like one:
Send a resolved task, not a conversation. Resolve scope first (chapter 1), then pass a self-contained brief: the user's original words, the resolved scope (project keys, groups, date range in absolute terms), the output schema you want, and a token budget for the answer. Never forward your full message history.
Let it refine, not re-guess. An AI-enabled server may narrow the scope with knowledge it has (components, labels), but must not widen it, and must return the interpretation it used.
Ask for structured output. Request JSON matching a schema ({answer, records_ref, confidence, sources[]}), not prose. Prose answers from sub-agents are the main source of context poisoning: the orchestrator cannot tell fact from guess.
Do not import its transcript. Its internal reasoning stays inside it. You get the result and, if needed, a reference to the full data.
Version it like an API. Its prompt and model can change under you. Pin versions in the registry and run its contract tests in CI.
python
from pydantic import BaseModel
class SubAgentTask(BaseModel):
question: str # the user's words, for context
scope: dict # resolved: {"projects": ["NET", "FW"], "from": "...", "to": "..."}
interpretation: str # "Changes moved to Done today in Network Platform"
output_schema: dict # JSON schema the answer must satisfy
max_answer_tokens: int = 800
trace_id: str
class SubAgentResult(BaseModel):
answer: dict # validated against output_schema
data_ref: str | None # handle to full records in the result store
confidence: float # 0..1, self-reported, calibrated by evals
sources: list[str] # record ids or URLs
interpretation_used: str # what it actually searched, after any refinement
error: str | None = None
The blackboard is the key idea for many agents. Agents write findings to named keys (customer.id, incident.root_cause), and other agents read only the keys they need. This replaces "pass everything to everyone" with explicit data flow you can trace.
Measure actual usage per slice in your traces. When a slice blows its budget, fix the producer (shorter tool output, tighter retrieval) rather than raising the budget.
Compaction: when the conversation passes about 60 to 70% of the window, summarise old turns into a structured state (goal, decisions, open questions, handles) and drop the raw turns.
Tool-result clearing: old tool results are the cheapest thing to drop because their data is already in the result store. Claude's context editing does this automatically.
Re-state the goal at the end of context each turn (a short todo or plan). This counters drift in long sessions.
Each subagent starts with a fresh context window (or a copy, when it is forked), its tool calls stay out of the parent's context, and only a summary comes back. Persistent rules live in CLAUDE.md, which loads every session, so they survive compaction. Compaction keeps requests and key snippets, and you can tell it what to preserve. For ITSM: one investigator subagent per system returning typed findings, an ITSM.md per team for rules that must never be compacted away, and compaction instructions that always keep ticket ids, timestamps and decisions.
Context/Large tool results
Chapter 3
Large tool results
4 min read
A tool that returns 1,000 records at 5 KB each produces about 5 MB of JSON. At roughly 3 to 4 characters per token that is 1.2 to 1.7 million tokens: larger than most context windows, and far past the point where accuracy holds up. The answer is never "put it in the context". The model should see the shape of the data and query it.
Records go to a result store; the model sees a profile and queries it with code
The cheapest token is the one never fetched. Before reaching for summarisation, make the source do the work:
Query parameters: expose filters, date ranges, status and assignee in the tool schema so the model can ask for 40 records instead of 1,000.
Field projection: let the tool accept fields=["id","status","priority","updated"]. A 5 KB record is usually 300 bytes of useful fields and 4.7 KB of metadata, HTML and audit history.
Server-side aggregation: add tools like count_by(field) and top_n(field, n). Most operational questions are aggregations.
Hard caps: the tool returns at most N rows plus total_count and a message such as "Showing 50 of 1,000. Narrow by status or date." This teaches the model to refine instead of paginating blindly.
When you do need all the records (analysis, joins, reports), fetch them into a result store and give the model a handle:
python
import duckdb, json
def ingest(records: list[dict], source: str, con: duckdb.DuckDBPyConnection) -> dict:
table = f"r_{source}_{abs(hash(json.dumps(records[:1])))%10**6}"
flat = [flatten(r, keep=FIELD_ALLOWLIST[source]) for r in records] # drop HTML, audit trails, blobs
con.register("tmp", to_arrow(flat))
con.execute(f"CREATE TABLE {table} AS SELECT * FROM tmp")
return {
"handle": table,
"rows": len(flat),
"columns": describe_columns(con, table), # name, type, null %, distinct count
"top_values": top_values(con, table, k=5), # for low-cardinality columns
"sample": con.execute(f"SELECT * FROM {table} LIMIT 5").fetchall(),
}
# The model gets ~1-2k tokens of profile and calls run_sql(handle, "SELECT ...") next.
The model then writes read-only SQL against the handle. Results come back small (an aggregate, a top 20) and exact, because the database did the arithmetic. Lock it down: one SELECT only, no file or network access, a row cap on results, a timeout.
Instead of calling tools one by one through the context, the model writes a short program that calls the tools, filters and joins the data in a sandbox, and returns only the final result. Anthropic reports one workflow falling from about 150,000 tokens to about 2,000 with this approach (Code execution with MCP); the same idea ships as programmatic tool calling (Advanced tool use). The cost is a sandbox you must secure and observe.
For unstructured content (ticket descriptions, comments, logs) that SQL cannot summarise, split the records into chunks, give each chunk to a worker with a narrow extraction prompt ("return root cause category, product, customer impact as JSON"), then aggregate the structured outputs in code. Workers run in parallel with fresh contexts, and the orchestrator sees only the merged table.
Paginated tool with cursor; render rows in the UI, not in the context
Clean before you store: flatten nested JSON, drop HTML and audit fields, redact PII, normalise dates and enums. A good cleaner often cuts payload size by 80 to 95% before any model sees it.
Claude Code never loads a whole repository. It finds files by pattern, searches content with regex, and reads only the parts it needs: count and locate first, then read. When a single output is so large that context refills right after each compaction, it stops auto-compacting and reports an error instead of looping. For ITSM, the equivalent of "grep, then read lines 200 to 260" is "count matching incidents, profile them, then fetch the 20 that matter".
Routing/Too many tools
Chapter 4
Too many tools
3 min read
Fifty servers with 10 to 40 tools each means 500 to 2,000 tool definitions. Loading them all costs tens of thousands of tokens per call and, worse, the model picks the wrong tool more often as the list grows. Anthropic reports that letting the model search for tools instead of loading all of them cut definition tokens by about 85% and raised tool-selection accuracy on their MCP evaluation from 49% to 74% for Opus 4 (Advanced tool use). The RAG-MCP paper reports a similar effect from retrieving tools rather than listing them.
Two-stage selection: pick candidate servers, then load only their relevant tools
Before building tool search, shrink the catalogue:
Consolidate. Replace get_issue, get_issue_comments, get_issue_links with get_issue(id, include=["comments","links"]).
Task-level tools.find_customer_tickets(customer, since) that hits the right systems internally beats five CRUD tools.
Allow-lists per agent. A billing agent never sees deployment tools. Enforce this in the gateway, not in the prompt.
Write descriptions for the model. Say when to use the tool, when not to, and what it returns. Add one or two input examples for tricky schemas (Writing tools for agents).
Stage 1, servers: classify the request into domains (rules first, then a small model or embeddings over server descriptions). Output: 2 to 5 candidate servers.
Stage 2, tools: embed tool descriptions plus example queries. Retrieve the top 5 to 15 tools from the candidate servers only.
Always-on core: a handful of tools are always loaded (search tools, run_sql, ask_user, finish).
Escape hatch: give the model a search_tools(query) tool so it can fetch a tool the retriever missed. On Claude this is the built-in tool search tool with deferred loading.
python
def select_tools(query: str, agent: str, k: int = 12) -> list[ToolDef]:
allowed = registry.allowed_tools(agent) # gateway allow-list
servers = route_servers(query, candidates=registry.servers_for(agent)) # chapter 5
pool = [t for t in allowed if t.server in servers]
ranked = tool_index.search(embed(query), within=pool, k=k) # vector search over desc + examples
return CORE_TOOLS + ranked
Tool definitions sit near the start of the prompt. If they change every call, you lose prompt caching. Two ways to keep the benefit: keep a stable core set at the top and append dynamic tools after it, or use deferred loading so the cached prefix holds only the search tool.
Build a tool-selection eval: 100 to 300 real queries labelled with the correct tool(s). Track recall@k of the retriever and the model's final tool choice. Re-run it whenever a server adds or renames tools: a new tool with a vague description can silently steal traffic from an old one.
Claude Code ships a small set of general tools and treats everything else as optional. MCP tool definitions are deferred by default: only tool names and server instructions use context until a tool is needed, and the tool search finds and loads it. Skills follow the same idea: their descriptions load at session start and the full instructions load only when used. For ITSM, keep five or six core tools always loaded, defer every MCP server's tools behind search, and package runbooks as skills that load on demand.
Routing/Overlapping systems
Chapter 5
Routing across overlapping systems
3 min read
ServiceNow and Zendesk both have "tickets". Jira and GitHub both have "issues". Confluence and SharePoint both have "docs". When a user asks "show me open tickets for Acme", routing to one system is a guess, and routing to all is expensive. The fix is to make ownership explicit and to route with rules first, models second.
Rules first, then a classifier, then fan-out or a clarifying question when confidence is low
Routing runs on the resolved query from chapter 1, not on the raw text. Often the domain alone settles it: "network changes" resolves to Jira projects and ServiceNow change requests owned by network groups, and the user's word "jira" narrows it to one.
Deterministic rules (fast, exact). An ID pattern (INC0012345), an explicit system name ("jira", "in Zendesk"), a resolved domain that lives in only one system, or a user's default system settles it. Expect 30 to 60% of traffic to stop here.
Entity and intent classifier. A small model or fine-tuned classifier maps the request to entities and audience: "customer complaint" means Zendesk; "outage", "change" means ServiceNow. Output a probability per server.
Decision by confidence:
One server above threshold (say 0.8): route there.
Two servers close together: fan out to both in parallel, then merge (chapter 6).
Nothing confident: ask a clarifying question, offering the two likely systems.
Follow links. If a Zendesk ticket carries a ServiceNow incident id, fetch the linked record as a second step rather than guessing.
Claude Code mostly lets the model route: it picks tools and subagents from their descriptions, guided by rules in CLAUDE.md. Subagents are chosen by their description field, so "use for customer-facing support tickets" in a Zendesk investigator's description is effectively a routing rule. At ITSM scale, keep that model-led routing for the ambiguous tail, but put system-of-record rules in the registry and in your ITSM.md so the common cases are decided by data, not by wording.
Routing/Merging results
Chapter 6
Merging and narrowing results
2 min read
When two or more servers answer, you get overlapping, conflicting and differently shaped records. Narrowing them down is a data problem first and a model problem last.
Normalise, link, dedupe, rank, then give the model a small, sourced result
Status and priority mapping tables live in config, reviewed by people who know each system. This is where most "the agent said it was closed" bugs come from.
Hard links first: explicit cross-references (a Zendesk field holding the incident id, a correlation id, a URL in the description).
Soft matches second: same customer, created within a time window, and title similarity above a threshold (embeddings or trigram). Mark these as "likely the same", never merge them silently.
Cluster linked records into one logical item with several sources.
When sources disagree, the registry decides: the system of record for that field wins (ServiceNow for incident status, Zendesk for customer communication). Keep the losing value visible as context ("Zendesk shows pending; ServiceNow shows resolved at 14:02"), because the disagreement is often the answer the user needs.
Score clusters by relevance to the query (embedding similarity or a reranker), recency, priority and source authority. Pass the model the top 10 to 30 clusters as compact rows, plus the total count and a handle to the rest. The model writes the answer with source links for every claim.
Rule of thumb: if the model is deduplicating or counting, the pipeline is unfinished. Those are code jobs; the model should only judge relevance where rules cannot.
The closest Claude Code analogue is reading several files and reconciling them before editing: it gathers, compares and only then acts, and its verify step (running tests) catches mismatches. ITSM needs this as an explicit service because records from different systems describe the same real-world incident in different shapes, and no test suite will tell the agent they disagree.
Execution/Parallel vs sequential
Chapter 7
Parallel vs sequential execution
3 min read
Run steps in parallel when they do not depend on each other's output, and in sequence when one step needs another's result. The trick is to make those dependencies explicit so the executor, not the model, decides.
The planner emits a dependency graph; independent steps run together, dependent ones wait
Ask the planner for a DAG instead of a list. Each step names its inputs, so the executor can see what can run together. This is the idea behind LLMCompiler, which reported lower latency and cost than sequential ReAct-style calling.
import asyncio
async def run_plan(plan, budget):
results, done = {}, set()
pending = {s["id"]: s for s in plan["steps"]}
sem = asyncio.Semaphore(8) # global concurrency cap
while pending:
ready = [s for s in pending.values() if set(s.get("after", [])) <= done]
if not ready:
raise PlanError("cycle or missing dependency")
async def run(step):
async with sem, per_server_limit(step["tool"]): # e.g. 2 concurrent calls per server
args = resolve_refs(step["args"], results)
return step["id"], await call_with_policy(step["tool"], args, budget)
for sid, res in await asyncio.gather(*(run(s) for s in ready)):
results[sid] = res; done.add(sid); pending.pop(sid)
if res.failed and res.critical:
return await replan(plan, results) # ask the planner to repair
return results
The model can request several tool calls in one turn, so independent reads (several searches, several file reads) can go out together, and it can launch several subagents at once to investigate in parallel, each in its own context. Edits and commands with side effects happen step by step, with permission checks. For ITSM: let investigators for ServiceNow, Zendesk and monitoring run in parallel; serialise every write.
Execution/Frameworks and failures
Chapter 8
Frameworks and failure handling
4 min read
Framework choice matters less than the primitives you need: durable state, explicit control flow, parallel branches, human interrupts and tracing. With 50k lines already written, do not rewrite to adopt a framework. Adopt one where it removes code you would otherwise maintain.
Durable execution: retries, timeouts, resume after crash, long waits
Not agent-aware; you write the agent logic
Runs are long, failures are costly, or you need exactly-once side effects
Custom (asyncio + Postgres)
Full control, no abstraction tax
You own checkpointing, tracing, interrupts
Your existing system already has these pieces
A common production shape is a light agent layer for the loop, with a durable execution engine underneath. Chapter 13 compares the free, self-hostable options and recommends Temporal with Pydantic AI.
Partial answers with explicit gaps: "Zendesk returned 12 tickets. ServiceNow was unavailable, so incident status is missing." This beats a failed request or, worse, a silent omission.
Budgets propagate down: token, cost, time and step caps per request, split across sub-agents, so one runaway branch cannot spend everything.
Write safety: writes need idempotency keys, a dry-run or confirmation step, and an audit record. Never auto-retry a write without idempotency.
Dead-letter queue: failed requests with their trace go to a queue for review; they become eval cases.
Tool errors and permission denials go back to the model as tool results, so it can adapt (try another path, fix arguments, ask the user) instead of crashing. Hooks run before and after tool calls and can block an action deterministically, whatever the model decided. Permission modes set how much it may do without asking, and an auto mode uses a classifier to block risky actions. For ITSM writes, copy all three: errors as information, hooks as policy, and permission levels by risk (read freely, propose changes, auto-apply only low-risk actions).
python
# A PreToolUse-style policy hook for ITSM writes
def pre_tool_use(call, ctx) -> Decision:
if call.tool == "servicenow.update_incident":
inc = ctx.cache.get(call.args["id"])
if inc and inc.priority == 1 and not ctx.user.has_role("major_incident_manager"):
return Decision.block("P1 incidents need a major incident manager to approve changes.")
if "state" in call.args and call.args["state"] == "closed" and not ctx.verified:
return Decision.ask("Closing an incident: confirm the fix was verified?")
return Decision.allow()
def post_tool_use(call, result, ctx):
result.data = redact_pii(result.data) # before it reaches the model
audit.write(user=ctx.user, tool=call.tool, args=call.args, status=result.status)
Quality/Feedback and self-correction
Chapter 9
Feedback and self-correction
3 min read
Self-correction only works when the agent gets a real signal: a failed check, a tool error, a contradiction, or a user saying "that's wrong". Asking a model to "review your answer" without new information often does not help and can make answers worse (Huang et al. 2023). So the job is to create signals, both inside a run and across runs.
Signals inside a run trigger repair; user feedback across runs becomes rules, examples and evals
When a check fails, send the specific failure back to the agent ("The answer cites INC0012399, which is not in the results") and allow one or two repair attempts. A separate critic model helps for judgement calls such as relevance or tone, using tool-grounded critique in the style of CRITIC rather than free reflection.
Capture feedback with context: thumbs up or down, a free-text correction, and the trace id. Then triage each correction into one of these outlets:
Correction memory (fast, scoped). Store rules like "for Acme, tickets live in Zendesk org 4411" or "'P1' means priority 1 in ServiceNow, 'urgent' in Zendesk", keyed by user, team or domain. Retrieve relevant rules into the prompt for matching requests. Give each rule an owner and an expiry so stale rules do not poison later runs.
Catalog, routing and mapping data. "I meant only firewall" becomes a narrower alias or a scope preference for that user; "No, check Zendesk" becomes a labelled routing example; a wrong status becomes a mapping-table fix.
Few-shot examples. Good, corrected trajectories become retrievable examples for similar requests.
Tool description changes. If the model keeps misusing a tool, fix its description or schema, then re-run the tool-selection eval.
Eval cases. Every confirmed failure becomes a regression test (chapter 10). This is the outlet that stops the same mistake coming back.
Do not let the agent rewrite its own system prompt from user feedback automatically. Rules go into a scoped, reviewable memory store; prompt and tool changes go through review and evals.
Three mechanisms: a verify phase in the loop (run the tests, read the output) that gives the model a real signal; interrupt and steer, so the user can correct it mid-task; and memory (CLAUDE.md plus auto memory) that carries learnings into the next session. For ITSM: verify every write by re-reading the record, let agents surface their plan so users can correct it early, and route corrections into scoped memory and eval cases.
Quality/Evals and observability
Chapter 10
Evals and observability
2 min read
You cannot know whether a change made the system better without measuring it. At this scale, evaluate each layer separately, because an end-to-end failure could come from routing, tool selection, data handling or reasoning (Demystifying evals for AI agents).
Real vague queries labelled with projects, entity, time range, status
Exact match on project sets, clarification rate, user override rate
Routing
Labelled requests to systems
Accuracy, fan-out rate, clarifying-question rate
Tool selection
Requests to correct tools
Retriever recall@k, final tool accuracy
Data handling
Requests with known answers over fixed datasets
Exact match on numbers and record ids
Merging
Overlapping records with known links
Link precision and recall
End to end
Real tasks with graded answers
Task success (rubric judge, calibrated on human labels), cost, latency
Regression
Every confirmed user-reported failure
Pass rate, must not drop
Run the cheap layers on every pull request and the end-to-end set nightly. Snapshot MCP data for evals so results do not change when the live systems do.
One trace per request, with a span for every model call, tool call, routing decision and sub-agent task. Record: tokens in and out per context slice, tool result size before and after cleaning, routing scores, retries, breaker state, prompt and tool versions. Use OpenTelemetry GenAI conventions so the data can go to any backend (Langfuse, Phoenix, LangSmith, Datadog).
Tokens per request by slice, and the p95 of tool result size: catches context bloat.
Routing fan-out and clarification rates: catches registry drift.
Tool error rate and breaker openings per server: catches flaky servers.
Repair-attempt rate and verification failures by check: shows where the model struggles.
Thumbs-down rate by intent, with links to traces: tells you what to fix next.
When multi-agent runs fail, tag the traces with the MAST taxonomy (specification issues, inter-agent misalignment, task verification) to see whether to fix prompts, topology or checks.
Every session is saved as a transcript of messages, tool calls and results, which can be resumed or forked, and /context shows what is using the window. That is the minimum for an ITSM platform: a complete, replayable trajectory per request, and visibility into what filled the context.
Build/Reference architecture
Chapter 11
Reference architecture
21 min read
The whole platform is three layers, and only the bottom one grows. A small agent core reasons with a fixed set of eight tools. A connector hub turns those tools into calls to whichever MCP servers fit. Connectors are the MCP servers themselves, each described by a manifest. Adding a server means adding a manifest, plus a small adapter when the server needs one. The core, its prompts and its tools stay exactly as they are.
This is the Claude Code shape. Claude Code does not grow a new agent for every MCP server you connect. The loop stays the same, the server's tools are indexed and loaded on demand, and settings decide what each tool may do.
Your sketch has the right skeleton: many kinds of callers, one API layer, one orchestrator, and work fanned out to systems. What follows is what goes wrong with it at scale, and the changes that fix it. The improved diagram keeps your layout.
Your sketch, improved: the harness box filled in and wrapped around the orchestrator, agents replaced by connectors behind a hub, and a verified answer
#
In the sketch
What goes wrong
Change
1
Harness, context, memory and sessions sit in a side box marked "??"
This is the heart of the system, not an add-on. If the orchestrator only calls out to it, context gets assembled differently in different places, and nothing owns what the model sees
Make the harness the thing the orchestrator runs inside: sessions, a context builder with the 7 layers below, memory files, catalogs and the model client. Every model call goes through the context builder
2
One LLM agent per system (Jira agent, Zendesk agent, SharePoint agent, nth agent)
N prompts to maintain, N times the tokens and latency, context lost at every hand-off, and each new system means a new agent to build and evaluate
Systems become connectors: an MCP server, a manifest and a small code adapter behind a connector hub. Use a real sub-agent only for bulky self-contained tasks, through delegate, or for AI-enabled MCP servers
3
The orchestrator fans straight out to agents
A vague query ("network changes today") either hits every system or the wrong one
Resolve scope first with the domain catalog, then route by which system owns the record (chapters 1 and 5)
4
Agents return their output to the orchestrator
1,000 records of 5 KB each lands in the context, and the model drowns
Results go to the result store in the hub. The orchestrator sees counts, samples and a handle, and queries the rest with SQL (chapter 3)
5
"Final output" loops back to the orchestrator and the API layer
Nothing checks the answer, and an unbounded loop can retry forever
A verify step inside the orchestrator checks counts, coverage and citations, with at most two repair rounds, then streams the answer to the caller
6
No durability
A pod restart mid-run loses the work, and waiting for an approval holds a process
Each request is a Temporal workflow. Model and tool calls are activities, and approvals are signals (chapter 13)
7
No place for writes or approvals
An agent can create or change records with no gate
act goes through policy in the hub, and risky actions wait for approval
8
Agent and System callers look the same as users
Permissions and audit get lost, and long system jobs block the request
The API layer carries identity through to every connector call, gives each request a session id, and runs system and agent callers as async jobs with a webhook back
9
No feedback, traces or evals
The same mistakes repeat, and you cannot prove a change helped
Every run is traced. Ratings and corrections feed memory, catalogs and eval sets (chapters 9 and 10)
What the harness box contains, concretely:
Part
Stores or does
Lives in
Sessions and conversations
Messages, resolved scope, decisions, data handles, approvals
Postgres, plus Temporal workflow history for each run
Context builder
Assembles the 7 context layers before every model call, compacts at about 80%
Code in the agent worker
Memory
ITSM.md files at org, team and user level; reviewed corrections
Postgres or git, loaded at session start
Catalogs
Domain catalog, field catalogs, tool index
Postgres with pgvector
Model client
Azure OpenAI calls, retries, token budgets
Pydantic AI AzureProvider
#Every problem we discussed, solved in this design
Each problem below has a specific place in the improved diagram. The walkthroughs use real ITSM requests.
#
Problem
Where it is solved
Deep dive
1
Vague scope: "network jira changes done today"
Orchestrator step 1 (Scope), using the domain catalog in the harness
Chapter 1
2
Context across AI-enabled MCP servers and sub-agents
delegate (child workflow with its own context) and the context builder
Chapter 2
3
1,000 records of 5 KB each
Result store in the connector hub, query_results, capped tool results in the context builder
Chapter 3
4
Too many tools, tool selection
8 core tools; the tool index in the catalogs; find_tools for the rare server-specific tool
Chapter 4
5
ServiceNow and Zendesk overlap
Step 1 routes by the owns field in each manifest, then the router's rules and classifier
Chapter 5
6
Narrowing overlapping results
Merge and dedupe in the connector hub, ranking before the answer
Chapter 6
7
Parallel vs sequential
Step 2 (Plan) builds a step graph; Temporal runs independent activities in parallel
Chapter 7
8
Which framework
Temporal + Pydantic AI, self-hosted, with Azure OpenAI
Chapter 13
9
Failures
Temporal retries and timeouts; hub limits and circuit breakers; partial answers that say what failed
Chapter 8
10
Self-correction from user feedback
Step 4 (Verify) and repair inside a run; Feedback + evals into memory and catalogs across runs
Chapter 9
11
Making fewer mistakes, and proving it
Verify step, policy on writes, per-layer evals, traces
Chapter 10
12
300 Jira projects with different custom fields
Jira adapter in the connector hub, field catalog in the harness catalogs, describe
Chapter 12
1. Vague scope
"Network jira changes done today". Step 1 looks up "network" in the domain catalog and gets the Network Platform group: Jira projects NET, FW, LB, DNS, WAN and the ServiceNow Network assignment groups. "Today" becomes midnight to now in the user's timezone, taken from their session. "Changes done" becomes statusCategory = Done, with the change in status during today. If "network" matched two domains, the orchestrator would ask once with ask_user, offering the two likely options. The resolved scope is written into the session, so follow-up questions reuse it.
2. Context across AI-enabled MCP servers
Say SharePoint's MCP server has its own LLM that summarises documents. The orchestrator never hands it the conversation. It calls delegate with a brief that holds the goal, the resolved scope, the output format and a token budget. That becomes a child workflow with a fresh context, and only its short structured result comes back. The parent context gets about 300 tokens instead of the sub-agent's 30,000. The same contract applies to your own sub-agents.
3. 1,000 records of 5 KB each
search("tickets", ...) returns 1,000 Jira issues. The Jira adapter asks only for the fields the question needs, and normalises each issue to a Ticket in the result store. The context builder puts back a summary of about 2k tokens: the count, counts by project and status, five sample rows and a handle. To answer "which teams had the most failed changes", the model calls query_results(handle, "select team, count(*) ... group by team") and gets ten rows. The full 5 MB never enters the context.
4. Too many tools
Your 8 servers expose well over a hundred tools between them. The model sees 8. search, get, describe, query_results and act cover nearly every request, because the hub turns them into the right native calls. For something unusual, such as "list Confluence page restrictions", the model calls find_tools("confluence page permissions"). That searches the tool index in the catalogs, and only that one tool definition is loaded into the context, the same way Claude Code loads deferred MCP tools.
5. ServiceNow and Zendesk overlap
"Show my open tickets". Step 1 checks the manifests. ServiceNow owns: [incident, change, request] for internal IT, and Zendesk owns: [customer_ticket]. Rules come first: an id like INC0012345 or #48213 settles it, and the user's team default comes next. If it is still unclear, a classifier scores both. A confident score routes to one system, close scores fan out to both, and low scores ask the user. Every decision is logged, so misroutes become eval cases.
6. Narrowing overlapping results
Searching both systems for "VPN outage" returns 40 ServiceNow incidents and 25 Zendesk tickets. Many of them describe the same outage. The hub merges them as canonical Ticket records, links them on configuration item, problem record, time window and text similarity, and collapses duplicates into one cluster with every source attached. It applies conflict rules, such as the system of record winning on status, and ranks by relevance and recency. The model sees 6 clusters, not 65 records, and the answer still cites both systems.
7. Parallel vs sequential
"Changes on the payments servers this week, and any incidents after them". Step 2 builds a graph. Finding the servers in the CMDB comes first, because both later steps need them. Searching Jira changes and ServiceNow incidents for those servers then run in parallel. Linking incidents to changes by time window runs last. Temporal runs the independent activities concurrently, within each task queue's limits, so a slow ServiceNow cannot starve Jira.
8. Which framework
Temporal holds the workflow, Pydantic AI runs the loop, and Azure OpenAI is the model. All of it runs in your private cloud (chapter 13). The design does not depend on the framework. If you switched to the OpenAI Agents SDK later, the core tools, the hub and the connectors would not change.
9. Failures
Jira returns 429 errors for two minutes. Temporal retries the activity with backoff. After three failures the hub's circuit breaker opens for Jira, and the orchestrator answers with what it has: "ServiceNow results below. Jira was unavailable, so Jira changes are missing. I'll retry in 5 minutes." A pod restart halfway through a run replays from history without calling the model or Jira again. A retried act uses the activity id as an idempotency key, so a change is never created twice.
10. Self-correction from feedback
Inside a run: Step 4 finds that the answer claims 12 changes while the result store holds 14. It sends the run back to Plan with the specific failure, which can happen at most twice. Across runs: a user says "FW changes belong to Security, not Network". That correction goes through Feedback + evals, a reviewer accepts it, and it updates the domain catalog. It also becomes an eval case, so the mistake cannot come back unnoticed.
11. Making fewer mistakes, and proving it
Mistakes are prevented in layers. Scope is resolved before searching. The model sees canonical fields, not raw JSON. Deterministic checks run before the answer. Writes need approval. Each layer has its own eval set: scope resolution, routing, tool choice, field resolution, answer faithfulness. These run on every prompt, catalog or connector change, and traces show exactly which layer failed when something goes wrong.
12. 300 Jira projects with different custom fields
"Root cause DNS in network changes". The Jira adapter looks up the canonical field root_cause in the field catalog for the scoped projects. NET uses customfield_10042 (text), FW and LB use customfield_11873 (select), and WAN has no such field. It builds one JQL clause per field group and returns a coverage note with the results: "WAN does not track root cause, so it is not included". The model only ever sees root_cause.
Honest gaps: what the architecture does not solve on its own
Catalogs need owners. The domain catalog, field mappings and value maps start as drafts and need people to review them. Budget time for this before go-live.
Routing needs data. The classifier needs a few hundred labelled questions. Until you have them, rely on rules and asking the user.
Identity per connector. Carrying the user's permissions into each system needs every MCP server to accept an on-behalf-of token or a scoped service account. Some vendor servers do not support this, so check each one.
Conflicting data is a business decision. When ServiceNow and Zendesk disagree, which one wins is your policy. The hub only applies the rules you give it.
Model limits. Azure OpenAI deployment quotas and rate limits cap how much you can run in parallel. Size the Temporal task queues to match them.
Evals start empty. Seed them from real tickets and early user corrections. The design only pays off once the eval sets exist.
The three layers described next are the same design seen from inside: the orchestrator plus harness is the agent core, then the connector hub, then the connectors.
One agent loop (understand, plan, act, verify), with these tools. They are the only tools the model sees by default, whether you have 8 servers or 80:
Core tool
What it does
Chapter
search(kind, query, scope)
Searches every connector of a kind (tickets, knowledge, data, hosts) in parallel, merges, returns a summary and a data handle
3, 5, 6, 7
get(ref)
Fetches one record, for example jira:NET-4512 or servicenow:INC0012345
3
describe(kind, scope, terms)
Which fields and values exist for this scope, such as "root cause" across Network projects
1, 12
query_results(handle, sql)
Read-only SQL over results already fetched
3
act(ref, action, args)
Any write or command: create, transition, comment, restart a service. Always goes through policy and, if needed, approval
8
find_tools(query)
Finds a server-specific tool when the core tools cannot do the job, and loads only that tool
4
delegate(task, kinds)
Hands a self-contained task to a subagent with its own context, returns a short result
2
ask_user(question, options)
Clarifies scope or asks for approval
1, 9
The core also holds the things every request needs: the domain catalog for vague scopes ("network" means these Jira projects and these ServiceNow groups), memory, and the verifier.
Context is built in layers, from most stable to most volatile. Stable layers go first so they are cached once and reused on every turn. Volatile content is kept short, or kept out of the context entirely and stored as a handle. This is the order Claude Code uses: system prompt and tools, then memory files, then the conversation, with tool definitions and skills loaded only when needed (How Claude Code works, Memory).
Context layers from cached and stable at the top to per-turn and volatile at the bottom, with what stays outside the window
#
Layer
Contents
Loaded
Size budget
Claude Code equivalent
1
System prompt
Role, rules for scope, citing and approvals, how to use the core tools
Every turn, cached
2 to 4k tokens
Claude Code system prompt
2
Core tool definitions
The eight core tools, plus names only of the connectors and kinds
Every turn, cached
About 2k
Built-in tools and deferred MCP tool names
3
Memory files
ITSM.md at organisation, team and user level: conventions, defaults, corrections that became rules
Session start, cached
Under 3k in total; longer material goes to skills
CLAUDE.md hierarchy and auto memory
4
Catalog summary
Domain names and the kinds each one maps to, not the full mapping
Session start
Under 1k
The skill and MCP listing
5
On-demand context
A connector tool schema from find_tools, a runbook skill, a describe report
When the model asks
Each one capped, for example 1.5k
Tool search and skills
6
Conversation
User turns, the model's reasoning and decisions, the resolved scope
Every turn
Grows until compaction
The transcript
7
Tool results
Summary, counts, sample rows and a handle. Never the full payload
After each call
Capped per result, for example 2k
Large outputs truncated or saved to a file
What stays outside the window: the result store (raw records, queried with query_results), the full domain catalog and field catalogs (reached through describe), all connector tool schemas (reached through find_tools), and subagent transcripts.
When the conversation passes about 80% of the window, older turns are replaced by a summary. The summary must keep the resolved scope (projects, systems, time range in the user's timezone), the decisions taken and why, the handles to stored results, open questions, and any approvals given. Raw tool output is never kept, because it can always be queried again by handle. Like Claude Code, compaction runs automatically, and memory files are re-read rather than summarised, so rules survive it. If the same thing gets compacted repeatedly without progress, stop and tell the user instead of looping.
Subagent context
delegate(task, kinds) starts a fresh context with layers 1 to 4 and a written brief: the goal, the resolved scope, the handles it may read, the output format and a token budget. It does not get the parent's conversation. It returns a short structured result and new handles, and only that enters the parent's context. Use it for work that would otherwise fill the main context with intermediate steps, such as checking 40 hosts or reading 30 runbook pages. AI-enabled MCP servers are treated the same way: the hub gives them a brief and keeps only their structured answer.
Writing memory
Corrections and stable facts go to ITSM.md at the narrowest level that fits, through a reviewed write (chapter 9). They are never kept only in the conversation, because compaction or the next session would lose them.
None: generic adapter, command allow-list in the manifest
A new server of an existing kind needs a manifest and, at most, a small adapter. A new kind (say monitoring) needs one new canonical record and one adapter interface, written once, and then every monitoring server after it is a manifest.
"Any network changes done today that caused incidents? Check the runbook too."
The core resolves scope from the domain catalog: network means Jira projects NET, FW, LB, DNS and the ServiceNow Network groups. Today means midnight to now in the user's timezone.
It calls search("tickets", {type: change, status: done, date: today}, network) and search("tickets", {type: incident, date: today}, network) in parallel.
The hub sends each search to every tickets connector whose manifest owns that record type. The Jira adapter writes JQL, the ServiceNow adapter writes an encoded query, results come back as Ticket records into the result store.
The core links changes to incidents with query_results (configuration item and time window), then calls search("knowledge", "network change rollback runbook"), which goes to Confluence and SharePoint.
The verifier checks counts and coverage, and the answer cites each record.
The model never saw a Jira, ServiceNow, Confluence or SharePoint tool. It used search, query_results and the scope.
Five steps to add a server; nothing in the agent core changes
Run the MCP server. Use the vendor's server, or wrap the API with the MCP Python SDK.
Write the manifest. Kind, tools sorted into read, write and hidden, ownership, limits, auth.
Pick the adapter. If the generic adapter for the kind fits, put the field mapping in the manifest and you are done. If not, write a small adapter that implements the kind's interface.
Add 10 to 20 eval cases. Routing (does a question reach this server?), normalisation (is the canonical record right?), and policy (are writes blocked without approval?).
Register and roll out. The hub hot-loads the manifest, indexes the tools, and runs the connector in shadow mode, where it is queried and logged but not used in answers, until its evals pass.
What does not change: the agent loop, the eight core tools, the system prompt, the verifier and the existing connectors.
Add tracing with per-slice token counts and tool result sizes. You will find your worst offenders in a day.
Write manifests for the servers you already have, and sort their tools into read, write and hidden. This alone usually removes most of the tools from the model's view.
Put the eight core tools in front, starting with search and query_results for tickets, with a result store (chapter 3).
Build the domain catalog so scope is resolved before searching (chapter 1).
Move one kind at a time behind adapters: tickets first, then knowledge, then data and hosts.
Add the verifier and turn user feedback into eval cases (chapter 9).
Build/Jira connector
Chapter 12
Jira connector
7 min read
Jira is a tickets connector (chapter 11). The core asks for root_cause in the Network Platform projects through search and describe, and the Jira adapter in the connector hub does the hard part: working out which of 300 projects have that field, what it is called in each one, and how to query it. The core never sees customfield_11873. Jira's adapter is the largest one in the platform because of custom fields. ServiceNow and Zendesk implement the same TicketAdapter interface with less work.
The Jira adapter sits in the connector hub, between the core tools and the Jira MCP server, backed by a field catalog that a nightly crawler keeps current
With about 300 projects, custom fields go wrong in four ways at once:
Same meaning, different fields. "Root Cause" in NET, "RCA" in FW, "Root cause category" in DB. They are three custom fields with three ids.
Same name, different meaning or type. "Environment" is free text in one project, a select list (Prod, UAT, Dev) in another, and a multi-select in a third.
Same field, different options. One custom field can have different contexts, so its allowed values differ between projects.
Field missing. Many projects simply do not have the field, so a filter on it silently drops their issues.
Letting the model discover this per query, by reading raw issue JSON, is the expensive and unreliable path. A single issue can carry hundreds of customfield_* keys, most of them empty. The answer is a field catalog built ahead of time, plus a canonical field layer on top of it.
Three projects' fields map to one canonical field with value maps; a project without the field is reported as a gap
#Step 1: discover the schema with a nightly crawler
Jira's REST API exposes what you need:
Call
Gives you
GET /rest/api/3/field
Every field: id, name, schema type, custom or system
GET /rest/api/3/issue/createmeta/{project}/issuetypes/{issueTypeId}
Fields available for one project and issue type, with required flags and allowed values
GET /rest/api/3/field/{fieldId}/context and its options
Per-project contexts and option lists for select fields
POST /rest/api/3/search/jql with a count or small sample
Whether a field is actually used in a project, not just present
Store the result as one table you can query:
sql
CREATE TABLE jira_field_catalog (
project_key text,
issue_type text,
field_id text, -- customfield_10042
field_name text, -- "Root Cause"
field_type text, -- string | option | array<option> | user | date ...
allowed_values jsonb, -- options for this project's context
required boolean,
fill_rate real, -- share of recent issues with a value
canonical text, -- root_cause, or null if unmapped
value_map jsonb, -- {"DNS": "dns", "Config": "config"}
last_seen timestamptz,
PRIMARY KEY (project_key, issue_type, field_id)
);
Crawl nightly, diff against yesterday, and alert the owner when a mapped field disappears, changes type or gains options. Version the catalog so a bad crawl can be rolled back.
Define a short list of canonical fields that matter for ITSM questions: root_cause, environment, affected_service, change_risk, customer, severity, team. Then map project fields onto them:
Candidate matching: embed field names, descriptions and option values; cluster fields whose names or options are similar. Type compatibility is a hard filter: a user-picker never maps to environment.
LLM-proposed mapping, human-approved: for each cluster, the model proposes canonical and a value_map, with its reasoning. A field owner approves or edits it. Nothing reaches production unreviewed.
Coverage: record which projects have each canonical field and how full it is. "root_cause exists in 212 of 300 projects; filled in 64% of their issues" is information the answer must carry.
Unmapped is fine: most custom fields are never asked about. Leave them unmapped and keep them in the result store as extras, so nothing is lost.
After scope resolution (chapter 1) produces the project set, the field resolver looks up each canonical term in the catalog for exactly those projects:
python
def build_filter(term: str, value: str, projects: list[str]) -> tuple[str, Coverage]:
rows = catalog.lookup(canonical=term, projects=projects) # one row per project that has it
clauses = []
for field_id, group in groupby(rows, key=lambda r: r.field_id):
keys = [r.project_key for r in group]
native = group_value(group, value) # value_map, or text match for free text
op = "~" if group[0].field_type == "string" else "in"
clauses.append(f'(project in ({", ".join(keys)}) AND cf[{num(field_id)}] {op} {native})')
missing = sorted(set(projects) - {r.project_key for r in rows})
return " OR ".join(clauses), Coverage(found=len(projects) - len(missing), missing=missing)
For "root cause DNS in network", this produces one clause per field group, not one per project, so 300 projects usually collapse into a handful of clauses:
text
(project in (NET, NETOPS) AND cf[10042] ~ "DNS")
OR (project in (FW, LB) AND cf[11873] in ("DNS"))
OR (project = DNS AND cf[12001] in ("Name resolution"))
The answer then states the gap: "Root cause is not tracked in WAN and NETSEC, so their issues are not included."
#Step 4: fetch only what you need, normalise everything
Ask Jira only for the fields the question needs (fields=summary,status,updated,customfield_10042). This alone shrinks issues from tens of kilobytes to a few hundred bytes.
Normalise into canonical records (Change, Ticket) with canonical field names. Unmapped fields go to extras in the result store, never into the context.
Keep source_project and the original field_id on every value, so the verifier and the user can trace it.
The model never sees customfield_* ids. When it needs to filter on something unusual, it calls describe("tickets", scope, ["root cause"]) and gets back a compact report: canonical name, type, top values, coverage. This is layer 5 of the context (chapter 11). The field schema for 300 projects would flood the window, so the agent pulls only the slice it needs, the way Claude Code loads MCP tool definitions only when they are needed.
Both are manifests of kind tickets with their own TicketAdapter. ServiceNow's describe reads the table dictionary and choice lists, its build_query writes encoded queries, and its normalise emits the same Ticket with the same canonical field names. The core, the hub and the Jira adapter do not change, and a question about "network changes" starts returning ServiceNow records as soon as its manifest goes live.
Build/Production harness
Chapter 13
Production harness
9 min read
Recommendation: Temporal + Pydantic AI. Use Temporal (MIT licence, self-hosted) as the durable execution engine and Pydantic AI (MIT licence) as the agent layer, joined by Pydantic AI's built-in Temporal integration. Both are free, both run entirely in your network, and the integration is co-maintained by the Pydantic and Temporal teams. It works with OpenAI models from Azure AI Foundry out of the box, and nothing in the stack calls a vendor SaaS by default, so everything except the model runs in your private cloud. Add self-hosted Langfuse for traces. Checked November 2026.
An agent framework on its own is not a production harness. Frameworks give you the loop, tools and structured output. They do not survive a pod restart halfway through a 40-minute change investigation, wait two days for a CAB approval without holding a process, or guarantee that a ServiceNow change is created exactly once after a retry. That is what a durable execution engine does, and Temporal is the most mature open source one. The right answer is a pair: an engine for durability plus a light agent layer for the loop.
Agent workers run Pydantic AI on Temporal; every model call and tool call is a journaled activity, all inside your network
#Your setup: Azure OpenAI from Foundry, everything else in your private cloud
The recommendation stays the same. Each option below can run inside your private cloud, with the model as the only call out to Azure:
Option
Azure OpenAI support
Sends data to a vendor by default?
Durability
Fit
Temporal + Pydantic AI
Built in: azure:<deployment> model strings, or OpenAIChatModel / OpenAIResponsesModel with AzureProvider
No. Tracing is opt-in, and you send OpenTelemetry to your own Langfuse
Temporal, self-hosted
Recommended
Temporal + OpenAI Agents SDK
Yes, by passing an AsyncAzureOpenAI client to set_default_openai_client, with set_default_openai_api("chat_completions")
Yes. Tracing is on by default and goes to OpenAI's trace backend, including inputs and outputs. Turn it off with OPENAI_AGENTS_DISABLE_TRACING=1 or set_tracing_disabled(True), and use set_trace_processors() to send traces to your own backend only
Temporal (GA integration)
Good second choice, if you lock down tracing
Microsoft Agent Framework
First class: FoundryChatClient, Entra ID credentials
Built-in OpenTelemetry, which you point at your own collector
Workflow checkpointing; durable hosting samples use Azure Durable Task and Azure Functions
Strong for .NET or Azure-native teams. Its documented paths lean on Foundry services, so confirm that each piece you use can be self-hosted
How to keep everything private:
Model traffic: use a private endpoint for your Azure OpenAI resource, so calls never cross the public internet, and authenticate with Entra ID managed identity or keys held in your vault.
No SaaS defaults: with the OpenAI Agents SDK, disable its tracing as described above. With Pydantic AI, do not enable Logfire cloud; export OpenTelemetry to self-hosted Langfuse instead. Run Temporal yourself, not Temporal Cloud.
Gateway: LiteLLM is optional now. Add it only if you want one place for keys, budgets and fallbacks across several Azure deployments.
Data: prompts and tool results live in your Temporal history, Postgres and Langfuse. Set retention on all three, because tool results can contain ticket data and personal data.
python
# Pydantic AI on Azure OpenAI (Foundry). Set AZURE_OPENAI_ENDPOINT (ending in /openai/v1/)
# and AZURE_OPENAI_API_KEY, or pass api_version= for api-version deployments.
from pydantic_ai import Agent
itsm = Agent("azure:gpt-itsm-prod", instructions=SYSTEM_PROMPT, tools=[...]) # your deployment name
Temporal, DBOS, Prefect, Restate and more, built in
Recommended. Typed tools and outputs, MCP client built in, any model, including Azure OpenAI from Foundry and OpenAI-compatible local servers. The Temporal integration journals each model request and tool call, so a restarted run replays instead of redoing work
Its own Postgres checkpointer, or Temporal (public preview)
Fine library, but its Agent Server needs a LangSmith licence key, and the Temporal plugin is still in preview. Two state models (graph plus Temporal) is more to reason about
The harness is free and runs in your private cloud. The model is the one external call:
Model option
Data leaves your network?
Cost
Notes
Azure OpenAI in Azure AI Foundry, over a private endpoint
It goes to your Azure tenant, not across the public internet
Pay per token
Your plan. Check data handling and retention terms for your region and deployment type
Open-weight model on vLLM or Ollama
No
Your GPUs
Useful later for cheap, high-volume steps such as extraction and classification
Harness/Harness engineering
Chapter 14
Harness engineering
6 min read
We build our own harness. Claude Code shows why this works. Its agent loop is small, and almost all of its quality comes from the harness around the loop: what goes into the context, which tools the model sees, what it may do without asking, how work is split across contexts, and how results are kept out of the window. Off-the-shelf frameworks give you the loop and leave those decisions to you. For an ITSM platform with vague queries, overlapping systems and huge results, those decisions are the product.
This page is the overall design only. Each block gets its own deep-dive page next, one at a time.
The custom harness: a gateway, a runtime of eleven blocks around one agent loop, three integration blocks, and two cross-cutting blocks
Authenticates every caller, carries user identity, creates and restores sessions, streams events over WebSocket, runs long system jobs asynchronously with a webhook back
Supports all
Sessions, resume, headless mode
FastAPI, Postgres
B2 Agent loop
One turn engine: build context, call the model, run tool calls (in parallel where allowed), append results, repeat until done or a budget is hit; supports cancel and steer
7, 11
The core agentic loop
Your code, Azure OpenAI SDK
B3 Context engine
Assembles the 7 context layers before every model call, enforces token budgets per layer, caps tool results, compacts at about 80%
2, 3
Context assembly, auto-compaction
Your code, tokenizer
B4 Memory
Loads ITSM.md at org, team and user level; writes reviewed corrections back; keeps session notes across compaction
10
CLAUDE.md, auto memory
Postgres or git
B5 Scope and routing
Resolves vague terms with the domain catalog ("network" to projects and groups, "today" to a time range), then routes by record owner, rules and a classifier; asks when unsure
1, 5
(ITSM-specific; nearest is reading CLAUDE.md and the codebase first)
Postgres, pgvector
B6 Tool system
Defines the 8 core tools, validates arguments, indexes every connector tool, serves find_tools so only the tool needed is loaded
4
Built-in tools, deferred MCP tools, tool search
Your code, pgvector
B7 Planner and executor
Turns multi-part requests into a step graph; runs independent steps in parallel within per-connector limits; re-plans when a step fails
7
Plan mode, parallel tool calls, to-do list
Your code, asyncio
B8 Sub-agent runner
Runs delegate: a fresh context with a written brief, its own budget and tool set; also wraps AI-enabled MCP servers so only a short structured result comes back
2
Subagents (Task tool)
B2 run as a child
B9 Connector runtime
Loads manifests, keeps an MCP client pool, translates core calls into native queries through kind adapters, normalises results to canonical records; holds the Jira field catalog
5, 12
MCP client and server config
MCP Python SDK
B10 Data plane
Stores bulk results with profiles, answers query_results with read-only SQL, links, dedupes and ranks overlapping records
3, 6
Large outputs saved to files instead of the context
DuckDB, Postgres
B11 Policy and hooks
Checks every tool call against permissions and risk, asks for approval on writes, runs pre- and post-tool hooks, enforces idempotency keys
9, 11
Permission modes, hooks
Your code, policy files
B12 Durability and reliability
Journals every model and tool step so runs resume; retries with backoff, timeouts, circuit breakers per connector; partial answers when a system is down
8, 9
Checkpoints, session transcripts
Postgres journal, or Temporal as the substrate
B13 Verifier
Checks the answer before it goes out (counts match the data, scope coverage stated, every claim cited); sends specific failures back to the loop, at most twice
10, 11
Verify step, tests and linters as checks
Your code, plus a model critic
B14 Observability and feedback
Traces every step with one id, runs per-layer evals on every change, turns user corrections into memory, catalog fixes and eval cases
10, 11
OpenTelemetry, /feedback
OpenTelemetry, Langfuse
B15 Model gateway
The only path to Azure OpenAI: deployment choice per task, quotas and rate limits, retries, token accounting, prompt caching
8, 9
Model selection, retries
Azure OpenAI SDK, private endpoint
Problem numbers refer to the 12 problems on the Reference architecture page. Problem 8, choosing a framework, becomes: build B2 to B14 yourself, use libraries underneath, and decide in B12 whether a Postgres journal or Temporal is the durability substrate.
Each block gets its own page: its interfaces, data structures, failure modes, code and evals. A sensible build order is B2, B3, B6, B9, B10, then B5, B11, B12, B13, then B7, B8, B4, B14, B15, B1, because the loop, context and tools are what everything else plugs into. Deep dives so far: B1 Gateway and sessions, B2 Agent loop.
Harness/B1 Gateway and sessions
Chapter 15
B1 Gateway and sessions
8 min read
B1 is the front door of the harness. Every caller, whether a person in the portal, a script, a CLI, another agent or a ServiceNow webhook, enters here and leaves here. B1 turns all of them into one internal RunRequest for the agent loop (B2), knows who the caller is, keeps the conversation, and streams what happens back. It contains no agent logic and never calls the model.
B1 internals: protocol adapters, auth, admission, session manager, run dispatcher and event stream, backed by Postgres
Claude Code equivalent: sessions stored as transcripts, --resume and --continue, forking a session, headless mode with streamed JSON output, and queued messages while a turn is running (How Claude Code works).
Sync for short runs, async with 202 Accepted for long ones
User token or service principal
CLI
REST plus server-sent events
Interactive, streamed
User, device code sign-in
Other agents
An MCP server exposing one tool, ask_itsm, or A2A
Sync or async
Service principal, with the user it acts for
System events
Webhooks from ServiceNow, Jira, monitoring
Always async, result posted to a callback
Service principal; request signature checked
Each protocol adapter produces the same structure, so nothing after B1 knows or cares which caller it was:
python
@dataclass(frozen=True)
class Principal:
subject: str # user or service principal id
kind: Literal["user", "service"]
on_behalf_of: str | None # the user an agent or system acts for
tenant: str
teams: list[str] # used by B4 memory and B5 scope defaults
roles: list[str] # used by B11 policy
timezone: str # "today" is resolved in this zone
locale: str
obo_token: SecretRef # exchanged per connector in B9, never shown to the model
@dataclass(frozen=True)
class RunRequest:
session_id: str
run_id: str
principal: Principal
message: str
attachments: list[FileRef]
mode: Literal["interactive", "async"]
callback: Callback | None # for async callers
budget: Budget # max tokens, tool calls, wall time
idempotency_key: str | None
Users sign in with Entra ID (OIDC). Systems and other agents use service principals. When an agent or system acts for a user, the principal records both, and B11 checks permissions against the user, not the service.
B1 keeps an on-behalf-of token for the user. B9 exchanges it for a connector-specific token at call time, so Jira, ServiceNow and SharePoint each apply the user's real permissions. If an MCP server cannot accept a user token, its manifest says so, and B11 limits it to what a shared service account may safely return. Tokens never enter the model's context or the event log.
A session is a conversation. A run is one turn of the agent loop inside it, from a user message to an answer. An event is anything that happens during a run. Everything is stored in Postgres before it is streamed.
sql
CREATE TABLE sessions (
session_id uuid PRIMARY KEY,
owner text NOT NULL, -- principal subject
tenant text NOT NULL,
title text,
scope jsonb, -- last resolved scope, reused by follow-ups
parent_id uuid, -- set when forked
state text NOT NULL, -- active | archived
created_at timestamptz, updated_at timestamptz
);
CREATE TABLE runs (
run_id uuid PRIMARY KEY,
session_id uuid REFERENCES sessions,
principal jsonb NOT NULL, -- without tokens
state text NOT NULL, -- queued | running | waiting_approval | interrupted
-- | completed | failed | cancelled
mode text NOT NULL, -- interactive | async
idempotency_key text,
usage jsonb, -- tokens, tool calls, duration
started_at timestamptz, ended_at timestamptz,
UNIQUE (session_id, idempotency_key)
);
CREATE TABLE events (
run_id uuid REFERENCES runs,
seq bigint, -- strictly increasing per run
type text NOT NULL,
payload jsonb NOT NULL,
at timestamptz NOT NULL,
PRIMARY KEY (run_id, seq)
);
Session operations:
Create: new session, empty history.
Resume: continue an existing session. B3 rebuilds context from its history, compacted summary and stored scope.
Fork: copy a session up to a point and branch, for "try that again but for the Security domain" without losing the original.
Run states from queued to a terminal state, with approval waits and crash recovery
Every state change is an event. interrupted is set by B12 when a worker dies. B12 resumes the run from its journal, and B1 just keeps streaming events with the next sequence numbers.
"Network: NET, FW, LB, DNS, WAN · today" chip the user can correct
text.delta
Model streams answer text
Answer text
tool.started, tool.finished
Each tool call
Collapsible step list
approval.requested, approval.resolved
act needs approval
Approve and deny buttons
subagent.started, subagent.finished
delegate runs
Nested step
run.completed, run.failed, run.cancelled
Terminal state
Final answer, or error with what was done
Reconnects: a client that drops sends the last seq it saw (GET /v1/runs/{id}/events?after=14, or the same field on WebSocket reconnect). B1 replays from Postgres, then continues live. Because gateway pods are stateless and fan out live events through Postgres LISTEN/NOTIFY (or Redis Streams at higher volume), a reconnect can land on any pod.
POST returns 202 Accepted with run_id and a status URL.
The run continues without any open connection.
On a terminal state, B1 posts the result to the caller's callback URL, signed with HMAC-SHA256 over the body and a timestamp, and retries with backoff for up to 24 hours.
The caller can poll the status URL or read events at any time.
An Idempotency-Key header makes retries safe. If ServiceNow sends the same webhook twice, the second request returns the first run instead of starting another.
Events can contain ticket data and personal data. Set retention per tenant, such as 90 days for events and longer for session titles and scopes. Redact secrets before storage, never store tokens, and record who viewed or exported a session.
FastAPI service with WebSocket, REST and SSE adapters producing RunRequest.
Entra ID OIDC validation and on-behalf-of token storage in your vault.
Postgres tables for sessions, runs and events, plus LISTEN/NOTIFY fan-out.
Session manager with create, resume, fork and archive, and one active run per session with steer, cancel and queue.
Async mode, signed webhooks and idempotency keys.
Admission control and budgets.
The test suite above, running in CI.
Harness/B2 Agent loop
Chapter 16
B2 Agent loop
13 min read
B2 is the turn engine. It calls the model, runs the tool calls the model asks for, appends the results and repeats until the model answers or a limit is reached. Every caller uses the same loop: portal users, REST clients, the CLI, system webhooks and sub-agents (B8 runs B2 again with its own state). B2 is deliberately small. It decides the order things happen in, and the other blocks do the work.
This follows the advice that keeps coming up in teams who run agents in production: own your loop, keep it a plain while over explicit state, and put the intelligence in context, tools and checks (12-factor agents, Unrolling the Codex agent loop).
One step of the loop: check limits and steering, build context, call the model, journal, then run tools through policy or verify the answer
Claude Code equivalent: the core agentic loop of gather context, take action and verify, with tool calls run until the model stops calling tools, queued messages while a turn runs, and interrupt with Escape (How Claude Code works).
The loop is a reducer: the next state is a function of the current state and what just happened. Everything a run needs is in one serialisable object, which B12 journals after every change. That is what makes pause, resume, replay tests and debugging possible.
python
@dataclass
class RunState:
run_id: str
session_id: str
principal: Principal
items: list[dict] # Responses API input items, append-only
step: int = 0
repairs: int = 0
usage: Usage = field(default_factory=Usage) # tokens in/out/cached, tool calls, ms
budget: Budget = field(default_factory=Budget) # from B1 admission
status: str = "running" # mirrors B1 run states
pending_approval: str | None = None
recent_calls: list[str] = field(default_factory=list) # call fingerprints for loop detection
items is the conversation in the Azure OpenAI Responses API format: user messages, model output items, function_call items and function_call_output items. It only ever grows. Compaction (B3) replaces it in one journaled step, never by editing items in place.
async def run_turn(state: RunState, h: Harness) -> RunState:
while True:
# 1. limits, cancel and steering (messages queued by B1)
if (stop := h.limits.check(state)):
return await wrap_up(state, stop, h)
state = h.steering.inject(state)
# 2. build the request (B3), 3. call the model (B15)
request = h.context.build(state) # layers, caps, compaction if needed
response = await h.models.respond(request)
# 4. journal before acting, so a crash never repeats a model call (B12)
state = await h.journal.append(state, response.output, usage=response.usage)
calls = [i for i in response.output if i["type"] == "function_call"]
if not calls:
# 8. verify the answer (B13)
verdict = await h.verifier.check(state)
if verdict.ok or state.repairs >= 2:
return await h.finish(state, verdict)
state = await h.journal.append(state, [reminder(verdict.feedback)])
state.repairs += 1
continue
if h.loops.is_stuck(state, calls):
state = await h.loops.nudge_or_stop(state, calls)
if state.status != "running":
return state
continue
# 5-6. policy and execution (B11, B6 -> B9, B10)
results = await execute_calls(state, calls, h)
if state.status == "waiting_approval":
return state # resumed later by B1 when approved
# 7. cap results and journal them (B3, B12)
state = await h.journal.append(state, [h.context.cap(r) for r in results])
state.step += 1
Each request to Azure OpenAI is stateless: the whole items list is sent with store=False, as Codex does. Nothing about a run lives in the model provider, which fits a private deployment, and the harness can replay any run from its own journal.
python
response = await client.responses.create(
model=deployment, # one Azure deployment per session
instructions=SYSTEM_PROMPT, # layer 1, identical every call
tools=TOOL_DEFS, # layer 2, same order every call
input=request.items,
parallel_tool_calls=True,
store=False,
)
"No tool calls" is the normal end, but it is not enough on its own. A production loop needs hard limits and a way to notice it is stuck (The agent loop decoded, Building effective agents).
Checks run in order at the start of every step
Limit
Default for interactive runs
Default for async system runs
Steps (model calls)
25
60
Tool calls
60
200
Wall-clock time
3 minutes
30 minutes
Input plus output tokens
400k
2M
Repair rounds after verification
2
2
Identical tool call repeated
3 times
3 times
Loop detection. Each call is fingerprinted as tool name plus normalised arguments. If the same fingerprint appears three times in a row with the same result, the loop appends a short reminder ("You have called search with the same arguments three times and got the same result. Try a different approach or answer with what you have."). If it happens again, the run stops as stuck, and the trace is flagged for B14.
Hitting a limit should never produce an error page. At 80% of any budget, the loop appends a reminder: "Budget nearly used: finish the current step and answer." At 100%, it makes one final call with tool_choice="none", asking the model to answer from what it has and to state what is missing. The run ends as completed with a partial flag, so the UI can offer "continue".
Reads run in parallel within connector limits; writes run one at a time through policy, approval and an idempotency key
The model can ask for several tools in one response. B2 partitions them by the effect each tool declares in B6:
Reads (search, get, describe, query_results, find_tools) run concurrently, capped per connector by B9 so one slow system cannot starve others.
Writes (act) run one at a time, in the order the model gave. Each goes through B11 first. If B11 needs approval, the run is journaled as waiting_approval and returns. B1 resumes it when the user approves or denies.
Delegate runs a sub-agent through B8 and counts against this run's budget.
Every call gets an idempotency key, run_id:call_id, so a call retried after a crash is recognised by B9 and the target system instead of being run twice.
python
async def execute_calls(state, calls, h):
reads = [c for c in calls if h.tools.effect(c) == "read"]
writes = [c for c in calls if h.tools.effect(c) == "write"]
results = {}
for c, r in zip(reads, await asyncio.gather(*(h.tools.run(state, c) for c in reads),
return_exceptions=True)):
results[c["call_id"]] = r
for c in writes:
decision = await h.policy.check(state, c) # B11
if decision.needs_approval:
state.status, state.pending_approval = "waiting_approval", c["call_id"]
break
results[c["call_id"]] = await h.tools.run(state, c, idem_key=f'{state.run_id}:{c["call_id"]}')
return [to_output_item(c, results.get(c["call_id"])) for c in calls if c["call_id"] in results]
Errors are results, not exceptions. A failed call becomes a short function_call_output the model can act on: what failed, why, and what to try. Keep the failure in the context. Models avoid repeating mistakes they can see (Manus).
json
{"error": "jira_rate_limited", "retryable": true, "after_s": 30,
"hint": "Results from ServiceNow are complete. Answer without Jira or retry later."}
Stack traces and raw HTTP bodies go to the trace (B14), never to the model.
Azure OpenAI reuses the cached prefix of a prompt when the start of the request is identical to an earlier one, on models that support prompt caching. Every step of a run re-sends the whole conversation, so a stable prefix cuts cost and latency sharply. The rules, taken from Codex, Manus and Anthropic's harness guidance:
B1 allows one active run per session. Messages sent during a run reach B2 through a queue:
Steer: at the start of each step, B2 appends queued messages as user items, such as "also include FW". The model sees them on its next call. This is how Claude Code handles messages typed while it works.
Cancel: a flag checked at the start of each step. Running tool calls get a short grace period, then are cancelled. Their results are journaled as cancelled, and partial results stay in the session.
On long runs the original goal drifts out of the model's attention. Every 8 steps, or when B7 changes the plan, B2 appends a short reminder with the goal, resolved scope, done steps and remaining steps. Because it is appended rather than edited into the instructions, the cache stays intact, and the plan stays in the most recent part of the context (Manus, Effective harnesses for long-running agents).
#Durability: a Postgres journal now, Temporal later if needed
B12 journals every state change to Postgres before B2 acts on it. Model output is recorded before tools run, and tool results are recorded before the next model call. To resume after a crash, B12 loads the journal, rebuilds RunState and calls run_turn again:
A model call that finished is never repeated.
A read that was started but not recorded is simply run again.
A write that was started but not recorded is checked against its idempotency key with the connector before anything is retried.
This keeps B2 free of any framework. If you later need multi-day runs or very high volume, B2 can run inside a Temporal workflow with the model call and tool calls as activities. The loop code stays the same, and only B12's implementation changes.
The Anthropic, Claude and Claude Code docs links were checked on 30 November 2026. The others are well-known sources that could not be fetched from the build environment; a few URLs may have moved.