All chapters
  1. Start hereA protocol standardizes the call. It does not grant the permission
  2. Foundations · 1The primitive: a function, its arguments, its result, its side effects
  3. Foundations · 2Function calling: the model asks, your application executes
  4. Foundations · 3Client and server: process boundaries, JSON-RPC, errors and trust
  5. Foundations · 4What MCP is: host, client, server and what the protocol promises
  6. Protocol · 5Three surfaces: tools act, resources inform, prompts guide
  7. Protocol · 6A first MCP server: typed input, deterministic data, the raw exchange
  8. Protocol · 7Java and the SDKs: typed DTOs, validation and interoperability
  9. Protocol · 8Local or remote: stdio, HTTP, stateless requests and availability
  10. Platform · 9The database decision: direct SQL, a service boundary or an MCP adapter
  11. Platform · 10Sharing across teams: ownership, catalogs, contracts and versions
  12. Platform · 11Who gets access: users, agents, delegation and least privilege
  13. Platform · 12Enterprise authorization: tokens, audiences, gateways and no passthrough
  14. Platform · 13The threat model: injection, poisoned tools, confused deputies and egress
  15. Platform · 14Governance: who may publish, who approves, who answers the page
  16. Operations · 15Observability and audit: what was called, by whom, and why it was allowed
  17. Operations · 16Resilience: timeouts, retries, idempotency and overload at a shared server
  18. Operations · 17Testing and evaluation: contracts, authorization matrices and injection
  19. Reference · 18Advanced MCP: long tasks, large catalogs, tenants and evolving versions
  20. Reference · 19The ecosystem: SDKs, registries, gateways, identity and telemetry
  21. Reference · 20Enterprise reference architecture: one assessment platform, four teams
  22. Reference · 21Decision playbooks: function, API or MCP, and the records that explain why
  23. ReferenceGlossary
  24. AboutAbout this site and its sources
Foundations · 1

The primitive: a function, its arguments, its result, its side effects

Before any model or protocol, a capability is a function. One roof-assessment lookup and one write, in Python and in Java, and why the difference between reading and writing decides almost everything later.

You will understand
What a function promises: its arguments, its return value and what it changes.
You will be able to tell
A read from a write, and why a write repeated is a different event.
You will have run
The roof lookup and the recommendation write in Python and Java, with real output.

Before any model, protocol or network is involved, the insurer's underwriting agent is ordinary code. Its application imports the assessment service and calls two of its functions while it works on submission SUB-1004. One function reads the roof assessment: 22 years, evidence EV-ROOF-0412, against the 9 years the broker's application claimed. The other function stores the agent's recommendation, escalate, citing rule R-ROOF-03, so that an underwriter can review it in the cockpit.

Consider a first version of the write that had no protection against repetition. That is the mistake this page is about. The write reached the database and committed. Then the reply was slow, the calling code hit its timeout, and it did what calling code is built to do: it called again. The underwriter opened SUB-1004 and found two recommendations with the same text and two different ids. Nothing crashed. Each call did exactly what it was asked.

Now imagine the same retry on the read. The agent asks for the roof of SUB-1004 twice and gets the same answer twice. Nothing in the world changed. The two functions look alike in the code, but they make different promises, and every later page of this site (tools, servers, tokens, audit) inherits that difference. This page looks at the two functions as plain code, in Python and in Java, before anything else is wrapped around them.

A function is a promise about inputs, outputs and what changes#

A function is ordinary code with arguments and a result. You give it values, it computes, it hands one value back. get_roof_assessment("SUB-1004") is a function call: the text "SUB-1004" goes in, a record describing the roof comes out.

The values you give it are its arguments. Here there is one, submission_id, and it must look like SUB- followed by four digits. The value it hands back is its return value: here a PropertyAssessment, the small typed record you met on Start. A function can also fail, and a well-written one says so with an error the caller can tell apart from a result, rather than with a result that looks normal and is wrong.

Some functions also change something outside themselves: a row in a database, a file, a message sent to another system. That change is a side effect. It is the part of a function's behavior that the return value does not show and that stays after the call is over. record_recommendation has one: a new row in the recommendations table. get_roof_assessment has none.

Plain English. A function is a promise in three parts. What you must give it. What it gives back. What it leaves changed behind it. The third part is the one that causes trouble when calls are repeated, delayed or made by someone you did not expect.
Before AI. A backend engineer knows this split from every service layer. In a Spring application a @Service class has query methods and command methods; a REST controller maps GET to the first and POST to the second; a JDBC call is either a SELECT or a statement that changes rows. HTTP itself names the property: a GET is expected to be safe to repeat, a POST is not. Nothing about agents changes this. Agents make it matter more, because the caller that repeats or improvises is now a program steered by text.

Diagram: Two functions, one shape · only the write leaves something behind

Read left to right. Both functions take a submission id and return a value. The read changes nothing, so calling it twice is harmless. The write adds a row, so calling it twice is two events unless it recognizes the repeat. Click a box for the code that does it.

  1. In · arguments
    1. submission_id: The value the caller gives. It must match SUB- and four digits; anything else is refused before the database is touched.
    2. submission_id + recommendation + idempotency_key: The write takes the recommendation with reasons and citations, and a key the caller generates once per intent.
  2. The function
    1. get_roof_assessment: Reads through the uw_reader database account, which cannot change anything.
    2. record_recommendation: Checks the key, then inserts one row in one transaction through uw_rec_writer, which may insert recommendations only.
  3. Out · return value
    1. PropertyAssessment: A frozen, validated DTO with nine fields. An invalid one cannot be built.
    2. REC-0001: The stored recommendation's id and status, and whether this call was a replay of an earlier one.
  4. Changed · side effect
    1. nothing: A read leaves the world as it found it. Ten calls equal one call.
    2. one new row: The effect stays after the call. A repeat without a key would add a second row; with the key it returns the stored one.

The diagram puts the two functions of the example side by side. Both take a submission id and both return a value. Only the write leaves something behind, and only the write needs a second account in the database, a key against repetition and, later on this site, a separate permission.

The smallest primitive: one read, in Python#

The example's assessment service lives in examples/uw-mcp/domain.py. It is the domain service of this site: the code that owns the business rules and the data of the assessment domain. Every architecture on later pages calls this same class. Here is its read, quoted from AssessmentService.get_roof_assessment (shown at the top level so the excerpt stands alone):

def get_roof_assessment(self, submission_id: str) -> PropertyAssessment:
    sub = self.repo.submission(submission_id)
    if sub is None:
        raise NotFound(f"No submission {submission_id}.", submission_id=submission_id)
    row = self.repo.assessment(submission_id)
    if row is None:
        return PropertyAssessment(submission_id, sub["property_id"], None, None, EVIDENCE_SOURCE, None, None,
                                  self.policy_version, "no_record")
    return PropertyAssessment(row["submission_id"], row["property_id"], row["roof_age_years"], row["roof_material"],
                              row["evidence_source"], row["evidence_id"], row["assessed_at"], row["policy_version"],
                              row["assessment_status"])

Three outcomes are visible in eleven lines, and each is a deliberate choice. If the submission does not exist, the function raises NotFound; it does not return an empty record that a caller might mistake for "roof unknown". If the submission exists but no provider has assessed the roof (SUB-1003 in the seed data), it returns a record with assessment_status no_record and empty roof fields; that is a fact about the world, not an error. Otherwise it returns the assessed values. A caller can tell all three apart without reading the code.

Notice also what the function does not know. It does not know who is asking, whether a model is involved, or whether the request came over a network. It reads through a repository that uses a database account called uw_reader, which can read and cannot change anything. Who may call it is decided elsewhere; that question starts on Function calling.

The result is a DTO, and it cannot be built wrong#

The return value is a DTO, a data transfer object: a plain structure that carries data between layers and has no behavior of its own. Its job is to be the same everywhere. The underwriting agent, the support desk's API client and a Java service in another team all read the same nine fields with the same names.

In the example the DTO is a frozen Python dataclass. Frozen means that assigning to a field after construction raises an error, as the Python documentation for dataclasses describes, so a record cannot change on its way through the system. Its checks run in __post_init__, which the generated constructor calls, so an invalid instance never exists. An excerpt from domain.py:

@dataclass(frozen=True)
class PropertyAssessment:
    """The roof assessment of one submission's property. Field names are exact (series reference B2)."""

    submission_id: str
    property_id: str
    roof_age_years: int | None
    roof_material: str | None
    evidence_source: str
    evidence_id: str | None
    assessed_at: str | None
    policy_version: str
    assessment_status: str

    def __post_init__(self) -> None:
        def bad(path: str, message: str) -> None:
            raise InvalidDto(f"{path}: {message}", path=path)

        if not isinstance(self.submission_id, str) or not SUBMISSION_ID.match(self.submission_id):
            bad("/submission_id", "must match ^SUB-[0-9]{4}$")
        # ... the same for property_id, assessment_status, roof_age_years (0 to 150),
        # roof_material, evidence_id, assessed_at, policy_version and evidence_source

The error paths look like /roof_age_years: they are JSON Pointers, the same notation a JSON Schema validator uses. That is on purpose. The same file holds DTO_SCHEMA, the DTO written as a JSON Schema, which later becomes the output contract of the tool and the shared contract with the Java code. One shape, written twice in two notations, checked in both.

For SUB-1004 the fields are:

FieldValue for SUB-1004Why it is there
submission_idSUB-1004The quote request this answers
property_idPROP-2207The building; one property can carry several submissions
roof_age_years22The provider's assessment (the application said 9)
roof_materialmodified bitumenContext for the underwriter
evidence_sourceroof-data provider (stand-in)Where the fact came from
evidence_idEV-ROOF-0412The citation a recommendation must carry
assessed_at2026-08-03T14:20:00ZWhen the evidence was produced
policy_version2026.2Which version of UW-GUIDE the record was read under
assessment_statuscompletecomplete, no_record or pending

Two of these fields exist for people who will never call the function. evidence_id lets a reviewer check a recommendation's citation a year later. policy_version tells an auditor which rules were in force. A DTO that carries its own provenance is cheaper than reconstructing it from logs.

Reading and writing are different promises#

A read operation returns information and changes nothing. Calling it once or ten times leaves the system as it was. get_roof_assessment, search_guidance and check_eligibility are reads.

A write operation changes stored state, so the world after the call differs from the world before it. record_recommendation is a write: it inserts a row with status awaiting_underwriter. Here it is, quoted from AssessmentService.record_recommendation:

def record_recommendation(self, submission_id: str, recommendation: dict[str, Any], idempotency_key: str,
                          recorded_by: str) -> dict[str, Any]:
    """Store the agent's recommendation. The same key again returns the stored row (no second row)."""
    if self.repo.submission(submission_id) is None:
        raise NotFound(f"No submission {submission_id}.", submission_id=submission_id)
    digest = payload_hash({"submission_id": submission_id, "recommendation": recommendation})
    existing = self.repo.recommendation_by_key(idempotency_key)
    if existing is not None:
        if existing["payload_hash"] != digest:
            raise Conflict("This idempotency key was used with a different recommendation.",
                           idempotency_key=idempotency_key)
        return {"recommendation_id": existing["recommendation_id"], "submission_id": submission_id,
                "recommendation": existing["recommendation"], "status": existing["status"],
                "idempotent_replay": True}
    rec_id = f"REC-{self.repo.count('recommendations') + 1:04d}"
    self.repo.insert_recommendation({
        "recommendation_id": rec_id, "submission_id": submission_id,
        "recommendation": recommendation["recommendation"], "reasons_json": json.dumps(recommendation["reasons"]),
        "citations_json": json.dumps(recommendation["citations"]), "idempotency_key": idempotency_key,
        "payload_hash": digest, "recorded_by": recorded_by, "status": "awaiting_underwriter",
        "created_at": self.clock.iso()})
    return {"recommendation_id": rec_id, "submission_id": submission_id,
            "recommendation": recommendation["recommendation"], "status": "awaiting_underwriter",
            "idempotent_replay": False}

The insert runs inside one transaction (the repository's UnitOfWork: begin, then commit or roll back) on a connection whose database account, uw_rec_writer, may insert into recommendations and nothing else. So even this write is narrow: it cannot update an existing row, cannot touch decisions, and cannot read its way into another table's write.

The function also records recorded_by, and its status is awaiting_underwriter, never approved. The model recommends; a person decides. The person's decision is a different write, record_underwriter_decision, with its own account (uw_decision_writer), and the service refuses it unless the actor is a user with the underwriter role.

Why a repeated write is dangerous, and the key that makes it safe#

Go back to the opening. The first write committed; only its reply was late. The caller cannot see the difference between "the write did not happen" and "the write happened and the answer was lost". Both look like a timeout. If it does not retry, a recommendation may be missing. If it retries a write that has no protection, the recommendation may exist twice. Neither choice is right without help from the function.

The help is a value the caller generates once and sends again with every retry of the same intent. The function stores the value with the first result. When the same value arrives again, it returns the stored result instead of writing a second row. That value is an idempotency key, and a write that honors one is idempotent: repeating it has the same effect as doing it once. In the example the key is SUB-1004:run-7f3a:recommendation, built from the submission and the run id, so a new run of the agent produces a new key, while a retry inside the same run reuses it. If the same key arrives with a different recommendation, the function answers conflict instead of guessing which one was meant. Timeouts, retry budgets and keys at a server shared by many teams are the subject of Resilience; here it is enough to see that idempotency is a property of the write, designed into the function, and not something a caller can add from outside.

Diagram: The lost reply · why a repeated write needs a key

Time runs down the page. The first write commits, then its reply is lost, so the caller cannot tell success from failure. It retries with the same idempotency key, and the service returns the stored row instead of writing a second one. Without the key, the third message would be followed by a duplicate.

  1. Agent application to Assessment service: record_recommendation(SUB-1004, escalate, key). The first attempt, with the key generated once for this intent.
  2. Assessment service to Database: INSERT REC-0001 (key stored). One transaction through the uw_rec_writer account; it commits.
  3. Assessment service to Agent application: reply lost or late. The row exists, but the caller hits its timeout and sees nothing.
  4. Agent application to Assessment service: same call, same key. The caller retries, as it is built to do.
  5. Assessment service: key found, payload hash matches. The service recognizes the repeat. A different payload with this key would be a conflict.
  6. Assessment service to Agent application: REC-0001, idempotent_replay true. The stored result comes back; there is still one row.

The diagram shows the lost reply on a timeline. The decisive moment is the third message: the database has the row, and the caller does not know it. Everything after that depends on whether the second call can be recognized as a repeat.

Run it: a read, the same write twice, and three refusals#

This short driver calls the domain service directly: no model, no tool definition, no network. It shows that the read returns the DTO, that the same write twice leaves one row, that a reused key with a different payload is refused, and that failures arrive as errors with codes. A successful run proves the behavior of this in-memory service; it does not prove anything about concurrency, which the third folded block below takes up. It was run on 2026-11-18 in a scratch copy of examples/uw-mcp, with /opt/homebrew/bin/python3.

from domain import AssessmentService, Conflict, InvalidDto, NotFound, PropertyAssessment

service = AssessmentService()

# A read: arguments in, a typed result out, nothing changes.
print("read  ", service.get_roof_assessment("SUB-1004").to_dict())

# A write: it changes the database. Same key twice, then the same key with another payload.
rec = {"recommendation": "escalate",
       "reasons": ["Application 9 years, provider 22 years (EV-ROOF-0412)."],
       "citations": ["R-ROOF-03"]}
key = "SUB-1004:run-7f3a:recommendation"
print("write1", service.record_recommendation("SUB-1004", rec, key, recorded_by="agent:underwriting-agent"))
print("write2", service.record_recommendation("SUB-1004", rec, key, recorded_by="agent:underwriting-agent"))
print("rows  ", service.repo.count("recommendations"))
try:
    service.record_recommendation("SUB-1004", {**rec, "recommendation": "approve"}, key,
                                  recorded_by="agent:underwriting-agent")
except Conflict as e:
    print("write3", e.code, "-", e.message)

# Failures the function reports instead of returning a wrong value.
try:
    service.get_roof_assessment("SUB-9999")
except NotFound as e:
    print("read  ", e.code, "-", e.message)
try:
    PropertyAssessment("SUB-1004", "PROP-2207", -3, None, "roof-data provider (stand-in)",
                       "EV-ROOF-0412", None, "2026.2", "complete")
except InvalidDto as e:
    print("dto   ", e.code, "-", e.message)
service.close()
read   {'submission_id': 'SUB-1004', 'property_id': 'PROP-2207', 'roof_age_years': 22, 'roof_material': 'modified bitumen', 'evidence_source': 'roof-data provider (stand-in)', 'evidence_id': 'EV-ROOF-0412', 'assessed_at': '2026-08-03T14:20:00Z', 'policy_version': '2026.2', 'assessment_status': 'complete'}
write1 {'recommendation_id': 'REC-0001', 'submission_id': 'SUB-1004', 'recommendation': 'escalate', 'status': 'awaiting_underwriter', 'idempotent_replay': False}
write2 {'recommendation_id': 'REC-0001', 'submission_id': 'SUB-1004', 'recommendation': 'escalate', 'status': 'awaiting_underwriter', 'idempotent_replay': True}
rows   1
write3 conflict - This idempotency key was used with a different recommendation.
read   not_found - No submission SUB-9999.
dto    invalid_arguments - /roof_age_years: must be an integer from 0 to 150

What to notice. write2 returns the same REC-0001 with idempotent_replay true, and the row count stays at 1: the retry from the opening scene is now harmless. write3 shows the other half of the design: a key is a promise about one intent, and reusing it for a different recommendation is refused. The last two lines are errors with stable codes (not_found, invalid_arguments) that every adapter on later pages turns into its own error shape without rewriting the rule. The example's test test_domain.py:test_idempotency_key_gives_one_row checks the same property on every run of the suite.

The same service in Java#

The insurer's claims platform is written in Java, so the same contract has to make sense there. examples/uw-mcp/java/AssessmentService.java is a single-file program with the same shape: a DTO validated in its constructor, a repository interface with an in-memory implementation, and a service that separates the read from the write. It uses only the JDK. Java records were finalized in JDK 16 (JEP 395); running a single source file with java File.java exists since JDK 11 (JEP 330). Here it ran with JDK 23.

The record

A record's compact constructor runs before the fields are assigned, so throwing there means no invalid instance exists, the same guarantee as the Python __post_init__. Excerpt:

record PropertyAssessment(String submissionId, String propertyId, Integer roofAgeYears, String roofMaterial,
                          String evidenceSource, String evidenceId, String assessedAt, String policyVersion,
                          String assessmentStatus) {
    PropertyAssessment {
        if (submissionId == null || !SUBMISSION_ID.matcher(submissionId).matches())
            throw new IllegalArgumentException("/submission_id: must match ^SUB-[0-9]{4}$");
        // ... propertyId, assessmentStatus, roofAgeYears (0 to 150), evidenceId
    }
}

Read and write

The read needs uw.read; the write needs uw.recommend and honors the idempotency key. In this single-file demonstration the scope check sits inside the service; the first folded block below explains why the Python example puts it in a separate policy module instead.

String getRoofAssessment(Caller caller, String rawId) {
    if (!caller.scopes().contains("uw.read")) return error("not_authorized", "get_roof_assessment needs scope uw.read");
    SubmissionId id = new SubmissionId(rawId);
    return repo.findBySubmissionId(id).map(a -> "{\"ok\": true, \"data\": " + a.toJson() + "}")
               .orElse(error("not_found", "Submission " + id.value() + " was not found."));
}

String recordRecommendation(Caller caller, String rawId, String recommendation, String key) {
    if (!caller.scopes().contains("uw.recommend")) return error("not_authorized", "record_recommendation needs scope uw.recommend");
    SubmissionId id = new SubmissionId(rawId);
    if (!IDEMPOTENCY_KEY.matcher(key).matches()) throw new IllegalArgumentException("/idempotency_key: bad format");
    Optional<StoredRecommendation> existing = repo.findByIdempotencyKey(key);
    if (existing.isPresent())
        return "{\"ok\": true, \"data\": {\"recommendation_id\": " + q(existing.get().recommendationId())
            + ", \"idempotent_replay\": true, \"rows\": " + repo.recommendationCount() + "}}";
    // ... otherwise save a new StoredRecommendation and report idempotent_replay false
}

Real output

$ cd java && java AssessmentService.java
valid read             underwriting-agent  handled   {"ok": true, "data": {"submission_id": "SUB-1004", "property_id": "PROP-2207", "roof_age_years": 22, "roof_material": "modified bitumen", "evidence_source": "roof-data provider (stand-in)", "evidence_id": "EV-ROOF-0412", "assessed_at": "2026-08-03T14:20:00Z", "policy_version": "2026.2", "assessment_status": "complete"}}
invalid submission id  underwriting-agent  rejected  {"ok": false, "error": {"code": "invalid_arguments", "message": "/submission_id: must match ^SUB-[0-9]{4}$; got \"SUB-04\""}}
unknown submission     underwriting-agent  handled   {"ok": false, "error": {"code": "not_found", "message": "Submission SUB-9999 was not found."}}
missing scope (read)   analytics-jobs      handled   {"ok": false, "error": {"code": "not_authorized", "message": "get_roof_assessment needs scope uw.read"}}
valid write            underwriting-agent  handled   {"ok": true, "data": {"recommendation_id": "REC-0001", "status": "awaiting_underwriter", "idempotent_replay": false, "rows": 1}}
same key again         underwriting-agent  handled   {"ok": true, "data": {"recommendation_id": "REC-0001", "idempotent_replay": true, "rows": 1}}
missing scope (write)  intake-agent        handled   {"ok": false, "error": {"code": "not_authorized", "message": "record_recommendation needs scope uw.recommend"}}
invalid DTO            (constructor)       rejected  {"ok": false, "error": {"code": "invalid_arguments", "message": "/roof_age_years: must be an integer from 0 to 150"}}

The Java excerpts are quoted from the file; the whole file was compiled and run with java AssessmentService.java on JDK 23 (openjdk version "23.0.1") on 2026-11-18, and the output above is that run. The two languages agree on the field names on the wire (snake_case in JSON, camelCase inside Java), the error paths, the error codes and the replay behavior. That agreement is what Java and SDKs turns into a shared JSON Schema contract; Bean Validation and Spring are described there as documented shape.

What goes wrong without these ideas#

Each idea on this page prevents a specific failure, and the example shows most of them.

Without a typed, validated DTO, the read returns whatever dictionary the query produced. When a column is renamed, every consumer breaks at a different time, and some break silently by reading None. The validated DTO fails at the producer, with a path (/roof_age_years), on the first bad record.

Without a distinction between "not found" and "no record", the agent cannot tell a typo in the submission id from a roof nobody has assessed. Those lead to different recommendations: the first is an error to report, the second triggers R-ROOF-02 (request the roof age).

Without an idempotency key, a timeout followed by a retry creates the duplicate from the opening. Later on this site the same lost reply happens across a network (Client and server) and at a shared server under load. Case UW-M08 runs it: the service times out on the write, the client retries with the same key, and there is still one row.

Without separate database accounts for reading and writing, a bug or an injected instruction in a read path can reach a write. In the example, uw_reader cannot insert anything, so a read tool that is tricked into running a write statement is refused by the database itself.

Common confusion. "Idempotent" does not mean "returns the same value". A read of a roof that a provider re-assesses tomorrow returns a different value, and it is still a read with no side effect. Idempotent means that repeating the call adds no further effect. A write can be idempotent; a read is free of effects.

How frameworks and protocols describe a function#

Once a function is offered to a model or published on a server, the read or write distinction travels with it as metadata. Normative (MCP specification 2026-07-28): a tool may carry annotations such as readOnlyHint, destructiveHint and idempotentHint; all of them are hints, readOnlyHint defaults to false, and clients must treat annotations as untrusted unless they come from a trusted server. So the protocol lets a server say "this is a read", and it explicitly does not let anyone rely on that statement for safety. Three surfaces covers annotations. This site's recommendation: set the hints honestly, and enforce the property in the function and the database account, where it cannot be faked.

Ecosystem pattern: frameworks generate a tool's input schema from a function's signature (Pydantic models in Python, annotated records in Java). That saves typing and keeps the schema next to the code. It does not decide whether the function is safe to repeat; the function body does. Java and SDKs compares the generators as documented shape.

What this is not. This page does not teach functions as tools in depth: pure and impure functions, errors turned into results for a model, and the five functions of the insurance example are covered on Tools Engineering: functions. Here the function is the bottom rung of a platform, and the questions are the ones that grow when other teams call it.

Security and governance notes#

Security note. The function does not know who calls it. That is correct for a domain service, and it is also why every later layer must establish the caller before the function runs. In the example the database accounts give a floor that holds even if a layer above fails: uw_reader reads, uw_rec_writer inserts recommendations only, uw_decision_writer inserts decisions only, and only the domain team's deploy job holds owner.
Governance note. A write needs an owner who answers for its effects. For record_recommendation that is the assessment domain (the property-risk data team); its catalog record on later pages marks it risk tier high, and the decision tool critical. Decide the owner when the write is designed, not when it is first shared.
In a coding agent. The same split appears in a coding agent's tools. Reading a file or searching the code is a read; the agent may repeat it freely. Opening a pull request is a write: a retry after a lost reply can open two, so a careful implementation looks for an existing pull request from the same branch before creating one, which acts as its idempotency key. Harness Engineering shows where such tools sit in the agent's runtime.

Checklist for Monday#

Exercises#

  1. get_assessment_status("SUB-1004") returns a stage such as awaiting_underwriter. Calling it twice an hour apart gives two different stages. Is it a read or a write, and is it idempotent?
  2. A colleague proposes making record_recommendation safe to retry by checking whether a recommendation for the same submission already exists, instead of using a key. What breaks?
  3. Why does the idempotency key include the run id (run-7f3a) instead of only the submission id?
AnswersOne line each
  1. A read: it changes nothing, so it has no effect to repeat; its value changes because the world changed between the calls.
  2. A legitimate second recommendation for the same submission (a new run after new evidence) would be swallowed as a duplicate; the key separates "the same intent again" from "a new intent".
  3. A new run of the agent is a new intent and must be able to write a new recommendation, while retries inside one run must collapse into one row.
Where should the permission check live?Inside the service, in a policy module, or at the adapter: three designs and what each costs

The Java file checks the caller's scope inside the service method. The Python example does not: AssessmentService has no idea who calls, and the check lives in policy.py (authorize), which the adapters (the stage 2 tool adapter, the MCP server, the REST controller) call before the service. Both are defensible, and the difference matters once three adapters share one service.

A check inside the service is impossible to forget: every adapter goes through it. Its cost is that the service must understand the caller's identity model (scopes, principal types, business units), so the domain code now depends on the identity design, and a change of token format touches business code. A check in a separate policy module keeps the domain clean and lets the same pure function be tested as a matrix (Testing) and ported to the browser labs. Its cost is that an adapter that forgets to call it opens a hole.

The example combines the two for the one write where a mistake is unacceptable. record_underwriter_decision is authorized in policy.py (scope uw.decide, principal type user, role underwriter, client uw-cockpit) and the service checks again that the actor is a user with the underwriter role. This site's recommendation: keep general authorization in one policy module called by every adapter, and add a second check inside the domain service only for writes whose misuse would be a decision rather than a recommendation. Defense in depth is worth its duplication exactly where the consequence is irreversible.

Exceptions in the domain, error shapes at the edgeOne error vocabulary, many wire formats

The domain raises a small family of exceptions, each with a stable code: NotFound (not_found), Conflict (conflict), NotPermitted (not_authorized), InvalidDto (invalid_arguments). It never returns an HTTP status or a protocol error, because it does not know which protocol is in front of it.

Each adapter translates. The REST controller in stages.py turns NotFound into HTTP 404. The MCP server turns a domain error into a tool result with isError true and the same code in its body, so a model can read it and correct itself. A future gRPC adapter would map the same codes to its own status codes. The vocabulary stays fixed; only the envelope changes.

Two failure designs are worth naming because they are common. The first returns None or an empty object for "not found", which forces every caller to guess, and which a model will happily read as "the roof has no age". The second leaks internal errors upward: a database message such as a constraint name reaching a caller tells an attacker about the schema. The example's DomainError carries a message written for the caller and keeps internal details out of it. This site's recommendation: define the domain's error codes once, document them with the DTO, and test that each adapter maps every code.

What the example's idempotency does not coverConcurrent duplicates, id generation, and how long keys live

record_recommendation reads by key, then inserts. That is enough for the sequential retry in this page's demonstration and in UW-M08. It is not a full design for concurrent calls. If two calls with the same key arrive at the same moment, both can find no existing row; the table's UNIQUE constraint on idempotency_key then lets only one insert succeed, so a duplicate row cannot exist, but the losing call receives a database error instead of the stored result. A production service catches that constraint violation, re-reads the row by key and returns it as a replay. Observed from the code read on 2026-11-18; the example does not exercise concurrency.

The recommendation id is computed from a row count (REC-0001 for the first row). Under concurrency two inserts could compute the same id; the primary key would then refuse one. A production table uses a sequence or a generated identifier. Both points are simplifications of a teaching example, not patterns to copy.

The third question is retention. Keys stored forever make the table grow forever; keys deleted too early turn a late retry into a second write. A common rule is to keep a key at least as long as the longest retry window any caller may use, and to record that window in the catalog entry. Resilience covers keys at a shared server, where several teams retry with different budgets.

When the DTO has to changeAdding, renaming and tightening fields once other teams read them

A DTO is cheap to change while one application uses it and expensive once four teams do. Three kinds of change behave differently. Adding an optional field is usually safe for readers that ignore unknown fields, and unsafe for readers that validate strictly, which is why the example's schema says additionalProperties: false on inputs and a careful consumer treats output schemas more leniently. Renaming a field is a breaking change for everyone, even when the meaning is the same. Tightening a rule (for example, making roof_material required) breaks producers that sent nothing.

The example has one real version change. Version 1 of get_roof_assessment took property_id; version 2 takes submission_id, because one property can carry several submissions, so a property id cannot name one assessment. A client built for version 1 receives invalid_arguments with two paths, /submission_id (required) and /property_id (unknown), and the deprecated version is named in the error. That is case UW-M07, and Sharing across teams explains the versioning and deprecation that turn it from a surprise into a planned migration.

In one breath#

A function is a promise about what goes in, what comes out and what it leaves changed. The roof lookup is a read: it returns a validated PropertyAssessment and changes nothing, so it can be repeated freely. The recommendation is a write: it adds a row, so a lost reply followed by a retry is a second event unless the function recognizes the repeat by an idempotency key. Design that difference into the function and its database accounts first; every layer added later can only preserve it, never create it.

So far the caller is the agent application's own code, which knows exactly which function it wants and with which arguments. The next step lets a model choose: the model writes a request naming a function and its arguments, and application code must decide whether to run it. That is Function calling.