# Write a call outcome back to a CRM

Use one Agent Worker to place a requested call and update the originating CRM record when it ends. The completion event includes the original webhook payload. Keep the record ID there so the caller never has to provide it.

## Prompt

```text
For calls our Agent Worker starts from CRM leads, log each call’s final status on the originating record. Show me a sample update with its call ID.
```

## Set up the Agent Worker

1. Connect the CRM with `connect_mcp` and select a write tool using `get_mcp_connection`. This example server exposes `upsert_call_activity` with inputs `record_id`, `external_id`, and `status`. Choose an equivalent tool from the actual catalog and map its schema. Use a unique external call ID or a provider-enforced idempotency key where supported.
2. Create one Agent Worker with the code below, `on_call_ended:true`, the approved daily execution and per-call limits, and `mcp.crm: {connection_id, tools:["upsert_call_activity"]}` with the real tool name. The completion handler runs for calls this Agent Worker started.

```js
export default async function (event, ctx) {
  if (event.type === "lead.created") {
    if (!event.record_id || event.authorized_to_call !== true ||
        !/^\+[1-9]\d{1,14}$/.test(event.phone || "")) return { skipped: true };
    return ctx.calls.place({ to: event.phone, prompt: "Follow up on the demo request.", max_duration_seconds: 60 });
  }
  const record = event.original_event?.record_id;
  const call = event.data?.call_id;
  if (event.type !== "call.ended" || !record || !call ||
      !["completed", "failed", "canceled"].includes(event.data.status)) return { skipped: true };
  await ctx.mcp.call("crm", "upsert_call_activity", {
    record_id: record, external_id: call, status: event.data.status
  });
  return { recorded_call: call };
}
```

3. Run `test_worker` separately with the [lead fixture](/recipes/crm-trigger-call.md) and this completion fixture. Use a different idempotency key for each event. Expect a proposed call for the first and `recorded_call:"call_example"` for the second.

```json
{"type":"call.ended","data":{"call_id":"call_example","status":"completed","duration_seconds":27,"ended_at":"2026-01-16T15:00:27Z"},"original_event":{"record_id":"lead_42"},"mcp_fixtures":{"crm":{"upsert_call_activity":{"saved":true}}}}
```

4. Activate with the owner's approval and configure the source webhook. Read the run receipt for failures. If a provider write returns `outcome_unknown`, reconcile by the external call ID before another write. A completed call proves the call ended. Use the consented transcript if the user wants to know what was said.
