Wire a protocol call into an SDK host
A protocol such as MCP or A2A gives a host connectivity: a way to call a remote tool or delegate a task, and a way for the remote side to report back. It never gives the host authority. The recipes on this page show the SDK half of that rule, with released SDK 0.5.1 APIs and the source-only aiws-protocol-correlation/1 helper (capability row “Cross-language protocol correlation helper”). They follow spec/engine-v1/PROTOCOL-BINDINGS.md §2: a protocol adapter never grants authority, approves, marks verification PASS, accepts a deliverable or turns an UNKNOWN effect into success without reconciliation evidence.
The recipes use no real MCP or A2A client. Each injects a client port and runs it against a local stand-in, marked “replace before deployment”, so the same code runs under docs:examples with no network. The official protocol SDKs remain the wire implementations; the Praxis protocol bindings are engine source that no host wires yet, and they are not covered here.
The correlation record
Section titled “The correlation record”An aiws-protocol-correlation/1 record ties one AIWS operation and attempt to the exact binding revision, protocol version and manifest and capability digests it ran under, and to the remote identity and remote operation ID when they are known. Its authoritative field is always the literal false. The record is closed: each SDK refuses an unknown key or a missing one, and checks the result against the shared schema in spec/protocol-correlation-v1 before returning it. The recipe builds a record for an admitted operation, reads it back from JSON, and shows that a record claiming authority, or carrying an approved key, is refused.
Correlate governed work with a protocol binding · Executable source-only SDK correlation example; no protocol client or authority is created
import assert from 'node:assert/strict';import {createMission,parseContract,reduce,protocolCorrelation,validateProtocolCorrelation} from '@aiws/sdk';
const contract=parseContract(JSON.stringify({id:'contract:protocol',missionId:'mission:protocol',aiwsEdition:'0.4',profile:'finite-v1',budget:'20',deadline:'1000',criteria:['remote-result-reviewed'],actions:['remote.invoke'],resources:['protocol:mcp'],requiresApproval:false,maxAttempts:'2',maxAuthorizationAgeMs:'100',features:[]}));let state=createMission(contract);state=reduce(state,{type:'startRun',runId:'run:1'},'10');state=reduce(state,{type:'grant',grant:{id:'grant:1',subject:'agent:1',profile:'finite-v1',actions:['remote.invoke'],resources:['protocol:mcp'],notBefore:'0',expiresAt:'1000',limit:'20',canDelegate:false,depth:'0'}},'10');state=reduce(state,{type:'admit',runId:'run:1',operationId:'operation:1',attemptId:'attempt:1',grantId:'grant:1',subject:'agent:1',action:{capability:'remote.invoke',resource:'protocol:mcp',payload:{tool:'echo'},preconditions:{}},amount:'5',authorizationCheckedAt:'10',policy:'ALLOW',mandatoryChecksOk:true},'10');
const correlation=protocolCorrelation( {bindingId:'mcp:official-v2',bindingRevision:'1',protocol:'MCP',protocolVersion:'2026-07-28',manifestDigest:'a'.repeat(64),capabilityDigest:'b'.repeat(64)}, {workOrderId:'mission:protocol',runId:'run:1',taskId:null,operationId:'operation:1',attemptId:'attempt:1',remoteIdentityRef:'mcp:praxis-m9-fixture@1.0.0',remoteOperationId:null});assert.equal(correlation.operation.operationId,'operation:1');assert.equal(correlation.authoritative,false);assert.equal(state.operations['operation:1'].runId,'run:1');
// The record is portable JSON: read back from the wire, it passes the same closed check unchanged.const wire=JSON.parse(JSON.stringify(correlation));assert.deepEqual(validateProtocolCorrelation(wire),correlation);// A record that claims authority, or carries a key the schema does not define, is refused.const refused=(e:any)=>e.code==='INVALID_PROTOCOL_CORRELATION';assert.throws(()=>validateProtocolCorrelation({...wire,authoritative:true}),refused);assert.throws(()=>validateProtocolCorrelation({...wire,approved:true}),refused);console.log(JSON.stringify(correlation));console.log('PASS: protocol-correlation');use aiws_sdk::*;use serde_json::json;
fn main()->Result<()>{ let contract=Contract::parse(&json!({"id":"contract:protocol","missionId":"mission:protocol","aiwsEdition":"0.4","profile":"finite-v1","budget":"20","deadline":"1000","criteria":["remote-result-reviewed"],"actions":["remote.invoke"],"resources":["protocol:mcp"],"requiresApproval":false,"maxAttempts":"2","maxAuthorizationAgeMs":"100","features":[]}).to_string())?; let mut state=create_mission(&contract)?; state=reduce(&state,&Command::from_value(json!({"type":"startRun","runId":"run:1"}))?,"10")?; state=reduce(&state,&Command::from_value(json!({"type":"grant","grant":{"id":"grant:1","subject":"agent:1","profile":"finite-v1","actions":["remote.invoke"],"resources":["protocol:mcp"],"notBefore":"0","expiresAt":"1000","limit":"20","canDelegate":false,"depth":"0"}}))?,"10")?; state=reduce(&state,&Command::from_value(json!({"type":"admit","runId":"run:1","operationId":"operation:1","attemptId":"attempt:1","grantId":"grant:1","subject":"agent:1","action":{"capability":"remote.invoke","resource":"protocol:mcp","payload":{"tool":"echo"},"preconditions":{}},"amount":"5","authorizationCheckedAt":"10","policy":"ALLOW","mandatoryChecksOk":true}))?,"10")?;
let correlation=protocol_correlation( ProtocolBindingRef{binding_id:"mcp:official-v2".into(),binding_revision:"1".into(),protocol:"MCP".into(),protocol_version:"2026-07-28".into(),manifest_digest:"a".repeat(64),capability_digest:"b".repeat(64)}, ProtocolOperationRef{work_order_id:"mission:protocol".into(),run_id:"run:1".into(),task_id:None,operation_id:"operation:1".into(),attempt_id:"attempt:1".into(),remote_identity_ref:Some("mcp:praxis-m9-fixture@1.0.0".into()),remote_operation_id:None} ).map_err(|code|AiwsError{code})?; assert_eq!(correlation.operation.operation_id,"operation:1"); assert!(!correlation.authoritative); assert_eq!(state.as_value()["operations"]["operation:1"]["runId"],json!("run:1"));
// The record is portable JSON: read back from the wire, it passes the same closed check unchanged. let wire=serde_json::to_value(&correlation).map_err(|_|AiwsError{code:"ENCODE".into()})?; assert_eq!(ProtocolCorrelation::from_value(wire.clone()).map_err(|code|AiwsError{code})?,correlation); // A record that claims authority, or carries a key the schema does not define, is refused. for (key,value) in [("authoritative",json!(true)),("approved",json!(true))]{ let mut claim=wire.clone(); claim[key]=value; assert_eq!(ProtocolCorrelation::from_value(claim),Err("INVALID_PROTOCOL_CORRELATION".to_string())); } println!("{wire}"); println!("PASS: protocol-correlation"); Ok(())}import jsonfrom aiws import create_mission,parse_contract,reduce,protocol_correlation,validate_protocol_correlation,ProtocolCorrelationError
contract=parse_contract(json.dumps({'id':'contract:protocol','missionId':'mission:protocol','aiwsEdition':'0.4','profile':'finite-v1','budget':'20','deadline':'1000','criteria':['remote-result-reviewed'],'actions':['remote.invoke'],'resources':['protocol:mcp'],'requiresApproval':False,'maxAttempts':'2','maxAuthorizationAgeMs':'100','features':[]}))state=create_mission(contract)state=reduce(state,{'type':'startRun','runId':'run:1'},'10')state=reduce(state,{'type':'grant','grant':{'id':'grant:1','subject':'agent:1','profile':'finite-v1','actions':['remote.invoke'],'resources':['protocol:mcp'],'notBefore':'0','expiresAt':'1000','limit':'20','canDelegate':False,'depth':'0'}},'10')state=reduce(state,{'type':'admit','runId':'run:1','operationId':'operation:1','attemptId':'attempt:1','grantId':'grant:1','subject':'agent:1','action':{'capability':'remote.invoke','resource':'protocol:mcp','payload':{'tool':'echo'},'preconditions':{}},'amount':'5','authorizationCheckedAt':'10','policy':'ALLOW','mandatoryChecksOk':True},'10')
correlation=protocol_correlation( {'bindingId':'mcp:official-v2','bindingRevision':'1','protocol':'MCP','protocolVersion':'2026-07-28','manifestDigest':'a'*64,'capabilityDigest':'b'*64}, {'workOrderId':'mission:protocol','runId':'run:1','taskId':None,'operationId':'operation:1','attemptId':'attempt:1','remoteIdentityRef':'mcp:praxis-m9-fixture@1.0.0','remoteOperationId':None})assert correlation['operation']['operationId']=='operation:1'assert correlation['authoritative'] is Falseassert state['operations']['operation:1']['runId']=='run:1'
# The record is portable JSON: read back from the wire, it passes the same closed check unchanged.wire=json.loads(json.dumps(correlation))assert validate_protocol_correlation(wire)==correlation# A record that claims authority, or carries a key the schema does not define, is refused.for claim in ({'authoritative':True},{'approved':True}): try: validate_protocol_correlation({**wire,**claim}) raise AssertionError('accepted '+json.dumps(claim)) except ProtocolCorrelationError as error: assert error.code=='INVALID_PROTOCOL_CORRELATION'print(json.dumps(correlation))print('PASS: protocol-correlation')A protocol tool call as an effect adapter
Section titled “A protocol tool call as an effect adapter”A remote tool call is an external effect, so it goes through an effect adapter like any other: the coordinator commits DISPATCHED first, and the adapter reports CONFIRMED_APPLIED, CONFIRMED_NOT_APPLIED or UNKNOWN.
- An injected client port. The adapter receives the client; it has a mutating
callTooland two read-only calls,listToolsandreadBack. - Re-discovery before each call. The adapter lists the server’s tools again and compares their digest with the reviewed capability digest (PROTOCOL-BINDINGS §8.1). A changed digest blocks before the call is sent, which is the one case where the adapter knows nothing was applied.
- UNKNOWN on a timeout or a transport error. Neither shows whether the server ran the tool. A tool error result is UNKNOWN too, because it carries no proof that nothing changed.
- A read-only reconcile by read-back.
reconcilelooks the idempotency key up in the server’s ticket index and never calls the tool. A recorded key proves the call applied; anything else stays UNKNOWN for a human. - The correlation record stored with the evidence. Every observation the adapter makes is appended to the host’s evidence log with its correlation record, including the remote ticket ID once read-back finds it.
- Remote data stays data. The stand-in server marks its own ticket
approved: true. The host stores that in the evidence and nothing else: the mission has no approval, no assessment, and a worker that tried to turn it into anapprovecommand would be refused by the deny-by-default authorizer.
Call a protocol tool through an effect adapter: injected client port, correlated evidence, UNKNOWN on a timeout, read-back reconcile · Executable local adapter demonstration; SDK 0.4.0 APIs; a simulated MCP server and identity, no protocol client or real transport
import assert from 'node:assert/strict';import { createHash } from 'node:crypto';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { canonical, parseCommand, parseContract, protocolCorrelation, type ProtocolBindingRef, type ProtocolCorrelation } from '@aiws/sdk';import { SqliteStore } from '@aiws/sdk/sqlite';import { Coordinator, type Authorizer, type EffectAdapter, type Outcome } from '@aiws/sdk/runtime';
/* * Operation contract (STANDARD E-01, E-04) for `ticket.create` on `protocol:mcp:tickets`, the ToolCallAdapter below. * - Effect: the remote MCP tool `create_ticket` opens one ticket. Idempotent under the key: the server stores the * key with the ticket in one transaction and returns the same ticket for a repeated key. * - Binding: the reviewed binding revision. Before each call the adapter lists the server's tools again and compares * their digest with the reviewed capability digest (PROTOCOL-BINDINGS 8.1). A changed digest blocks before the * call is sent, so nothing was applied. * - Timeout: 30 seconds. A tool result reports applied, at a cost of 2. A timeout, a transport error or a tool error * result proves nothing: the outcome is UNKNOWN. * - Reconciliation: read-only `readBack` of the key from the server's ticket index. A ticket recorded under the key * proves the call applied. Anything else, an absent key included, stays UNKNOWN for a human. * - Evidence: every observation is stored with its aiws-protocol-correlation/1 record. What the server returns is * data: an `approved: true` in a result approves nothing, verifies nothing and accepts nothing. */interface Tool { name: string; inputSchema: Record<string, unknown> }type ToolReply = { timedOut: true } | { isError: boolean; structuredContent: Record<string, unknown> };/** Own-property check on the client's plain reply object, never `in`. */const timedOut = (reply: ToolReply): reply is { timedOut: true } => Object.hasOwn(reply, 'timedOut');type ReadBack = { recorded: true; ticketId: string; content: Record<string, unknown> } | { recorded: false };/** The client port, injected by the host: an MCP client session in production, a fake server in tests. */interface ToolClient { /** Read-only: lists the server's tools as it declares them now. */ listTools(): Promise<Tool[]>; callTool(request: { name: string; arguments: unknown; idempotencyKey: string; timeoutMs: number }): Promise<ToolReply>; /** Read-only: looks the key up in the server's ticket index; never calls a tool. */ readBack(idempotencyKey: string): Promise<ReadBack>;}interface Evidence { id: string; correlation: ProtocolCorrelation; observation: string; data: Record<string, unknown> | null }/** The evidence port: an append-only store the host keeps beside the mission store. It grants nothing. */interface EvidenceLog { append(entry: Evidence): void }const sha256 = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');const idempotencyKey = (missionId: string, operation: Readonly<Record<string, any>>): string => `${missionId}/${operation.id}/${operation.fingerprint}`;const applied: Outcome = { effect: 'CONFIRMED_APPLIED', actualCost: '2' };const notApplied: Outcome = { effect: 'CONFIRMED_NOT_APPLIED', actualCost: '0' };const unknown: Outcome = { effect: 'UNKNOWN', actualCost: '0' };class ToolCallAdapter implements EffectAdapter { private missionId: string; private binding: ProtocolBindingRef; private remoteIdentityRef: string; private client: ToolClient; private evidence: EvidenceLog; constructor(missionId: string, binding: ProtocolBindingRef, remoteIdentityRef: string, client: ToolClient, evidence: EvidenceLog) { this.missionId = missionId; this.binding = binding; this.remoteIdentityRef = remoteIdentityRef; this.client = client; this.evidence = evidence; } private record(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>, observation: string, data: Record<string, unknown> | null, remoteOperationId: string | null): void { const correlation = protocolCorrelation(this.binding, { workOrderId: this.missionId, runId: operation.runId, taskId: null, operationId: operation.id, attemptId: attempt.id, remoteIdentityRef: this.remoteIdentityRef, remoteOperationId }); this.evidence.append({ id: `evidence:${attempt.id}:${observation}`, correlation, observation, data }); } async execute(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>): Promise<Outcome> { let reply: ToolReply; try { if (sha256(await this.client.listTools()) !== this.binding.capabilityDigest) { this.record(operation, attempt, 'CAPABILITY_CHANGED', null, null); return notApplied; // Blocked before the call was sent: nothing reached the server. } reply = await this.client.callTool({ name: 'create_ticket', arguments: operation.action.payload, idempotencyKey: idempotencyKey(this.missionId, operation), timeoutMs: 30_000 }); } catch { this.record(operation, attempt, 'TRANSPORT_ERROR', null, null); return unknown; // A thrown transport error does not show whether the server ran the tool. } if (timedOut(reply)) { this.record(operation, attempt, 'TIMED_OUT', null, null); return unknown; // A timeout never proves the call did not happen. } this.record(operation, attempt, reply.isError ? 'TOOL_ERROR' : 'RESULT', reply.structuredContent, null); return reply.isError ? unknown : applied; // A tool error result carries no proof that nothing changed. } async reconcile(operation: Readonly<Record<string, any>>, attempt: Readonly<Record<string, any>>): Promise<Outcome> { let found: ReadBack; try { found = await this.client.readBack(idempotencyKey(this.missionId, operation)); } catch { return unknown; } if (!found.recorded) return unknown; // An absent key does not prove that a late call will not land. this.record(operation, attempt, 'READ_BACK', found.content, found.ticketId); return applied; }}
// ---- A local MCP server stand-in that runs the tool and then loses the response: replace before deployment. ----class LossyTicketServer implements ToolClient { tools: Tool[] = [{ name: 'create_ticket', inputSchema: { type: 'object', required: ['title'] } }]; calls = 0; tickets = new Map<string, { ticketId: string; content: Record<string, unknown> }>(); async listTools(): Promise<Tool[]> { return structuredClone(this.tools); } async callTool(request: { arguments: unknown; idempotencyKey: string }): Promise<ToolReply> { this.calls++; if (!this.tickets.has(request.idempotencyKey)) { // The remote side marks its own ticket approved. That is the server's data, not an AIWS approval. this.tickets.set(request.idempotencyKey, { ticketId: `ticket:T-${this.tickets.size + 1}`, content: { ticket: `T-${this.tickets.size + 1}`, approved: true, request: request.arguments } }); } return { timedOut: true }; // Applied, but the response never arrived. } async readBack(key: string): Promise<ReadBack> { const ticket = this.tickets.get(key); return ticket ? { recorded: true, ...structuredClone(ticket) } : { recorded: false }; }}
// The reviewed binding: its digests are computed from the manifest and tool list a human reviewed.const server = new LossyTicketServer();const binding: ProtocolBindingRef = { bindingId: 'mcp:tickets', bindingRevision: '1', protocol: 'MCP', protocolVersion: '2026-07-28', manifestDigest: sha256({ bindingId: 'mcp:tickets', protocol: 'MCP', protocolVersion: '2026-07-28', endpointRef: 'endpoint:tickets' }), capabilityDigest: sha256(server.tools) };const log: Evidence[] = [];const adapter = new ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', server, { append: (entry) => log.push(structuredClone(entry)) });
// Simulated identity: replace before deployment. Deny by default; each rule names the one session it allows.type Session = { actor: string; kind: 'HUMAN' | 'RULE' | 'AGENT' };const RUNNER: Session = { actor: 'host:runner', kind: 'RULE' }, AGENT: Session = { actor: 'agent:triage', kind: 'AGENT' };const OWNER: Session = { actor: 'human:owner', kind: 'HUMAN' }, WORKER: Session = { actor: 'host:worker-1', kind: 'RULE' };function permits(session: Session, c: any): boolean { switch (c.type) { case 'startRun': return session === RUNNER; case 'grant': return session === OWNER; case 'admit': return session === AGENT && c.subject === AGENT.actor && c.action.capability === 'ticket.create'; case 'dispatch': case 'settle': return session === WORKER; default: return false; // approve, revokeGrant, verify, accept and the rest: never from this host's rules. }}const authorizerFor = (session: Session): Authorizer => async (command) => { const allowed = permits(session, command); return { allowed, policy: allowed ? 'ALLOW' : 'DENY', mandatoryChecksOk: true, context: { actor: session.actor, policyRevision: 'policy:1', decisionClass: session.kind === 'HUMAN' ? 'HUMAN' : 'DETERMINISTIC' } };};const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['ticket-reviewed'], actions: ['ticket.create'], resources: ['protocol:mcp:tickets'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: [] }));const store = new SqliteStore(join(mkdtempSync(join(tmpdir(), 'aiws-protocol-call-')), 'mission.db'), contract);const as = (session: Session) => new Coordinator(store, authorizerFor(session), () => '10');const admit = (operationId: string, attemptId: string) => as(AGENT).apply(parseCommand(canonical({ type: 'admit', runId: 'r', operationId, attemptId, grantId: 'g', subject: AGENT.actor, action: { capability: 'ticket.create', resource: 'protocol:mcp:tickets', payload: { title: 'Guard missing on press 4' }, preconditions: {} }, amount: '10', authorizationCheckedAt: '10', policy: 'ALLOW', mandatoryChecksOk: true })));try { await as(RUNNER).apply(parseCommand(canonical({ type: 'startRun', runId: 'r' }))); await as(OWNER).apply(parseCommand(canonical({ type: 'grant', grant: { id: 'g', subject: AGENT.actor, profile: 'finite-v1', actions: ['ticket.create'], resources: ['protocol:mcp:tickets'], notBefore: '0', expiresAt: '10000', limit: '100', canDelegate: false, depth: '0' } }))); await admit('o1', 'a1'); let state = await as(WORKER).dispatch('a1', adapter); assert.equal(state.attempts.a1.status, 'UNKNOWN'); // The tool ran, but the timeout proves nothing. assert.equal(state.reserved, '10'); // UNKNOWN keeps the reservation. state = await as(WORKER).reconcile('a1', adapter); // Read-only: reads the key back, never calls the tool. assert.equal(state.operations.o1.effect, 'CONFIRMED_APPLIED'); assert.equal(state.spent, '2'); assert.equal(server.calls, 1); // Called exactly once. // The server's `approved: true` is stored as evidence data. It is not an approval, a PASS or an acceptance. assert.equal(log[1].data?.approved, true); assert.equal(Object.keys(state.approvals).length, 0); assert.equal(Object.keys(state.assessments).length, 0); // A host that turned it into an approve command would be refused: no rule lets a worker approve. await assert.rejects(as(WORKER).apply(parseCommand(canonical({ type: 'approve', approval: { id: 'ap', runId: 'r', approver: WORKER.actor, fingerprint: state.operations.o1.fingerprint, expiresAt: '1000', uses: '1' } }))), (e: any) => e.code === 'AUTHORITY_DENIED');
// The server changes its tool declaration. The next call is blocked before it is sent. server.tools[0].inputSchema = { type: 'object', required: ['title', 'assignee'] }; await admit('o2', 'a2'); state = await as(WORKER).dispatch('a2', adapter); assert.equal(state.operations.o2.effect, 'CONFIRMED_NOT_APPLIED'); assert.equal(server.calls, 1);
// A transport that fails reports UNKNOWN: classification checked on a scripted client, outside the coordinator. const failing: ToolClient = { listTools: async () => [{ name: 'create_ticket', inputSchema: { type: 'object', required: ['title'] } }], callTool: async () => { throw new Error('connection reset'); }, readBack: async () => { throw new Error('connection reset'); } }; const scratch: Evidence[] = []; const probe = new ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', failing, { append: (entry) => scratch.push(entry) }); assert.equal((await probe.execute(state.operations.o1, state.attempts.a1)).effect, 'UNKNOWN'); assert.equal((await probe.reconcile(state.operations.o1, state.attempts.a1)).effect, 'UNKNOWN');
assert.deepEqual(log.map((e) => e.observation), ['TIMED_OUT', 'READ_BACK', 'CAPABILITY_CHANGED']); for (const entry of log) console.log(JSON.stringify(entry.correlation)); console.log('PASS: protocol-call');} finally { store.close();}use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::*;use serde_json::{json, Value};use std::cell::{Cell, RefCell};use std::rc::Rc;
// Operation contract (STANDARD E-01, E-04) for `ticket.create` on `protocol:mcp:tickets`, the ToolCallAdapter below.// - Effect: the remote MCP tool `create_ticket` opens one ticket. Idempotent under the key: the server stores the// key with the ticket in one transaction and returns the same ticket for a repeated key.// - Binding: the reviewed binding revision. Before each call the adapter lists the server's tools again and compares// their digest with the reviewed capability digest (PROTOCOL-BINDINGS 8.1). A changed digest blocks before the// call is sent, so nothing was applied.// - Timeout: 30 seconds. A tool result reports applied, at a cost of 2. A timeout, a transport error or a tool error// result proves nothing: the outcome is UNKNOWN.// - Reconciliation: read-only `read_back` of the key from the server's ticket index. A ticket recorded under the key// proves the call applied. Anything else, an absent key included, stays UNKNOWN for a human.// - Evidence: every observation is stored with its aiws-protocol-correlation/1 record. What the server returns is// data: an `approved: true` in a result approves nothing, verifies nothing and accepts nothing.pub enum ToolReply { TimedOut, Result { is_error: bool, structured_content: Value },}pub enum ReadBack { Recorded { ticket_id: String, content: Value }, Absent,}/// The client port, injected by the host: an MCP client session in production, a fake server in tests.pub trait ToolClient { /// Read-only: lists the server's tools as it declares them now. fn list_tools(&mut self) -> std::result::Result<Value, String>; fn call_tool(&mut self, request: &Value) -> std::result::Result<ToolReply, String>; /// Read-only: looks the key up in the server's ticket index; never calls a tool. fn read_back(&mut self, idempotency_key: &str) -> std::result::Result<ReadBack, String>;}#[derive(Clone)]pub struct Evidence { pub id: String, pub correlation: ProtocolCorrelation, pub observation: String, pub data: Option<Value>,}/// The evidence port: an append-only store the host keeps beside the mission store. It grants nothing.pub trait EvidenceLog { fn append(&mut self, entry: Evidence);}pub fn sha256(value: &Value) -> Result<String> { Ok(digest(value)?.trim_start_matches("sha256:").to_owned())}pub fn idempotency_key(mission_id: &str, operation: &Value) -> String { format!( "{}/{}/{}", mission_id, operation["id"].as_str().unwrap_or_default(), operation["fingerprint"].as_str().unwrap_or_default() )}fn outcome(effect: &str, actual_cost: &str) -> Outcome { Outcome { effect: effect.into(), actual_cost: actual_cost.into(), }}fn applied() -> Outcome { outcome("CONFIRMED_APPLIED", "2")}fn not_applied() -> Outcome { outcome("CONFIRMED_NOT_APPLIED", "0")}fn unknown() -> Outcome { outcome("UNKNOWN", "0")}pub struct ToolCallAdapter<T: ToolClient, L: EvidenceLog> { pub mission_id: String, pub binding: ProtocolBindingRef, pub remote_identity_ref: String, pub client: T, pub evidence: L,}impl<T: ToolClient, L: EvidenceLog> ToolCallAdapter<T, L> { fn record(&mut self, operation: &Value, attempt: &Value, observation: &str, data: Option<Value>, remote_operation_id: Option<String>) -> Result<()> { let text = |v: &Value| v.as_str().unwrap_or_default().to_owned(); let correlation = protocol_correlation( self.binding.clone(), ProtocolOperationRef { work_order_id: self.mission_id.clone(), run_id: text(&operation["runId"]), task_id: None, operation_id: text(&operation["id"]), attempt_id: text(&attempt["id"]), remote_identity_ref: Some(self.remote_identity_ref.clone()), remote_operation_id, }, ) .map_err(|code| AiwsError { code })?; let id = format!("evidence:{}:{}", text(&attempt["id"]), observation); self.evidence.append(Evidence { id, correlation, observation: observation.into(), data }); Ok(()) }}impl<T: ToolClient, L: EvidenceLog> EffectAdapter for ToolCallAdapter<T, L> { fn execute(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { let tools = match self.client.list_tools() { Ok(tools) => tools, Err(_) => { self.record(operation, attempt, "TRANSPORT_ERROR", None, None)?; return Ok(unknown()); } }; if sha256(&tools)? != self.binding.capability_digest { self.record(operation, attempt, "CAPABILITY_CHANGED", None, None)?; // Blocked before the call was sent: nothing reached the server. return Ok(not_applied()); } let request = json!({ "name": "create_ticket", "arguments": operation["action"]["payload"], "idempotencyKey": idempotency_key(&self.mission_id, operation), "timeoutMs": 30000 }); match self.client.call_tool(&request) { // A thrown transport error does not show whether the server ran the tool. Err(_) => { self.record(operation, attempt, "TRANSPORT_ERROR", None, None)?; Ok(unknown()) } // A timeout never proves the call did not happen. Ok(ToolReply::TimedOut) => { self.record(operation, attempt, "TIMED_OUT", None, None)?; Ok(unknown()) } // A tool error result carries no proof that nothing changed. Ok(ToolReply::Result { is_error, structured_content }) => { self.record(operation, attempt, if is_error { "TOOL_ERROR" } else { "RESULT" }, Some(structured_content), None)?; Ok(if is_error { unknown() } else { applied() }) } } } fn reconcile(&mut self, operation: &Value, attempt: &Value) -> Result<Outcome> { match self.client.read_back(&idempotency_key(&self.mission_id, operation)) { Err(_) => Ok(unknown()), // An absent key does not prove that a late call will not land. Ok(ReadBack::Absent) => Ok(unknown()), Ok(ReadBack::Recorded { ticket_id, content }) => { self.record(operation, attempt, "READ_BACK", Some(content), Some(ticket_id))?; Ok(applied()) } } }}
// ---- A local MCP server stand-in that runs the tool and then loses the response: replace before deployment. ----struct LossyTicketServer { tools: Value, calls: u32, tickets: std::collections::BTreeMap<String, (String, Value)>,}impl ToolClient for LossyTicketServer { fn list_tools(&mut self) -> std::result::Result<Value, String> { Ok(self.tools.clone()) } fn call_tool(&mut self, request: &Value) -> std::result::Result<ToolReply, String> { self.calls += 1; let key = request["idempotencyKey"].as_str().ok_or("idempotencyKey")?.to_owned(); if !self.tickets.contains_key(&key) { // The remote side marks its own ticket approved. That is the server's data, not an AIWS approval. let n = self.tickets.len() + 1; self.tickets.insert(key, (format!("ticket:T-{n}"), json!({"ticket": format!("T-{n}"), "approved": true, "request": request["arguments"]}))); } Ok(ToolReply::TimedOut) // Applied, but the response never arrived. } fn read_back(&mut self, key: &str) -> std::result::Result<ReadBack, String> { Ok(match self.tickets.get(key) { Some((ticket_id, content)) => ReadBack::Recorded { ticket_id: ticket_id.clone(), content: content.clone() }, None => ReadBack::Absent, }) }}#[derive(Clone, Default)]struct Log(Rc<RefCell<Vec<Evidence>>>);impl EvidenceLog for Log { fn append(&mut self, entry: Evidence) { self.0.borrow_mut().push(entry); }}
// Simulated identity: replace before deployment. Deny by default; each rule names the one session it allows.struct Session { actor: &'static str, kind: &'static str,}static RUNNER: Session = Session { actor: "host:runner", kind: "RULE" };static AGENT: Session = Session { actor: "agent:triage", kind: "AGENT" };static OWNER: Session = Session { actor: "human:owner", kind: "HUMAN" };static WORKER: Session = Session { actor: "host:worker-1", kind: "RULE" };fn permits(session: &'static Session, c: &Value) -> bool { let is = |s: &'static Session| std::ptr::eq(session, s); match c["type"].as_str().unwrap_or_default() { "startRun" => is(&RUNNER), "grant" => is(&OWNER), "admit" => is(&AGENT) && c["subject"] == AGENT.actor && c["action"]["capability"] == "ticket.create", "dispatch" | "settle" => is(&WORKER), // approve, revokeGrant, verify, accept and the rest: never from this host's rules. _ => false, }}/// The session the host authenticated for the command it is about to apply.struct Policy(Rc<Cell<&'static Session>>);impl Authorizer for Policy { fn authorize(&mut self, command: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { let session = self.0.get(); let allowed = permits(session, command.as_value()); Ok(Authorization { allowed, policy: if allowed { "ALLOW" } else { "DENY" }.into(), mandatory_checks_ok: true, context: json!({"actor": session.actor, "policyRevision": "policy:1", "decisionClass": if session.kind == "HUMAN" { "HUMAN" } else { "DETERMINISTIC" }}), }) }}struct Fixed;impl Clock for Fixed { fn now_ms(&self) -> String { "10".into() }}fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { // The reviewed binding: its digests are computed from the manifest and tool list a human reviewed. let reviewed_tools = json!([{"name": "create_ticket", "inputSchema": {"type": "object", "required": ["title"]}}]); let binding = ProtocolBindingRef { binding_id: "mcp:tickets".into(), binding_revision: "1".into(), protocol: "MCP".into(), protocol_version: "2026-07-28".into(), manifest_digest: sha256(&json!({"bindingId": "mcp:tickets", "protocol": "MCP", "protocolVersion": "2026-07-28", "endpointRef": "endpoint:tickets"}))?, capability_digest: sha256(&reviewed_tools)?, }; let log = Log::default(); let mut adapter = ToolCallAdapter { mission_id: "m".into(), binding: binding.clone(), remote_identity_ref: "mcp:tickets-server@3.1.0".into(), client: LossyTicketServer { tools: reviewed_tools.clone(), calls: 0, tickets: Default::default() }, evidence: log.clone(), }; let contract = Contract::parse(&json!({"id":"c","missionId":"m","aiwsEdition":"0.4","profile":"finite-v1","budget":"100","deadline":"10000","criteria":["ticket-reviewed"],"actions":["ticket.create"],"resources":["protocol:mcp:tickets"],"requiresApproval":false,"maxAttempts":"2","maxAuthorizationAgeMs":"10","features":[]}).to_string())?; let directory = std::env::temp_dir().join(format!( "aiws-protocol-call-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos() )); std::fs::create_dir(&directory)?; let store = SqliteStore::open(directory.join("mission.db").to_str().unwrap(), Some(&contract))?; let session = Rc::new(Cell::new(&RUNNER)); let mut c = Coordinator::new(store, Policy(session.clone()), Fixed); let admit = |operation_id: &str, attempt_id: &str| json!({"type":"admit","runId":"r","operationId":operation_id,"attemptId":attempt_id,"grantId":"g","subject":AGENT.actor,"action":{"capability":"ticket.create","resource":"protocol:mcp:tickets","payload":{"title":"Guard missing on press 4"},"preconditions":{}},"amount":"10","authorizationCheckedAt":"10","policy":"ALLOW","mandatoryChecksOk":true}); for (who, raw) in [ (&RUNNER, json!({"type":"startRun","runId":"r"})), (&OWNER, json!({"type":"grant","grant":{"id":"g","subject":AGENT.actor,"profile":"finite-v1","actions":["ticket.create"],"resources":["protocol:mcp:tickets"],"notBefore":"0","expiresAt":"10000","limit":"100","canDelegate":false,"depth":"0"}})), (&AGENT, admit("o1", "a1")), ] { session.set(who); c.apply(&Command::from_value(raw)?, None)?; } session.set(&WORKER); let state = c.dispatch("a1", &mut adapter, None)?; assert_eq!(state.as_value()["attempts"]["a1"]["status"], "UNKNOWN"); // The tool ran, but the timeout proves nothing. assert_eq!(state.as_value()["reserved"], "10"); // UNKNOWN keeps the reservation. let state = c.reconcile("a1", &mut adapter)?; // Read-only: reads the key back, never calls the tool. assert_eq!(state.as_value()["operations"]["o1"]["effect"], "CONFIRMED_APPLIED"); assert_eq!(state.as_value()["spent"], "2"); assert_eq!(adapter.client.calls, 1); // Called exactly once. // The server's `approved: true` is stored as evidence data. It is not an approval, a PASS or an acceptance. assert_eq!(log.0.borrow()[1].data.as_ref().unwrap()["approved"], true); assert!(state.as_value()["approvals"].as_object().unwrap().is_empty()); assert!(state.as_value()["assessments"].as_object().unwrap().is_empty()); // A host that turned it into an approve command would be refused: no rule lets a worker approve. let approve = json!({"type":"approve","approval":{"id":"ap","runId":"r","approver":WORKER.actor,"fingerprint":state.as_value()["operations"]["o1"]["fingerprint"],"expiresAt":"1000","uses":"1"}}); assert_eq!(c.apply(&Command::from_value(approve)?, None).unwrap_err().code, "AUTHORITY_DENIED");
// The server changes its tool declaration. The next call is blocked before it is sent. adapter.client.tools[0]["inputSchema"] = json!({"type": "object", "required": ["title", "assignee"]}); session.set(&AGENT); c.apply(&Command::from_value(admit("o2", "a2"))?, None)?; session.set(&WORKER); let state = c.dispatch("a2", &mut adapter, None)?; assert_eq!(state.as_value()["operations"]["o2"]["effect"], "CONFIRMED_NOT_APPLIED"); assert_eq!(adapter.client.calls, 1);
// A transport that fails reports UNKNOWN: classification checked on a scripted client, outside the coordinator. struct Failing(Value); impl ToolClient for Failing { fn list_tools(&mut self) -> std::result::Result<Value, String> { Ok(self.0.clone()) } fn call_tool(&mut self, _: &Value) -> std::result::Result<ToolReply, String> { Err("connection reset".into()) } fn read_back(&mut self, _: &str) -> std::result::Result<ReadBack, String> { Err("connection reset".into()) } } let mut probe = ToolCallAdapter { mission_id: "m".into(), binding, remote_identity_ref: "mcp:tickets-server@3.1.0".into(), client: Failing(reviewed_tools), evidence: Log::default() }; let (operation, attempt) = (&state.as_value()["operations"]["o1"], &state.as_value()["attempts"]["a1"]); assert_eq!(probe.execute(operation, attempt)?.effect, "UNKNOWN"); assert_eq!(probe.reconcile(operation, attempt)?.effect, "UNKNOWN");
let entries = log.0.borrow(); assert_eq!(entries.iter().map(|e| e.observation.as_str()).collect::<Vec<_>>(), ["TIMED_OUT", "READ_BACK", "CAPABILITY_CHANGED"]); for entry in entries.iter() { println!("{}", serde_json::to_string(&entry.correlation)?); } println!("PASS: protocol-call"); Ok(())}"""Call a protocol tool through an effect adapter, then run it through the coordinator with a lossy local server."""import copyimport hashlibimport jsonimport tempfilefrom pathlib import Pathfrom typing import Optional, Protocol, TypedDict, Unionfrom aiws import protocol_correlationfrom aiws.core import canonical, parse_contractfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator, Outcome
# Operation contract (STANDARD E-01, E-04) for `ticket.create` on `protocol:mcp:tickets`, the ToolCallAdapter below.# - Effect: the remote MCP tool `create_ticket` opens one ticket. Idempotent under the key: the server stores the# key with the ticket in one transaction and returns the same ticket for a repeated key.# - Binding: the reviewed binding revision. Before each call the adapter lists the server's tools again and compares# their digest with the reviewed capability digest (PROTOCOL-BINDINGS 8.1). A changed digest blocks before the# call is sent, so nothing was applied.# - Timeout: 30 seconds. A tool result reports applied, at a cost of 2. A timeout, a transport error or a tool error# result proves nothing: the outcome is UNKNOWN.# - Reconciliation: read-only `read_back` of the key from the server's ticket index. A ticket recorded under the key# proves the call applied. Anything else, an absent key included, stays UNKNOWN for a human.# - Evidence: every observation is stored with its aiws-protocol-correlation/1 record. What the server returns is# data: an `approved: true` in a result approves nothing, verifies nothing and accepts nothing.class TimedOut(TypedDict): timedOut: boolclass ToolResult(TypedDict): isError: bool structuredContent: dictToolReply = Union[TimedOut, ToolResult]class ToolClient(Protocol): """The client port, injected by the host: an MCP client session in production, a fake server in tests.""" def list_tools(self) -> list: """Read-only: lists the server's tools as it declares them now.""" ... def call_tool(self, request: dict) -> ToolReply: ... def read_back(self, idempotency_key: str) -> dict: """Read-only: looks the key up in the server's ticket index; never calls a tool.""" ...class EvidenceLog(Protocol): """The evidence port: an append-only store the host keeps beside the mission store. It grants nothing.""" def append(self, entry: dict) -> None: ...def sha256(value) -> str: return hashlib.sha256(canonical(value).encode()).hexdigest()def idempotency_key(mission_id: str, operation: dict) -> str: return f"{mission_id}/{operation['id']}/{operation['fingerprint']}"APPLIED: Outcome = {'effect': 'CONFIRMED_APPLIED', 'actualCost': '2'}NOT_APPLIED: Outcome = {'effect': 'CONFIRMED_NOT_APPLIED', 'actualCost': '0'}UNKNOWN: Outcome = {'effect': 'UNKNOWN', 'actualCost': '0'}class ToolCallAdapter: def __init__(self, mission_id: str, binding: dict, remote_identity_ref: str, client: ToolClient, evidence: EvidenceLog): self.mission_id, self.binding, self.remote_identity_ref, self.client, self.evidence = mission_id, binding, remote_identity_ref, client, evidence def record(self, operation: dict, attempt: dict, observation: str, data: Optional[dict], remote_operation_id: Optional[str]) -> None: correlation = protocol_correlation(self.binding, {'workOrderId': self.mission_id, 'runId': operation['runId'], 'taskId': None, 'operationId': operation['id'], 'attemptId': attempt['id'], 'remoteIdentityRef': self.remote_identity_ref, 'remoteOperationId': remote_operation_id}) self.evidence.append({'id': f"evidence:{attempt['id']}:{observation}", 'correlation': correlation, 'observation': observation, 'data': data}) def execute(self, operation: dict, attempt: dict) -> Outcome: try: if sha256(self.client.list_tools()) != self.binding['capabilityDigest']: self.record(operation, attempt, 'CAPABILITY_CHANGED', None, None) return dict(NOT_APPLIED) # Blocked before the call was sent: nothing reached the server. reply = self.client.call_tool({'name': 'create_ticket', 'arguments': operation['action']['payload'], 'idempotencyKey': idempotency_key(self.mission_id, operation), 'timeoutMs': 30000}) except Exception: self.record(operation, attempt, 'TRANSPORT_ERROR', None, None) return dict(UNKNOWN) # A thrown transport error does not show whether the server ran the tool. if 'timedOut' in reply: self.record(operation, attempt, 'TIMED_OUT', None, None) return dict(UNKNOWN) # A timeout never proves the call did not happen. self.record(operation, attempt, 'TOOL_ERROR' if reply['isError'] else 'RESULT', reply['structuredContent'], None) return dict(UNKNOWN if reply['isError'] else APPLIED) # A tool error result carries no proof that nothing changed. def reconcile(self, operation: dict, attempt: dict) -> Outcome: try: found = self.client.read_back(idempotency_key(self.mission_id, operation)) except Exception: return dict(UNKNOWN) if not found['recorded']: return dict(UNKNOWN) # An absent key does not prove that a late call will not land. self.record(operation, attempt, 'READ_BACK', found['content'], found['ticketId']) return dict(APPLIED)
# ---- A local MCP server stand-in that runs the tool and then loses the response: replace before deployment. ----class LossyTicketServer: def __init__(self): self.tools = [{'name': 'create_ticket', 'inputSchema': {'type': 'object', 'required': ['title']}}] self.calls, self.tickets = 0, {} def list_tools(self): return copy.deepcopy(self.tools) def call_tool(self, request): self.calls += 1 if request['idempotencyKey'] not in self.tickets: # The remote side marks its own ticket approved. That is the server's data, not an AIWS approval. n = len(self.tickets) + 1 self.tickets[request['idempotencyKey']] = {'ticketId': f'ticket:T-{n}', 'content': {'ticket': f'T-{n}', 'approved': True, 'request': request['arguments']}} return {'timedOut': True} # Applied, but the response never arrived. def read_back(self, key): ticket = self.tickets.get(key) return {'recorded': True, **copy.deepcopy(ticket)} if ticket else {'recorded': False}
# The reviewed binding: its digests are computed from the manifest and tool list a human reviewed.server = LossyTicketServer()binding = {'bindingId': 'mcp:tickets', 'bindingRevision': '1', 'protocol': 'MCP', 'protocolVersion': '2026-07-28', 'manifestDigest': sha256({'bindingId': 'mcp:tickets', 'protocol': 'MCP', 'protocolVersion': '2026-07-28', 'endpointRef': 'endpoint:tickets'}), 'capabilityDigest': sha256(server.tools)}class Log: def __init__(self): self.entries = [] def append(self, entry): self.entries.append(copy.deepcopy(entry))log = Log()adapter = ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', server, log)
# Simulated identity: replace before deployment. Deny by default; each rule names the one session it allows.RUNNER, AGENT = {'actor': 'host:runner', 'kind': 'RULE'}, {'actor': 'agent:triage', 'kind': 'AGENT'}OWNER, WORKER = {'actor': 'human:owner', 'kind': 'HUMAN'}, {'actor': 'host:worker-1', 'kind': 'RULE'}def permits(session, c): kind = c['type'] if kind == 'startRun': return session is RUNNER if kind == 'grant': return session is OWNER if kind == 'admit': return session is AGENT and c['subject'] == AGENT['actor'] and c['action']['capability'] == 'ticket.create' if kind in ('dispatch', 'settle'): return session is WORKER return False # approve, revokeGrant, verify, accept and the rest: never from this host's rules.def authorizer_for(session): def authorize(command, state, now): allowed = permits(session, command) return {'allowed': allowed, 'policy': 'ALLOW' if allowed else 'DENY', 'mandatoryChecksOk': True, 'context': {'actor': session['actor'], 'policyRevision': 'policy:1', 'decisionClass': 'HUMAN' if session['kind'] == 'HUMAN' else 'DETERMINISTIC'}} return authorizecontract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['ticket-reviewed'], 'actions': ['ticket.create'], 'resources': ['protocol:mcp:tickets'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': []}))directory = Path(tempfile.mkdtemp(prefix='aiws-python-protocol-call-'))with SqliteStore(str(directory / 'mission.db'), contract) as store: def as_(session): return Coordinator(store, authorizer_for(session), lambda: '10') def admit(operation_id, attempt_id): return as_(AGENT).apply({'type': 'admit', 'runId': 'r', 'operationId': operation_id, 'attemptId': attempt_id, 'grantId': 'g', 'subject': AGENT['actor'], 'action': {'capability': 'ticket.create', 'resource': 'protocol:mcp:tickets', 'payload': {'title': 'Guard missing on press 4'}, 'preconditions': {}}, 'amount': '10', 'authorizationCheckedAt': '10', 'policy': 'ALLOW', 'mandatoryChecksOk': True}) as_(RUNNER).apply({'type': 'startRun', 'runId': 'r'}) as_(OWNER).apply({'type': 'grant', 'grant': {'id': 'g', 'subject': AGENT['actor'], 'profile': 'finite-v1', 'actions': ['ticket.create'], 'resources': ['protocol:mcp:tickets'], 'notBefore': '0', 'expiresAt': '10000', 'limit': '100', 'canDelegate': False, 'depth': '0'}}) admit('o1', 'a1') state = as_(WORKER).dispatch('a1', adapter) assert state['attempts']['a1']['status'] == 'UNKNOWN' # The tool ran, but the timeout proves nothing. assert state['reserved'] == '10' # UNKNOWN keeps the reservation. state = as_(WORKER).reconcile('a1', adapter) # Read-only: reads the key back, never calls the tool. assert state['operations']['o1']['effect'] == 'CONFIRMED_APPLIED' assert state['spent'] == '2' assert server.calls == 1 # Called exactly once. # The server's `approved: true` is stored as evidence data. It is not an approval, a PASS or an acceptance. assert log.entries[1]['data']['approved'] is True assert state['approvals'] == {} and state['assessments'] == {} # A host that turned it into an approve command would be refused: no rule lets a worker approve. try: as_(WORKER).apply({'type': 'approve', 'approval': {'id': 'ap', 'runId': 'r', 'approver': WORKER['actor'], 'fingerprint': state['operations']['o1']['fingerprint'], 'expiresAt': '1000', 'uses': '1'}}) raise AssertionError('a worker approved') except Exception as error: assert getattr(error, 'code', None) == 'AUTHORITY_DENIED'
# The server changes its tool declaration. The next call is blocked before it is sent. server.tools[0]['inputSchema'] = {'type': 'object', 'required': ['title', 'assignee']} admit('o2', 'a2') state = as_(WORKER).dispatch('a2', adapter) assert state['operations']['o2']['effect'] == 'CONFIRMED_NOT_APPLIED' assert server.calls == 1
# A transport that fails reports UNKNOWN: classification checked on a scripted client, outside the coordinator. class Failing: def list_tools(self): return [{'name': 'create_ticket', 'inputSchema': {'type': 'object', 'required': ['title']}}] def call_tool(self, request): raise ConnectionResetError('connection reset') def read_back(self, key): raise ConnectionResetError('connection reset') probe = ToolCallAdapter('m', binding, 'mcp:tickets-server@3.1.0', Failing(), Log()) assert probe.execute(state['operations']['o1'], state['attempts']['a1'])['effect'] == 'UNKNOWN' assert probe.reconcile(state['operations']['o1'], state['attempts']['a1'])['effect'] == 'UNKNOWN'
assert [e['observation'] for e in log.entries] == ['TIMED_OUT', 'READ_BACK', 'CAPABILITY_CHANGED']for entry in log.entries: print(json.dumps(entry['correlation']))print('PASS: protocol-call')Remote completion as an EXTERNAL_RESPONSE resume
Section titled “Remote completion as an EXTERNAL_RESPONSE resume”When the remote side reports back later, its completion resumes a wait through an EXTERNAL_RESPONSE trigger. The host stored one correlation record per delegated attempt, keyed by the remote task ID, and correlated the wait to the current attempt’s record. An inbound request then passes these steps in order:
- Authenticate the sender before reading the body. The event source comes from the authenticated principal, never from a
sourcefield in the body. - Find the stored record for the remote task. A remote task ID the host never delegated is refused, and a remote ID never becomes a local one.
- Fire the trigger through the coordinator, whose authorizer allows
fireTriggeronly from that principal and allows nothing else to an inbound request.
The SDK then refuses a result for a superseded attempt (WAIT_CORRELATION), a result older than the trigger’s maxAgeMs (EVENT_EXPIRED) and a changed redelivery under the same event ID (EVENT_ID_CONFLICT). An identical redelivery is absorbed by its event ID. The completion resumes the wait and does nothing more: its approved: true approves nothing, verifies nothing and settles no attempt. The operation’s effect still comes from its adapter or a read-only reconcile.
Resume on a correlated remote completion: authenticated inbound request, event-ID idempotency, stale and superseded results refused · Executable local control demonstration; SDK 0.4.0 APIs; simulated peer authentication, scripted clock, no protocol client or real transport
import assert from 'node:assert/strict';import { createHash } from 'node:crypto';import { mkdtempSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import { AiwsError, canonical, parseCommand, parseContract, parseStrict, protocolCorrelation, type ProtocolBindingRef, type ProtocolCorrelation, type Snapshot } from '@aiws/sdk';import { SqliteStore } from '@aiws/sdk/sqlite';import { Coordinator, type Authorizer, type Clock } from '@aiws/sdk/runtime';
/* * Remote completion of the A2A task the host delegated for operation `o1` through the reviewed binding `a2a:reviewer`. * - The host stored one aiws-protocol-correlation/1 record per delegated attempt, keyed by the remote task ID. The * task of attempt a1 was superseded when the host delegated attempt a2, so only a2's completion may resume the run. * - Inbound: the remote agent posts its completion to the host. The host authenticates the sender first and takes the * event source from the authenticated principal, never from the body. * - The completion becomes a fireTrigger on an EXTERNAL_RESPONSE trigger, correlated to the current attempt's record. * The SDK refuses a stale event (EVENT_EXPIRED), a result for any other attempt (WAIT_CORRELATION) and a changed * redelivery (EVENT_ID_CONFLICT); an identical redelivery is absorbed by its event ID. * - The completion's content is data: its `approved: true` approves nothing, verifies nothing and settles no attempt. */const sha256 = (value: unknown): string => createHash('sha256').update(canonical(value)).digest('hex');const binding: ProtocolBindingRef = { bindingId: 'a2a:reviewer', bindingRevision: '1', protocol: 'A2A', protocolVersion: '1.0', manifestDigest: sha256({ bindingId: 'a2a:reviewer', protocol: 'A2A', protocolVersion: '1.0', endpointRef: 'endpoint:reviewer' }), capabilityDigest: sha256({ skills: ['review'] }) };const delegated = (attemptId: string, remoteTaskId: string): ProtocolCorrelation => protocolCorrelation(binding, { workOrderId: 'm', runId: 'r', taskId: null, operationId: 'o1', attemptId, remoteIdentityRef: 'a2a:reviewer-agent@2.0.0', remoteOperationId: remoteTaskId });/** The records the host stored when it delegated each attempt, by remote task ID. A remote ID is never a local one. */const correlations = new Map<string, ProtocolCorrelation>([['a2a-task:7', delegated('a1', 'a2a-task:7')], ['a2a-task:9', delegated('a2', 'a2a-task:9')]]);/** The wait correlation for one delegated attempt: a completion for any other attempt cannot match it. */const completionCorrelation = (record: ProtocolCorrelation): string => `${record.operation.operationId}/${record.operation.attemptId}`;
// Simulated identity: replace before deployment. A deployed host verifies the peer's certificate or signature; here// the transport's verified peer name maps to the one event source the trigger accepts.type Session = { actor: string; kind: 'RULE' | 'SERVICE' };const RUNNER: Session = { actor: 'host:runner', kind: 'RULE' };const peers = new Map<string, Session>([['mtls:reviewer-agent', { actor: 'a2a:reviewer', kind: 'SERVICE' }]]);const authenticate = (peer: string): Session | null => peers.get(peer) ?? null;function permits(session: Session, c: any): boolean { switch (c.type) { case 'startRun': case 'registerTrigger': case 'wait': case 'transition': case 'join': return session === RUNNER; case 'fireTrigger': return session.kind === 'SERVICE' && c.event.source === session.actor; default: return false; // approve, settle, verify, accept and the rest: never from an inbound request. }}const authorizerFor = (session: Session): Authorizer => async (command) => { const allowed = permits(session, command); return { allowed, policy: allowed ? 'ALLOW' : 'DENY', mandatoryChecksOk: true, context: { actor: session.actor, policyRevision: 'policy:1', decisionClass: 'DETERMINISTIC' } };};let nowMs = 20n;const clock: Clock = () => nowMs.toString(); // Scripted: a deployed host injects its trusted UTC clock.const contract = parseContract(canonical({ id: 'c', missionId: 'm', aiwsEdition: '0.4', profile: 'finite-v1', budget: '100', deadline: '10000', criteria: ['review-complete'], actions: ['review.request'], resources: ['protocol:a2a:reviewer'], requiresApproval: false, maxAttempts: '2', maxAuthorizationAgeMs: '10', features: ['triggers'] }));const store = new SqliteStore(join(mkdtempSync(join(tmpdir(), 'aiws-protocol-completion-')), 'mission.db'), contract);const as = (session: Session) => new Coordinator(store, authorizerFor(session), clock);
interface InboundRequest { peer: string; body: string }/** The inbound endpoint: authenticate, find the stored record for the remote task, then fire the trigger. */async function receive(request: InboundRequest): Promise<Snapshot> { const session = authenticate(request.peer); if (session === null) throw new AiwsError('UNAUTHENTICATED'); // Refused before the body is read. const body = parseStrict(request.body) as Record<string, any>; const record = typeof body.taskId === 'string' ? correlations.get(body.taskId) : undefined; if (record === undefined) throw new AiwsError('UNKNOWN_REMOTE_TASK'); const event = { id: body.eventId, source: session.actor, type: 'task.completed', occurredAt: body.occurredAt, data: body.result, depth: '0', correlation: completionCorrelation(record) }; return as(session).apply(parseCommand(canonical({ type: 'fireTrigger', triggerId: 't', runId: record.operation.runId, event })));}const completion = (peer: string, taskId: string, eventId: string, occurredAt: string, result: Record<string, unknown>): InboundRequest => ({ peer, body: JSON.stringify({ taskId, eventId, occurredAt, result, source: 'a2a:reviewer' }) });const refused = (code: string) => (e: any) => e.code === code;try { for (const command of [ { type: 'startRun', runId: 'r' }, { type: 'registerTrigger', trigger: { id: 't', revision: '1', kind: 'EXTERNAL_RESPONSE', source: 'a2a:reviewer', eventType: 'task.completed', contractId: 'c', action: 'RESUME_WAIT', waitId: 'w', enabled: true, notBefore: '0', expiresAt: '10000', maxAgeMs: '100', maxConcurrent: '1', rateLimit: '10', rateWindowMs: '1000', maxDepth: '0' } }, { type: 'wait', runId: 'r', waitId: 'w', correlation: completionCorrelation(correlations.get('a2a-task:9')!), deadline: '5000', kind: 'EXTERNAL' }, { type: 'transition', runId: 'r', to: 'WAITING' }, ]) await as(RUNNER).apply(parseCommand(canonical(command)));
// A sender the host cannot authenticate never reaches the trigger, whatever source its body claims. await assert.rejects(receive(completion('mtls:unknown', 'a2a-task:9', 'e0', '15', { verdict: 'done' })), refused('UNAUTHENTICATED')); // The superseded attempt's late result is refused: its correlation is not the wait's. await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:7', 'e1', '15', { verdict: 'done' })), refused('WAIT_CORRELATION')); // A remote task the host never delegated has no stored record. await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:99', 'e2', '15', { verdict: 'done' })), refused('UNKNOWN_REMOTE_TASK')); // A result older than the trigger's maxAgeMs is stale. nowMs = 300n; await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e3', '150', { verdict: 'done' })), refused('EVENT_EXPIRED'));
// The current attempt's fresh result resumes the wait. const current = completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', { verdict: 'done', approved: true }); let state = await receive(current); assert.equal(state.waits.w.status, 'SATISFIED'); // A redelivery with the same event ID and content is absorbed; a changed one is refused. state = await receive(current); assert.equal(Object.keys(state.receipts).length, 1); await assert.rejects(receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', { verdict: 'rejected' })), refused('EVENT_ID_CONFLICT'));
state = await as(RUNNER).apply(parseCommand(canonical({ type: 'join', runId: 'r', waitIds: ['w'], mode: 'ALL' }))); assert.equal(state.runs.r.state, 'READY'); // The remote `approved: true` stayed data: no approval, no assessment and no settled attempt came from it. assert.equal(Object.keys(state.approvals).length, 0); assert.equal(Object.keys(state.assessments).length, 0); assert.equal(Object.keys(state.attempts).length, 0); console.log('PASS: protocol-completion');} finally { store.close();}use aiws_sdk::runtime::*;use aiws_sdk::sqlite::SqliteStore;use aiws_sdk::*;use serde_json::{json, Value};use std::cell::Cell;use std::collections::BTreeMap;use std::rc::Rc;
// Remote completion of the A2A task the host delegated for operation `o1` through the reviewed binding `a2a:reviewer`.// - The host stored one aiws-protocol-correlation/1 record per delegated attempt, keyed by the remote task ID. The// task of attempt a1 was superseded when the host delegated attempt a2, so only a2's completion may resume the run.// - Inbound: the remote agent posts its completion to the host. The host authenticates the sender first and takes the// event source from the authenticated principal, never from the body.// - The completion becomes a fireTrigger on an EXTERNAL_RESPONSE trigger, correlated to the current attempt's record.// The SDK refuses a stale event (EVENT_EXPIRED), a result for any other attempt (WAIT_CORRELATION) and a changed// redelivery (EVENT_ID_CONFLICT); an identical redelivery is absorbed by its event ID.// - The completion's content is data: its `approved: true` approves nothing, verifies nothing and settles no attempt.fn sha256(value: &Value) -> Result<String> { Ok(digest(value)?.trim_start_matches("sha256:").to_owned())}fn delegated(binding: &ProtocolBindingRef, attempt_id: &str, remote_task_id: &str) -> Result<ProtocolCorrelation> { protocol_correlation( binding.clone(), ProtocolOperationRef { work_order_id: "m".into(), run_id: "r".into(), task_id: None, operation_id: "o1".into(), attempt_id: attempt_id.into(), remote_identity_ref: Some("a2a:reviewer-agent@2.0.0".into()), remote_operation_id: Some(remote_task_id.into()), }, ) .map_err(|code| AiwsError { code })}/// The wait correlation for one delegated attempt: a completion for any other attempt cannot match it.fn completion_correlation(record: &ProtocolCorrelation) -> String { format!("{}/{}", record.operation.operation_id, record.operation.attempt_id)}
// Simulated identity: replace before deployment. A deployed host verifies the peer's certificate or signature; here// the transport's verified peer name maps to the one event source the trigger accepts.struct Session { actor: &'static str, kind: &'static str,}static RUNNER: Session = Session { actor: "host:runner", kind: "RULE" };static REVIEWER: Session = Session { actor: "a2a:reviewer", kind: "SERVICE" };fn authenticate(peer: &str) -> Option<&'static Session> { match peer { "mtls:reviewer-agent" => Some(&REVIEWER), _ => None, }}fn permits(session: &'static Session, c: &Value) -> bool { match c["type"].as_str().unwrap_or_default() { "startRun" | "registerTrigger" | "wait" | "transition" | "join" => std::ptr::eq(session, &RUNNER), "fireTrigger" => session.kind == "SERVICE" && c["event"]["source"] == session.actor, // approve, settle, verify, accept and the rest: never from an inbound request. _ => false, }}/// The session the host authenticated for the command it is about to apply.struct Policy(Rc<Cell<&'static Session>>);impl Authorizer for Policy { fn authorize(&mut self, command: &Command, _: &Snapshot, _: &str) -> Result<Authorization> { let session = self.0.get(); let allowed = permits(session, command.as_value()); Ok(Authorization { allowed, policy: if allowed { "ALLOW" } else { "DENY" }.into(), mandatory_checks_ok: true, context: json!({"actor": session.actor, "policyRevision": "policy:1", "decisionClass": "DETERMINISTIC"}), }) }}/// Scripted: a deployed host injects its trusted UTC clock.struct Scripted(Rc<Cell<u64>>);impl Clock for Scripted { fn now_ms(&self) -> String { self.0.get().to_string() }}struct Host { coordinator: Coordinator<Policy, Scripted>, session: Rc<Cell<&'static Session>>, correlations: BTreeMap<String, ProtocolCorrelation>,}impl Host { fn apply(&mut self, session: &'static Session, raw: Value) -> Result<Snapshot> { self.session.set(session); self.coordinator.apply(&Command::from_value(raw)?, None) } /// The inbound endpoint: authenticate, find the stored record for the remote task, then fire the trigger. fn receive(&mut self, peer: &str, body: &str) -> Result<Snapshot> { // Refused before the body is read. let session = authenticate(peer).ok_or_else(|| error("UNAUTHENTICATED"))?; let body = parse_strict(body)?; let record = body["taskId"].as_str().and_then(|id| self.correlations.get(id)).ok_or_else(|| error("UNKNOWN_REMOTE_TASK"))?; let event = json!({"id": body["eventId"], "source": session.actor, "type": "task.completed", "occurredAt": body["occurredAt"], "data": body["result"], "depth": "0", "correlation": completion_correlation(record)}); let run_id = record.operation.run_id.clone(); self.apply(session, json!({"type": "fireTrigger", "triggerId": "t", "runId": run_id, "event": event})) }}fn completion(task_id: &str, event_id: &str, occurred_at: &str, result: Value) -> String { json!({"taskId": task_id, "eventId": event_id, "occurredAt": occurred_at, "result": result, "source": "a2a:reviewer"}).to_string()}fn refused(code: &str, result: Result<Snapshot>) { assert_eq!(result.err().map(|e| e.code).as_deref(), Some(code));}fn main() -> std::result::Result<(), Box<dyn std::error::Error>> { let binding = ProtocolBindingRef { binding_id: "a2a:reviewer".into(), binding_revision: "1".into(), protocol: "A2A".into(), protocol_version: "1.0".into(), manifest_digest: sha256(&json!({"bindingId": "a2a:reviewer", "protocol": "A2A", "protocolVersion": "1.0", "endpointRef": "endpoint:reviewer"}))?, capability_digest: sha256(&json!({"skills": ["review"]}))?, }; // The records the host stored when it delegated each attempt, by remote task ID. A remote ID is never a local one. let correlations = BTreeMap::from([ ("a2a-task:7".to_owned(), delegated(&binding, "a1", "a2a-task:7")?), ("a2a-task:9".to_owned(), delegated(&binding, "a2", "a2a-task:9")?), ]); let contract = Contract::parse(&json!({"id":"c","missionId":"m","aiwsEdition":"0.4","profile":"finite-v1","budget":"100","deadline":"10000","criteria":["review-complete"],"actions":["review.request"],"resources":["protocol:a2a:reviewer"],"requiresApproval":false,"maxAttempts":"2","maxAuthorizationAgeMs":"10","features":["triggers"]}).to_string())?; let directory = std::env::temp_dir().join(format!( "aiws-protocol-completion-{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_nanos() )); std::fs::create_dir(&directory)?; let store = SqliteStore::open(directory.join("mission.db").to_str().unwrap(), Some(&contract))?; let (session, now_ms) = (Rc::new(Cell::new(&RUNNER)), Rc::new(Cell::new(20))); let wait_correlation = completion_correlation(&correlations["a2a-task:9"]); let mut host = Host { coordinator: Coordinator::new(store, Policy(session.clone()), Scripted(now_ms.clone())), session, correlations }; for raw in [ json!({"type":"startRun","runId":"r"}), json!({"type":"registerTrigger","trigger":{"id":"t","revision":"1","kind":"EXTERNAL_RESPONSE","source":"a2a:reviewer","eventType":"task.completed","contractId":"c","action":"RESUME_WAIT","waitId":"w","enabled":true,"notBefore":"0","expiresAt":"10000","maxAgeMs":"100","maxConcurrent":"1","rateLimit":"10","rateWindowMs":"1000","maxDepth":"0"}}), json!({"type":"wait","runId":"r","waitId":"w","correlation":wait_correlation,"deadline":"5000","kind":"EXTERNAL"}), json!({"type":"transition","runId":"r","to":"WAITING"}), ] { host.apply(&RUNNER, raw)?; }
// A sender the host cannot authenticate never reaches the trigger, whatever source its body claims. refused("UNAUTHENTICATED", host.receive("mtls:unknown", &completion("a2a-task:9", "e0", "15", json!({"verdict": "done"})))); // The superseded attempt's late result is refused: its correlation is not the wait's. refused("WAIT_CORRELATION", host.receive("mtls:reviewer-agent", &completion("a2a-task:7", "e1", "15", json!({"verdict": "done"})))); // A remote task the host never delegated has no stored record. refused("UNKNOWN_REMOTE_TASK", host.receive("mtls:reviewer-agent", &completion("a2a-task:99", "e2", "15", json!({"verdict": "done"})))); // A result older than the trigger's maxAgeMs is stale. now_ms.set(300); refused("EVENT_EXPIRED", host.receive("mtls:reviewer-agent", &completion("a2a-task:9", "e3", "150", json!({"verdict": "done"}))));
// The current attempt's fresh result resumes the wait. let current = completion("a2a-task:9", "e4", "290", json!({"verdict": "done", "approved": true})); let state = host.receive("mtls:reviewer-agent", ¤t)?; assert_eq!(state.as_value()["waits"]["w"]["status"], "SATISFIED"); // A redelivery with the same event ID and content is absorbed; a changed one is refused. let state = host.receive("mtls:reviewer-agent", ¤t)?; assert_eq!(state.as_value()["receipts"].as_object().unwrap().len(), 1); refused("EVENT_ID_CONFLICT", host.receive("mtls:reviewer-agent", &completion("a2a-task:9", "e4", "290", json!({"verdict": "rejected"}))));
let state = host.apply(&RUNNER, json!({"type":"join","runId":"r","waitIds":["w"],"mode":"ALL"}))?; assert_eq!(state.as_value()["runs"]["r"]["state"], "READY"); // The remote `approved: true` stayed data: no approval, no assessment and no settled attempt came from it. for record in ["approvals", "assessments", "attempts"] { assert!(state.as_value()[record].as_object().unwrap().is_empty()); } println!("PASS: protocol-completion"); Ok(())}"""Resume a run on an authenticated, correlated remote completion, and refuse stale and superseded results."""import hashlibimport jsonimport tempfilefrom pathlib import Pathfrom typing import Optionalfrom aiws import protocol_correlationfrom aiws.core import AiwsError, canonical, parse_contract, parse_strictfrom aiws.sqlite import SqliteStorefrom aiws.runtime import Coordinator
# Remote completion of the A2A task the host delegated for operation `o1` through the reviewed binding `a2a:reviewer`.# - The host stored one aiws-protocol-correlation/1 record per delegated attempt, keyed by the remote task ID. The# task of attempt a1 was superseded when the host delegated attempt a2, so only a2's completion may resume the run.# - Inbound: the remote agent posts its completion to the host. The host authenticates the sender first and takes the# event source from the authenticated principal, never from the body.# - The completion becomes a fireTrigger on an EXTERNAL_RESPONSE trigger, correlated to the current attempt's record.# The SDK refuses a stale event (EVENT_EXPIRED), a result for any other attempt (WAIT_CORRELATION) and a changed# redelivery (EVENT_ID_CONFLICT); an identical redelivery is absorbed by its event ID.# - The completion's content is data: its `approved: true` approves nothing, verifies nothing and settles no attempt.def sha256(value) -> str: return hashlib.sha256(canonical(value).encode()).hexdigest()binding = {'bindingId': 'a2a:reviewer', 'bindingRevision': '1', 'protocol': 'A2A', 'protocolVersion': '1.0', 'manifestDigest': sha256({'bindingId': 'a2a:reviewer', 'protocol': 'A2A', 'protocolVersion': '1.0', 'endpointRef': 'endpoint:reviewer'}), 'capabilityDigest': sha256({'skills': ['review']})}def delegated(attempt_id: str, remote_task_id: str) -> dict: return protocol_correlation(binding, {'workOrderId': 'm', 'runId': 'r', 'taskId': None, 'operationId': 'o1', 'attemptId': attempt_id, 'remoteIdentityRef': 'a2a:reviewer-agent@2.0.0', 'remoteOperationId': remote_task_id})# The records the host stored when it delegated each attempt, by remote task ID. A remote ID is never a local one.correlations = {'a2a-task:7': delegated('a1', 'a2a-task:7'), 'a2a-task:9': delegated('a2', 'a2a-task:9')}def completion_correlation(record: dict) -> str: """The wait correlation for one delegated attempt: a completion for any other attempt cannot match it.""" return f"{record['operation']['operationId']}/{record['operation']['attemptId']}"
# Simulated identity: replace before deployment. A deployed host verifies the peer's certificate or signature; here# the transport's verified peer name maps to the one event source the trigger accepts.RUNNER = {'actor': 'host:runner', 'kind': 'RULE'}peers = {'mtls:reviewer-agent': {'actor': 'a2a:reviewer', 'kind': 'SERVICE'}}def authenticate(peer: str) -> Optional[dict]: return peers.get(peer)def permits(session, c): kind = c['type'] if kind in ('startRun', 'registerTrigger', 'wait', 'transition', 'join'): return session is RUNNER if kind == 'fireTrigger': return session['kind'] == 'SERVICE' and c['event']['source'] == session['actor'] return False # approve, settle, verify, accept and the rest: never from an inbound request.def authorizer_for(session): def authorize(command, state, now): allowed = permits(session, command) return {'allowed': allowed, 'policy': 'ALLOW' if allowed else 'DENY', 'mandatoryChecksOk': True, 'context': {'actor': session['actor'], 'policyRevision': 'policy:1', 'decisionClass': 'DETERMINISTIC'}} return authorizenow_ms = 20def clock() -> str: return str(now_ms) # Scripted: a deployed host injects its trusted UTC clock.contract = parse_contract(json.dumps({'id': 'c', 'missionId': 'm', 'aiwsEdition': '0.4', 'profile': 'finite-v1', 'budget': '100', 'deadline': '10000', 'criteria': ['review-complete'], 'actions': ['review.request'], 'resources': ['protocol:a2a:reviewer'], 'requiresApproval': False, 'maxAttempts': '2', 'maxAuthorizationAgeMs': '10', 'features': ['triggers']}))
def completion(peer, task_id, event_id, occurred_at, result): return {'peer': peer, 'body': json.dumps({'taskId': task_id, 'eventId': event_id, 'occurredAt': occurred_at, 'result': result, 'source': 'a2a:reviewer'})}def refused(code, call): try: call() except AiwsError as error: assert error.code == code, error.code return raise AssertionError('accepted; expected ' + code)
directory = Path(tempfile.mkdtemp(prefix='aiws-python-protocol-completion-'))with SqliteStore(str(directory / 'mission.db'), contract) as store: def as_(session): return Coordinator(store, authorizer_for(session), clock) def receive(request): """The inbound endpoint: authenticate, find the stored record for the remote task, then fire the trigger.""" session = authenticate(request['peer']) if session is None: raise AiwsError('UNAUTHENTICATED') # Refused before the body is read. body = parse_strict(request['body']) record = correlations.get(body['taskId']) if isinstance(body.get('taskId'), str) else None if record is None: raise AiwsError('UNKNOWN_REMOTE_TASK') event = {'id': body['eventId'], 'source': session['actor'], 'type': 'task.completed', 'occurredAt': body['occurredAt'], 'data': body['result'], 'depth': '0', 'correlation': completion_correlation(record)} return as_(session).apply({'type': 'fireTrigger', 'triggerId': 't', 'runId': record['operation']['runId'], 'event': event}) for command in [ {'type': 'startRun', 'runId': 'r'}, {'type': 'registerTrigger', 'trigger': {'id': 't', 'revision': '1', 'kind': 'EXTERNAL_RESPONSE', 'source': 'a2a:reviewer', 'eventType': 'task.completed', 'contractId': 'c', 'action': 'RESUME_WAIT', 'waitId': 'w', 'enabled': True, 'notBefore': '0', 'expiresAt': '10000', 'maxAgeMs': '100', 'maxConcurrent': '1', 'rateLimit': '10', 'rateWindowMs': '1000', 'maxDepth': '0'}}, {'type': 'wait', 'runId': 'r', 'waitId': 'w', 'correlation': completion_correlation(correlations['a2a-task:9']), 'deadline': '5000', 'kind': 'EXTERNAL'}, {'type': 'transition', 'runId': 'r', 'to': 'WAITING'}, ]: as_(RUNNER).apply(command)
# A sender the host cannot authenticate never reaches the trigger, whatever source its body claims. refused('UNAUTHENTICATED', lambda: receive(completion('mtls:unknown', 'a2a-task:9', 'e0', '15', {'verdict': 'done'}))) # The superseded attempt's late result is refused: its correlation is not the wait's. refused('WAIT_CORRELATION', lambda: receive(completion('mtls:reviewer-agent', 'a2a-task:7', 'e1', '15', {'verdict': 'done'}))) # A remote task the host never delegated has no stored record. refused('UNKNOWN_REMOTE_TASK', lambda: receive(completion('mtls:reviewer-agent', 'a2a-task:99', 'e2', '15', {'verdict': 'done'}))) # A result older than the trigger's maxAgeMs is stale. now_ms = 300 refused('EVENT_EXPIRED', lambda: receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e3', '150', {'verdict': 'done'})))
# The current attempt's fresh result resumes the wait. current = completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', {'verdict': 'done', 'approved': True}) state = receive(current) assert state['waits']['w']['status'] == 'SATISFIED' # A redelivery with the same event ID and content is absorbed; a changed one is refused. state = receive(current) assert len(state['receipts']) == 1 refused('EVENT_ID_CONFLICT', lambda: receive(completion('mtls:reviewer-agent', 'a2a-task:9', 'e4', '290', {'verdict': 'rejected'})))
state = as_(RUNNER).apply({'type': 'join', 'runId': 'r', 'waitIds': ['w'], 'mode': 'ALL'}) assert state['runs']['r']['state'] == 'READY' # The remote `approved: true` stayed data: no approval, no assessment and no settled attempt came from it. assert state['approvals'] == {} and state['assessments'] == {} and state['attempts'] == {}print('PASS: protocol-completion')What the recipes leave out
Section titled “What the recipes leave out”Peer authentication, the evidence store and the protocol servers are simulated, and each is marked “replace before deployment”. Credential and endpoint handling (PROTOCOL-BINDINGS §10), cancellation and a real protocol transport are out of scope, so the recipes imply nothing about them. The agent skill aiws-protocol-wiring teaches these recipes; see Coding agents.