# Google ADK integration

> Last updated: 2026-12-01.
> For the complete documentation index, see [llms.txt](https://docs.temporal.io/llms.txt).
> Any documentation page is available as raw Markdown by appending `.md` to its URL.
> For related questions, query `https://docs.temporal.io/api/retrieve?q=<question>&jtb=<job-to-be-done>&src=md-page&agent=<your-name>` (no auth; returns JSON `{content, source_url, page_url}`, with `source_url` pointing to Markdown for docs pages). Don't include personal data or credentials.
> If this page is wrong or missing something you needed, or Temporal behaves differently from what it says, report it with `https://docs.temporal.io/api/feedback?title=<summary>&message=<what-happened>&category=documentation&page_url=/develop/go/integrations/google-adk&src=md-page&agent=<your-name>` (use `category=product` when the product, not the page, is wrong). Report only a specific problem you hit, send it once, and don't include personal data or credentials.

> Run Google ADK agents with durable execution using the Temporal Go SDK and the standalone googleadk module for model calls and tools.

Temporal's integration with [Google ADK](https://google.github.io/adk-docs/) (`adk-go`) gives your agents
[Durable Execution](/durable-execution): the agent's orchestration loop runs inside a Temporal Workflow, each
LLM call becomes a durable Temporal Activity, and any tool that does I/O runs as an Activity too — so every step is
retried, timed out, recorded in Workflow history, and replayable after crashes or restarts.

You keep building agents the native ADK way — `llmagent.New(...)` with a `model.LLM`, `tool.Tool`s / `tool.Toolset`s and
`SubAgents`, wrapped in `runner.New(...)` and driven by `r.Run(...)`. You change two things:

1. Use `googleadk.NewModel("<model-name>")` as your agent's `Model`. It is a `model.LLM` whose calls dispatch to the
   `InvokeModel` Activity; the real model is reconstructed **worker-side**, never in the Workflow.
2. Pass `googleadk.NewContext(workflowCtx)` to `r.Run`, which installs Temporal-deterministic time, UUID, and
   task-fan-out providers so the agent loop replays deterministically.

Tools run **in-workflow by default** (the idiomatic Temporal model: the Workflow Definition is deterministic, and anything touching
the network, clock, or disk goes through an Activity). Opt a tool into an Activity with `googleadk.ActivityAsTool`, or
use `googleadk.NewMCPToolset` for MCP.

Code snippets in this guide are taken from the
[Google ADK plugin samples](https://github.com/temporalio/samples-go/tree/main/googleadk). Refer to the samples for the
complete, runnable code.

## Prerequisites

- This guide assumes you are already familiar with Google ADK. If you aren't, refer to the
  [Google ADK documentation](https://google.github.io/adk-docs/) for more details.
- If you are new to Temporal, read [Understanding Temporal](/evaluate/understanding-temporal) or take the
  [Temporal 101](https://learn.temporal.io/courses/temporal_101/) course.
- Set up your local development environment by following the
  [Set up your local development environment](/develop/go/set-up-your-local-go) guide. Leave the Temporal development
  server running if you want to test your code locally.
- Provide model credentials **worker-side** — for Gemini, set `GEMINI_API_KEY` (or `GOOGLE_API_KEY`) in the worker's
  environment. Credentials are captured in the worker's `ModelFactory` and never cross the Activity boundary into the
  Workflow.

## Install the plugin

Install the standalone [`go.temporal.io/googleadk`](https://pkg.go.dev/go.temporal.io/googleadk) module:

```bash
go get go.temporal.io/googleadk@latest
```

```go
import "go.temporal.io/googleadk"
```

The module is versioned separately from the Temporal Go SDK. Its source and releases are maintained in
[`temporalio/ai-integrations`](https://github.com/temporalio/ai-integrations/tree/main/go/googleadk). It requires Go
1.26.10 or later and ADK v2.6.0 or later.

### Upgrade the integration

Before deploying a new ADK or `googleadk` version, let affected open runs finish or keep them on their existing Workers
with [Worker Versioning](/production-deployment/worker-deployments/worker-versioning). ADK's agent loop runs in your
Workflow, so treat upgrades to either package as Workflow Definition changes.

Upgrading `googleadk` to v1.0.0 affects runs that used `NewMCPToolset` directly in an agent's `Toolsets` or made a model
call that the new A2A validation rejects. If the Workflow returns the `r.Run` error, as the samples on this page do,
the run closes as `Failed`. A rollback does not reopen it.

Runs with pending or answered tool confirmations or long-running tool calls also get new identifiers across an upgrade
or rollback. An approval or answer sent with an old identifier is dropped without an error. An answered confirmation
that scheduled a Workflow command can fail replay.

Do not let Workers on different plugin versions poll the same Task Queue while affected runs can exist, including runs
started during rollout. This also applies to agents or runner plugins with tool-error callbacks, or after-tool callbacks
that treat errors differently from results. Follow the
[README's upgrade steps](https://github.com/temporalio/ai-integrations/blob/go/googleadk/v1.0.0/go/googleadk/README.md#L268-L311)
for rollout and recovery.

## Run an agent with Durable Execution

An agent has two halves: the **worker** registers the real model behind the `InvokeModel` Activity, and the **workflow**
builds a vanilla ADK agent and drives it.

### Configure the Worker

Configure the Worker with the integration's plugin, which registers the model, MCP, and A2A Activities at Worker start
(and closes any cached MCP toolsets at Worker stop). The real Gemini model lives in the plugin's config, behind the Activity
boundary; the API key is read worker-side. Disable the model SDK's own retries so Temporal's `RetryPolicy` is the
single source of truth.

Create one plugin per Worker and register it in `worker.Options.Plugins`. Do not put it in `client.Options.Plugins`,
which passes it to every Worker created from that Client. If two Workers share a plugin, MCP calls on one fail after
the other stops. A Worker that receives the plugin through both its Client and its own options panics at startup.

<!--SNIPSTART googleadk-hello-worker-->
[googleadk/worker/main.go](https://github.com/temporalio/samples-go/blob/main/googleadk/worker/main.go)
```go
// The plugin registers the integration's Activities on the worker (and closes
// any cached MCP toolsets at worker stop). The real Gemini model lives in the
// factory, behind the Activity boundary; the API key is read worker-side from
// the env and never crosses into the workflow. Disable the model SDK's own
// retries so Temporal's RetryPolicy is the single source of truth.
adkPlugin, err := googleadk.NewPlugin(googleadk.Config{
	Models: map[string]googleadk.ModelFactory{
		adk.ModelName: func(ctx context.Context, name string) (model.LLM, error) {
			// nil config reads GEMINI_API_KEY / GOOGLE_API_KEY from the env.
			return gemini.NewModel(ctx, name, nil)
		},
	},
})
if err != nil {
	log.Fatalln("Unable to build googleadk plugin", err)
}

w := worker.New(c, adk.TaskQueue, worker.Options{
	Plugins: []worker.Plugin{adkPlugin},
})

w.RegisterWorkflow(adk.AgentWorkflow)
// Register GetWeather under the tool name the ActivityAsTool dispatches, so the
// agent's get_weather call resolves to this activity.
w.RegisterActivityWithOptions(adk.GetWeather, activity.RegisterOptions{Name: adk.WeatherToolName})

if err := w.Run(worker.InterruptCh()); err != nil {
	log.Fatalln("Unable to start worker", err)
}
```
<!--SNIPEND-->

`Config.Models` is optional for providers ADK's registry already knows (for example, `gemini-*`): when a model name is
absent, `InvokeModel` falls back to `model.NewLLM`. Supply a factory to inject credentials, disable the model SDK's own
retries, or override the default.

### Define the Workflow

Build the agent the ordinary ADK way, using `googleadk.NewModel` for the model and passing `googleadk.NewContext(ctx)`
to `r.Run`. The `get_weather` tool is an ordinary Temporal Activity exposed to the agent with `googleadk.ActivityAsTool`.

<!--SNIPSTART googleadk-hello-workflow-->
[googleadk/workflow.go](https://github.com/temporalio/samples-go/blob/main/googleadk/workflow.go)
```go
func AgentWorkflow(ctx workflow.Context, question string) (string, error) {
	weatherTool, err := googleadk.ActivityAsTool(GetWeather, googleadk.ActivityToolOptions{
		Name:        WeatherToolName,
		Description: "Get the current weather for a city.",
	})
	if err != nil {
		return "", err
	}

	// Build the agent the ordinary ADK way. NewModel is a model.LLM that carries
	// only the model name in-workflow; the real Gemini client lives worker-side.
	root, err := llmagent.New(llmagent.Config{
		Name:        "assistant",
		Description: "a helpful weather assistant",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "Answer the user's question. Use the get_weather tool when asked about the weather.",
		Tools:       []tool.Tool{weatherTool},
	})
	if err != nil {
		return "", err
	}

	r, err := runner.New(runner.Config{
		AppName:           "weather",
		Agent:             root,
		SessionService:    session.InMemoryService(),
		AutoCreateSession: true,
	})
	if err != nil {
		return "", err
	}

	// NewContext bridges the workflow.Context into the context ADK reads its
	// determinism/executor seams from. Pass it straight to Run.
	adkCtx := googleadk.NewContext(ctx)
	msg := genai.NewContentFromText(question, genai.RoleUser)

	var answer string
	for ev, err := range r.Run(adkCtx, "user-1", "session-1", msg, agent.RunConfig{}) {
		if err != nil {
			return "", err
		}
		if ev != nil && ev.Content != nil {
			for _, p := range ev.Content.Parts {
				if p != nil && p.Text != "" {
					answer = p.Text
				}
			}
		}
	}
	return answer, nil
}
```
<!--SNIPEND-->

The tool itself is an ordinary Temporal Activity — register it on the worker as usual, and expose it to the agent with
`ActivityAsTool` (its parameter schema is inferred from the argument type):

<!--SNIPSTART googleadk-hello-tool-->
[googleadk/workflow.go](https://github.com/temporalio/samples-go/blob/main/googleadk/workflow.go)
```go
func GetWeather(ctx context.Context, in GetWeatherInput) (GetWeatherOutput, error) {
	return GetWeatherOutput{City: in.City, Conditions: "sunny, 72°F"}, nil
}
```
<!--SNIPEND-->

### Start the Workflow

Start the Workflow like any other and read its result:

<!--SNIPSTART googleadk-hello-starter-->
[googleadk/starter/main.go](https://github.com/temporalio/samples-go/blob/main/googleadk/starter/main.go)
```go
question := "What's the weather in San Francisco?"
we, err := c.ExecuteWorkflow(context.Background(), workflowOptions, adk.AgentWorkflow, question)
if err != nil {
	log.Fatalln("Unable to execute workflow", err)
}

log.Println("Started workflow", "WorkflowID", we.GetID(), "RunID", we.GetRunID())

// Synchronously wait for the workflow completion.
var answer string
if err := we.Get(context.Background(), &answer); err != nil {
	log.Fatalln("Unable to get workflow result", err)
}
log.Println("Agent answer:", answer)
```
<!--SNIPEND-->

## Tools

- **Function tools run in-workflow by default.** Ordinary `functiontool.New(...)` tools run on Temporal's deterministic
  dispatcher inside the Workflow — no Activity overhead — and their session-state mutations propagate normally. Their
  code must be deterministic and replay-safe: no direct network, clock, randomness, or goroutines.
- **Opt a tool into an Activity when it does I/O.** `googleadk.ActivityAsTool(myActivity, ...)` exposes an existing
  `func(context.Context, TArgs) (TResults, error)` Temporal Activity to the agent as a tool (shown in the Hello World
  Workflow above); its call dispatches the Activity, so it is retried, timed out, and visible in the UI.
- **MCP, statelessly.** `googleadk.NewMCPToolset(...)` is a workflow-side proxy that lists remote tools via the
  `ListMcpTools` Activity and executes calls via `CallMcpTool`. The live, stateful `mcptoolset.New(...)` runs worker-side
  (registered in `Config.MCPToolsets`), never in the Workflow.

## Multi-agent systems

Build a coordinator agent with specialist `SubAgents`; ADK wires the parent/child relationship and exposes the built-in
`transfer_to_agent` tool automatically. The entire tree — including the transfer hop — runs in the Workflow; only the
model calls and any Activity-backed tools leave it.

<!--SNIPSTART googleadk-multiagent-workflow-->
[googleadk/multiagent/workflow.go](https://github.com/temporalio/samples-go/blob/main/googleadk/multiagent/workflow.go)
```go
func MultiAgentWorkflow(ctx workflow.Context, question string) (string, error) {
	weatherTool, err := googleadk.ActivityAsTool(GetWeather, googleadk.ActivityToolOptions{
		Name:        WeatherToolName,
		Description: "Get the current weather for a city.",
	})
	if err != nil {
		return "", err
	}

	// The weather specialist owns the get_weather tool.
	weather, err := llmagent.New(llmagent.Config{
		Name:        "weather",
		Description: "answers questions about the current weather in a city",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "You are a weather specialist. Use the get_weather tool to answer weather questions.",
		Tools:       []tool.Tool{weatherTool},
	})
	if err != nil {
		return "", err
	}

	// The jokes specialist just tells jokes.
	jokes, err := llmagent.New(llmagent.Config{
		Name:        "jokes",
		Description: "tells a light-hearted joke",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "You are a comedian. Respond with a short, friendly joke.",
	})
	if err != nil {
		return "", err
	}

	// The coordinator delegates to whichever specialist fits the question. ADK
	// wires the parent/child relationship from SubAgents and exposes the built-in
	// transfer_to_agent tool automatically.
	coordinator, err := llmagent.New(llmagent.Config{
		Name:        "coordinator",
		Description: "routes the user's request to the right specialist",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "You are a router. Delegate weather questions to the weather agent " +
			"and requests for a joke to the jokes agent. Do not answer directly.",
		SubAgents: []agent.Agent{weather, jokes},
	})
	if err != nil {
		return "", err
	}

	r, err := runner.New(runner.Config{
		AppName:           "multiagent",
		Agent:             coordinator,
		SessionService:    session.InMemoryService(),
		AutoCreateSession: true,
	})
	if err != nil {
		return "", err
	}

	adkCtx := googleadk.NewContext(ctx)
	msg := genai.NewContentFromText(question, genai.RoleUser)

	var answer string
	for ev, err := range r.Run(adkCtx, "user-1", "session-1", msg, agent.RunConfig{}) {
		if err != nil {
			return "", err
		}
		if ev == nil || ev.Content == nil {
			continue
		}
		// Keep the last non-empty text produced by any agent in the tree; after a
		// transfer_to_agent hop this is the specialist's answer.
		for _, p := range ev.Content.Parts {
			if p != nil && p.Text != "" {
				answer = p.Text
			}
		}
	}
	return answer, nil
}
```
<!--SNIPEND-->

## Human-in-the-loop tool confirmation

A sensitive tool calls ADK's `ctx.RequestConfirmation(hint, payload)`, which ends the turn with an
`adk_request_confirmation` function call. The Workflow detects requests with `googleadk.PendingConfirmations` and
waits for a decision on every pending request before resuming the agent once with
`googleadk.ConfirmationResponse(decisions...)`. ADK emits each request only once, so the Workflow keeps pending
requests until every one has a decision. The wait survives Worker restarts and ends if the Workflow is canceled.

In this sample, `PendingConfirmationsQuery` is `"pending-confirmations"`. Query it to get each pending request's
`FunctionCallID`, tool arguments, and hint. Send each `googleadk.ConfirmationDecision` through the
`googleadk.ConfirmationSignalName` Signal with that ID and `Confirmed: true` or `false`. Every decision requires an
ID, even when only one request remains. The Workflow drops malformed decisions and decisions with missing, unknown,
or already answered IDs with a warning. `Result.Approved` is true only if at least one decision was accepted and all
accepted decisions were approvals.

The [full sample](https://github.com/temporalio/samples-go/tree/main/googleadk/humanintheloop) includes the imports,
constants, tool, result type, and a starter that queries the pending requests and sends decisions by ID.

<!--SNIPSTART googleadk-hitl-workflow-->
[googleadk/humanintheloop/workflow.go](https://github.com/temporalio/samples-go/blob/main/googleadk/humanintheloop/workflow.go)
```go
func ApprovalWorkflow(ctx workflow.Context, request string) (Result, error) {
	delTool, err := functiontool.New[DeleteArgs, map[string]any](
		functiontool.Config{
			Name:        DeleteToolName,
			Description: "Delete a named resource. Requires human confirmation before it runs.",
		},
		deleteResource,
	)
	if err != nil {
		return Result{}, err
	}

	root, err := llmagent.New(llmagent.Config{
		Name:        "assistant",
		Description: "an assistant that can delete resources with human approval",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "Use the delete_resource tool when the user asks to delete something.",
		Tools:       []tool.Tool{delTool},
	})
	if err != nil {
		return Result{}, err
	}

	r, err := runner.New(runner.Config{
		AppName:           "hitl",
		Agent:             root,
		SessionService:    session.InMemoryService(),
		AutoCreateSession: true,
	})
	if err != nil {
		return Result{}, err
	}

	adkCtx := googleadk.NewContext(ctx)
	msg := genai.NewContentFromText(request, genai.RoleUser)

	var res Result
	var waiting []googleadk.PendingConfirmation
	if err := workflow.SetQueryHandler(ctx, PendingConfirmationsQuery, func() ([]googleadk.PendingConfirmation, error) {
		return waiting, nil
	}); err != nil {
		return Result{}, err
	}
	var denied bool
	decisions := workflow.GetSignalChannel(ctx, googleadk.ConfirmationSignalName)
	// Run each pass over the same session, then answer all its confirmations
	// before letting the model take another step.
	for {
		var events []*session.Event
		for ev, err := range r.Run(adkCtx, "user-1", "session-1", msg, agent.RunConfig{}) {
			if err != nil {
				return Result{}, err
			}
			if ev == nil {
				continue
			}
			events = append(events, ev)
			if ev.Content != nil {
				for _, p := range ev.Content.Parts {
					if p != nil && p.Text != "" {
						res.Answer = p.Text
					}
				}
			}
		}

		waiting = googleadk.PendingConfirmations(events)
		if len(waiting) == 0 {
			// The agent finished without (further) confirmations needed.
			return res, nil
		}

		// Durably wait for a decision on every pending confirmation. The workflow
		// can wait across worker restarts without losing requests or decisions.
		//
		// Every decision must include its FunctionCallID. Query
		// PendingConfirmationsQuery for the IDs, tool arguments, and hints.
		var batch []googleadk.ConfirmationDecision
		for len(waiting) > 0 {
			// Receive raw JSON so a failed decode cannot leave fields behind
			// when the SDK reads the next signal into the same destination.
			var raw json.RawMessage
			if err := workflow.Await(ctx, func() bool { return decisions.Len() > 0 }); err != nil {
				return Result{}, err
			}
			decisions.ReceiveAsync(&raw)
			var decision googleadk.ConfirmationDecision
			// Decoding into this string/bool struct is deterministic.
			err := json.Unmarshal(raw, &decision) //workflowcheck:ignore
			if err != nil {
				workflow.GetLogger(ctx).Warn("Ignoring malformed confirmation", "Error", err)
				continue
			}
			if decision.FunctionCallID == "" {
				workflow.GetLogger(ctx).Warn("Ignoring confirmation without an ID")
				continue
			}
			i := slices.IndexFunc(waiting, func(p googleadk.PendingConfirmation) bool {
				return p.FunctionCallID == decision.FunctionCallID
			})
			if i < 0 {
				workflow.GetLogger(ctx).Warn("Ignoring confirmation for an unknown or already decided request", "FunctionCallID", decision.FunctionCallID)
				continue
			}
			waiting = slices.Delete(waiting, i, i+1)
			batch = append(batch, decision)
			denied = denied || !decision.Confirmed
			res.Approved = !denied
		}

		// Resume once with all decisions. ADK executes or blocks each original
		// tool call before the model takes another step.
		msg = googleadk.ConfirmationResponse(batch...)
	}
}
```
<!--SNIPEND-->

## Continue-as-new for long conversations

A conversation's history lives in the ADK session. To keep a Workflow's history bounded, snapshot the session with
`googleadk.ExportSession` and [continue-as-new](/develop/go/workflows/continue-as-new); rebuild it on the next run with
`googleadk.ImportSession`. `SessionSnapshot` is JSON-serializable (session-scoped state plus the full event history), so
every value in session state and every tool result must be JSON-encodable.

<!--SNIPSTART googleadk-chat-workflow-->
[googleadk/chat/workflow.go](https://github.com/temporalio/samples-go/blob/main/googleadk/chat/workflow.go)
```go
func ChatWorkflow(ctx workflow.Context, in ChatInput) error {
	// A fresh in-memory session service, kept in a local so we can Export it later.
	svc := session.InMemoryService()

	adkCtx := googleadk.NewContext(ctx)

	// Resume a prior conversation if this run was continued-as-new.
	if in.Snapshot != nil {
		if _, err := googleadk.ImportSession(adkCtx, svc, in.Snapshot); err != nil {
			return err
		}
	}

	root, err := llmagent.New(llmagent.Config{
		Name:        "assistant",
		Description: "a friendly conversational assistant",
		Model:       googleadk.NewModel(ModelName),
		Instruction: "You are a helpful assistant. Answer the user, using the conversation history for context.",
	})
	if err != nil {
		return err
	}

	r, err := runner.New(runner.Config{
		AppName:           AppName,
		Agent:             root,
		SessionService:    svc,
		AutoCreateSession: true,
	})
	if err != nil {
		return err
	}

	turns := 0
	// One agent turn runs at a time: serialize concurrent Updates so they can't
	// interleave on the shared ADK session.
	busy := false

	err = workflow.SetUpdateHandlerWithOptions(
		ctx,
		SendMessageUpdateName,
		func(ctx workflow.Context, text string) (string, error) {
			if err := workflow.Await(ctx, func() bool { return !busy }); err != nil {
				return "", err
			}
			busy = true
			defer func() { busy = false }()

			// Build the ADK context from this Update handler's own workflow.Context so
			// the model Activity is scheduled on the handler's coroutine.
			turnCtx := googleadk.NewContext(ctx)
			var answer string
			msg := genai.NewContentFromText(text, genai.RoleUser)
			for ev, err := range r.Run(turnCtx, UserID, SessionID, msg, agent.RunConfig{}) {
				if err != nil {
					return "", err
				}
				if ev == nil || ev.Content == nil {
					continue
				}
				for _, p := range ev.Content.Parts {
					if p != nil && p.Text != "" {
						answer = p.Text
					}
				}
			}
			turns++
			return answer, nil
		},
		workflow.UpdateHandlerOptions{
			Validator: func(ctx workflow.Context, text string) error {
				if text == "" {
					return fmt.Errorf("message must not be empty")
				}
				return nil
			},
		},
	)
	if err != nil {
		return err
	}

	// Serve messages until Temporal suggests continue-as-new (history getting large)
	// or the demo turn cap is reached.
	if err := workflow.Await(ctx, func() bool {
		return workflow.GetInfo(ctx).GetContinueAsNewSuggested() || (in.MaxTurns > 0 && turns >= in.MaxTurns)
	}); err != nil {
		return err
	}

	// Let any in-flight Update finish so its turn is captured in the snapshot.
	if err := workflow.Await(ctx, func() bool { return workflow.AllHandlersFinished(ctx) }); err != nil {
		return err
	}

	snap, err := googleadk.ExportSession(adkCtx, svc, AppName, UserID, SessionID)
	if err != nil {
		return err
	}
	return workflow.NewContinueAsNewError(ctx, ChatWorkflow, ChatInput{
		Snapshot: snap,
		MaxTurns: in.MaxTurns,
	})
}
```
<!--SNIPEND-->

## Streaming

`googleadk.NewModel(name, googleadk.WithStreaming(topic, 0))` drives the model in streaming mode: the `InvokeModel`
Activity calls the model with `stream=true`, heartbeats, and publishes each chunk to a per-run
[`workflowstreams`](https://pkg.go.dev/go.temporal.io/sdk/contrib/workflowstreams) topic for external (UI) consumers,
then returns the aggregated final response into the Workflow so replay stays deterministic.

Streaming is experimental: it builds on `workflowstreams`, a v0 module, and `WithStreaming` and `StreamServer` may
change in a 1.x release.

Call `googleadk.StreamServer(ctx)` once near the top of the Workflow that drives `r.Run`, and set
`agent.RunConfig{StreamingMode: agent.StreamingModeSSE}`:

```go
func StreamingAgentWorkflow(ctx workflow.Context, q string) (string, error) {
	if err := googleadk.StreamServer(ctx); err != nil { // required when streaming
		return "", err
	}
	topic := "run-" + workflow.GetInfo(ctx).WorkflowExecution.ID
	root, _ := llmagent.New(llmagent.Config{
		Model: googleadk.NewModel("gemini-2.0-flash", googleadk.WithStreaming(topic, 0)),
		// ...
	})
	// ... build the runner, set agent.RunConfig{StreamingMode: agent.StreamingModeSSE}, and drive r.Run
}
```

External consumers read chunks with `workflowstreams.NewClient(c, workflowID, ...).Subscribe(...)`. The bidirectional
`RunLive` path (hard-coded goroutines/channels) is **not** supported.

## Error handling

The plugin reports failures as Temporal `ApplicationError`s. Use these Go constants to check `ApplicationError.Type()`:

| Go constant | Type string | Failure |
| --- | --- | --- |
| `googleadk.ErrorTypeModel` | `"googleadk.ModelError"` | Model call |
| `googleadk.ErrorTypeMCP` | `"googleadk.McpError"` | MCP list or call |
| `googleadk.ErrorTypeA2A` | `"googleadk.A2AError"` | A2A card fetch, message, or cancellation |
| `googleadk.ErrorTypeTool` | `"googleadk.ToolError"` | MCP tool misuse of its read-only Activity context |
| `googleadk.ErrorTypeStream` | `"googleadk.StreamError"` | Streamed model chunks could not all be published |

`ErrorTypeTool` covers attempts to write session state, search memory, or request a confirmation without a function
call ID. An `ActivityAsTool` Activity fails with the error your Activity returned.

The plugin treats an MCP error as the tool's own error when it wraps no other error and isn't an `ApplicationError`.
`CallMcpTool` succeeds without a retry, and ADK, its tool-error callbacks, and the model receive an error with only
the tool's message. The original Go type and identity don't cross the Activity boundary: `errors.Is` and `errors.As`
can't match the original error, and `googleadk.IsNonRetryable` can't classify it. A wrapped MCP request error instead fails the Activity with a
retryable `ErrorTypeMCP` error. To request a retry, wrap the cause with `%w` or return a retryable
`temporal.ApplicationError`.

For plugin `ApplicationError`s, classify retryability with `googleadk.IsNonRetryable(err)` rather than matching error
messages. For model calls, the upstream HTTP status drives retryability (`408`/`409`/`429`/`5xx` are retryable;
other `4xx` are not).

A2A transport failures follow the same status rule with the plugin's default clients. To add credentials or other client
options while keeping those clients, set `Config.A2AClientFactory` to `googleadk.NewA2AClientFactory(opts...)`.
Other factories use their own HTTP clients, whose retryability depends on how a2a-go reports the error rather than on
the status alone. An A2A error returned by the remote agent is not retried, regardless of its status.

On ADK v2.6.0 to v2.7.1, a remote A2A call that fails for good becomes an event with an `ErrorMessage`, and `r.Run` returns no error.
Inspect those events: `IsNonRetryable(err)` cannot see the failure. Sequential and loop agents continue after it.
From ADK v2.8.0, the remote agent returns the error and the run ends there. On every release, an `agenttool` around
the remote agent passes the error to the model as a failed tool call instead.

> **💡 Tip:**
>
> Disable your model client's own retries in the `ModelFactory`. `InvokeModel` already runs under Temporal's
> `RetryPolicy`; leaving the model SDK's retries on retries a transient failure twice over. Let Temporal own retries.
>

## Composing with other plugins

The integration's plugin only registers its Activities and closes cached MCP toolsets — it uses the default JSON data
converter and ships no client/worker interceptor — so it composes with interceptor- or converter-based plugins (for example
[`sdk-go/contrib/opentelemetry`](https://pkg.go.dev/go.temporal.io/sdk/contrib/opentelemetry)) without conflict. ADK
emits its own OpenTelemetry telemetry from Workflow code. Without the plugin's replay-safe provider wrappers, ADK
emits that telemetry again on every replay, even with a Temporal tracing interceptor. Install the wrappers before
creating the Worker, as shown in the [README's telemetry setup](https://github.com/temporalio/ai-integrations/blob/go/googleadk/v1.0.0/go/googleadk/README.md#telemetry-and-replay).

## Testing without a live LLM

The plugin ships test helpers so you can unit-test agent Workflows with no network: `FakeModel` (with `TextResponse` /
`FunctionCallResponse` builders) and `FakeMCPServer`. Register them through the same `googleadk.Config` your production
worker uses — via `googleadk.NewActivities` and `Register` rather than the plugin, since the test environments construct
no real Worker and therefore run no plugins.

## Supported and not-yet-supported

- **Supported:** single- and multi-agent (`SubAgents`) trees, in-workflow function tools, `ActivityAsTool`, stateless
  MCP, remote A2A agents built with the plugin's providers, Gemini built-in tools (executed server-side inside
  `InvokeModel`), human-in-the-loop tool confirmation, continue-as-new session-state carry, the in-memory session
  service, and SSE streaming (experimental).
  Build remote A2A agents with `remoteagent.NewA2A` from `google.golang.org/adk/v2/agent/remoteagent/v2`, setting
  `AgentCardProvider` to `googleadk.NewA2AAgentCardProvider(cardURL, activityOptions)` and `ClientProvider` to
  `googleadk.NewA2AClientProvider(activityOptions)`. A static `AgentCard` can replace the card provider.
  Both providers take `workflow.ActivityOptions`. `StartToCloseTimeout` defaults to one minute, a nil `RetryPolicy`
  lets Temporal retry without limit, and `HeartbeatTimeout` defaults to 10 seconds (a negative value disables it).
  Set `StartToCloseTimeout` longer than the remote agent takes to answer: a timed-out send is retried and starts
  another remote task. Cancellation uses a single five-second attempt.

  Validate the agent tree when building the runner. `NewRunnerPlugin(root)` returns `(*plugin.Plugin, error)`:

  ```go
  runnerPlugin, err := googleadk.NewRunnerPlugin(root)
  if err != nil {
      return "", err
  }
  r, err := runner.New(runner.Config{
      AppName:           "weather",
      Agent:             root,
      SessionService:    session.InMemoryService(),
      AutoCreateSession: true,
      PluginConfig: runner.PluginConfig{
          Plugins: []*plugin.Plugin{runnerPlugin},
      },
  })
  if err != nil {
      return "", err
  }
  ```

  Here `plugin` is `google.golang.org/adk/v2/plugin`. Use `r` to run the agent as in the earlier examples. See the
  [README's remote A2A setup](https://github.com/temporalio/ai-integrations/blob/go/googleadk/v1.0.0/go/googleadk/README.md#L310-L356)
  for the client and streaming limits.
- **Not yet:** `RunLive` (bidirectional streaming), sub-agent-as-child-workflow, live memory/artifact tools that require
  in-workflow network I/O, and database/Vertex session services. These raise or are documented rather than silently
  degrading. Also not supported yet:
  - Parallel agents (`parallelagent`), `ParallelWorker` nodes, and graph (`workflowagent`) fan-outs with two or more
    branches that make a `NewModel` call, use an `ActivityAsTool` tool or MCP toolset, or call an A2A agent built with
    the plugin's providers. The Worker process exits, each Worker that retries the Workflow Task exits too, and the
    run stays open until you terminate it or its Workflow Execution Timeout expires. A graph fan-out can instead
    fail the run with a node panic. Fan out with `agenttool` tools called in one model response, or use a sequential
    agent (`sequentialagent`).
  - Single-turn sub-agents (`llmagent.ModeSingleTurn`) called in the same model response as another tool or sub-agent:
    every Workflow Task fails. Pass `googleadk.WithSequentialToolFanout()` to `NewContext`, or wrap the agents with
    `agenttool.New`.
  - Graph node `RetryConfig` delays and `NodeConfig.Timeout`, which use the wall clock. Leave both unset.
  - Graph input requests without an `InterruptID` on ADK v2.6.0 to v2.7.1. Set a replay-stable `InterruptID`.
  - `toolsearch.New` around `NewMCPToolset`: every MCP tool is still declared to the model and callable.
  - Per-user MCP credentials (`mcptoolset.Config.Auth` with a provider that reads the acting user):
    `agent.IdentityFromContext` finds no user in the MCP Activities.
  - `GenerateContentConfig.HTTPOptions.ExtrasRequestProvider` is dropped without an error and doesn't reach the
    Worker model. Use `Headers` or `ExtraBody`, which do reach it.
- **Rejected:** ADK's remote A2A agents built without `NewA2AClientProvider`, or that fetch their card without
  `NewA2AAgentCardProvider`, including every agent from the deprecated `agent/remoteagent` package. They would send
  their requests again on every replay. A model call from an agent with such a remote agent below it returns an error.
  Add `googleadk.NewRunnerPlugin(root)` to the runner's plugins to also catch a remote root agent, agents reached by
  transfer, and other cases the model-call check misses. Neither check walks `workflowagent` graph nodes or looks
  below agents wrapped with `agenttool`. An agent using `NewModel` inside a wrapped agent still checks its own
  descendants. The runner plugin also misses agents wrapped with `agenttool` in `Toolsets`. Unchecked remote agents
  can still send requests again on replay. The
  [plugin README](https://github.com/temporalio/ai-integrations/tree/main/go/googleadk#supported--not-yet-supported)
  lists the exact rules.

## Samples

The [Google ADK plugin samples](https://github.com/temporalio/samples-go/tree/main/googleadk) demonstrate a basic agent
with a tool, a [multi-agent](https://github.com/temporalio/samples-go/tree/main/googleadk/multiagent) system, durable
[human-in-the-loop](https://github.com/temporalio/samples-go/tree/main/googleadk/humanintheloop) tool approval, and a
[continue-as-new chat](https://github.com/temporalio/samples-go/tree/main/googleadk/chat).
