Google Managed Agents in the Gemini API: Production Guide
> A verification-first guide to Google Gemini Managed Agents: background execution, remote MCP, custom functions, credential refresh, sandboxing, costs, retention, and implementation.
🎧 Listen — ~13 min
Ready · Google Managed Agents in the Gem
Google’s Managed Agents in the Gemini API are now more practical for production workloads: background execution lets long-running tasks continue after the client disconnects, remote MCP connects agents to external tool servers, custom functions bridge local business logic, and credential refresh preserves a running environment while network credentials rotate. The feature runs through Google’s Interactions API and provisions a managed Linux sandbox for agent execution.
This guide explains the architecture, the JavaScript implementation path, the security boundaries you need to configure, and where Managed Agents fit compared with a self-hosted agent harness.
Direct answer
Use Gemini Managed Agents when you want Google to provision and operate the agent runtime while your application supplies the task, tools, network policy, and approval logic. The practical production pattern is:
- Create an interaction with the
antigravity-preview-05-2026managed agent andenvironment: "remote". - Set
background: truefor research, coding, or other work that can outlive an HTTP request. - Add built-in tools such as code execution and Google Search only when needed.
- Add a remote MCP server or custom function for controlled access to business systems.
- Poll or resume the interaction, and require human review before external side effects.
Google’s documentation currently labels Managed Agents Public Preview. Treat the sandbox as an execution boundary, not as an authorization system: credentials, network allowlists, tool permissions, data retention, and approval gates remain application responsibilities.
What Google added
Google announced four capabilities for Managed Agents in the Gemini API on July 7, 2026:
- Background execution: set
background: true; the API returns an interaction ID immediately and the client can poll, stream, or reconnect later. - Remote MCP integration: connect the managed agent directly to an MCP server and combine those tools with built-in sandbox tools.
- Custom function calling: let the agent request a function that your application executes locally, returning the result through the interaction protocol.
- Credential refresh: reuse an existing environment while replacing network credentials, preserving the sandbox filesystem, installed packages, and repositories.
The underlying Interactions API is now generally available and is Google’s recommended interface for new Gemini API projects. It represents each task as an Interaction containing execution steps, tool calls, results, and model output.
Architecture: managed execution with application-owned control
Google manages the agent runtime and sandbox lifecycle. Your application still decides which environment to use, which tools to expose, how to execute custom functions, which domains the sandbox may reach, and whether an output is safe to apply.
That distinction matters for teams already designing harness engineering controls for AI coding agents. Managed infrastructure can remove VM and dependency-management work, but it does not remove the need for deterministic checks, least privilege, audit logs, or a clear stop condition.
Prerequisites and API surface
The documented JavaScript path uses @google/genai 2.3.0 or later. Create a project and API key according to Google’s current account and region requirements, then keep the key in the runtime secret manager rather than source control.
1npm install @google/genai
2export GEMINI_API_KEY="replace-me"The main objects and fields are:
| Object or field | Purpose | Operational note |
|---|---|---|
interactions.create() | Starts a model or agent task | Re-specify interaction-scoped tools and instructions on each turn |
agent or model | Selects the managed agent or Gemini model | Google’s examples use antigravity-preview-05-2026 |
environment: "remote" | Provisions or uses a remote managed environment | Managed-agent follow-ups need the environment context |
background: true | Runs asynchronously | Required for work that may exceed ordinary request timeouts |
previous_interaction_id | Continues stored conversation history | Not available when store: false |
tools | Enables built-in, MCP, or custom tools | Expose the smallest useful set |
environment_id | Reuses a managed environment | Useful for stateful follow-ups and credential refresh |
Google’s overview says managed-agent interactions can consume roughly 100,000 to 3 million tokens per task depending on reasoning loops and tools. Preview compute is not billed separately in the overview, but token and tool usage still affect cost. Benchmark your own workloads rather than assuming a single prompt equals one model call.
Build a background managed-agent task
The following example starts a remote coding or research task and polls without holding the original HTTP request open. The agent name and fields are taken from Google’s official announcement and Interactions API documentation.
1import { GoogleGenAI } from "@google/genai";
2
3const client = new GoogleGenAI({
4 apiKey: process.env.GEMINI_API_KEY,
5});
6
7const started = await client.interactions.create({
8 agent: "antigravity-preview-05-2026",
9 input:
10 "Inspect the repository, run the test suite, group failures by root cause, and write a report to /tmp/test-report.md.",
11 environment: "remote",
12 tools: [
13 { type: "code_execution" },
14 ],
15 background: true,
16});
17
18console.log(`Started interaction ${started.id}`);
19
20let result = started;
21while (result.status === "in_progress") {
22 await new Promise((resolve) => setTimeout(resolve, 5000));
23 result = await client.interactions.get(started.id);
24}
25
26if (result.status !== "completed") {
27 throw new Error(`Agent ended with status: ${result.status}`);
28}
29
30console.log(result.output_text);A production worker should persist the interaction ID, status transitions, timestamps, and any required-action steps. If the process restarts, retrieve the interaction by ID instead of starting a duplicate task. Add an application-level deadline and cancellation path; asynchronous execution should not become unbounded execution.
Add remote MCP without custom proxy middleware
Managed Agents can call a remote MCP server alongside built-in tools. The conceptual configuration is:
1const interaction = await client.interactions.create({
2 agent: "antigravity-preview-05-2026",
3 input:
4 "Check the internal observability service for authentication latency spikes and correlate them with recent commits.",
5 environment: "remote",
6 tools: [
7 { type: "google_search" },
8 { type: "code_execution" },
9 {
10 type: "mcp_server",
11 name: "internal_telemetry",
12 url: "https://mcp.example.com/mcp",
13 },
14 ],
15});
16
17console.log(interaction.output_text);Do not interpret direct MCP connectivity as permission to expose an entire internal platform. Put an authentication layer in front of the server, validate the calling identity, scope tools to read-only operations where possible, and log every tool invocation. For teams migrating MCP infrastructure, the MCP stateless migration guide provides useful context on session state and horizontal scaling.
Remote MCP also creates a new trust boundary. The managed sandbox, Google’s service, your MCP server, and the underlying business system each handle data. Document what crosses each boundary, whether tool results contain personal or confidential information, and how long logs are retained.
Combine built-in tools with custom functions
Built-in tools execute on Google-managed infrastructure. Custom functions transition the interaction to requires_action, at which point your application performs the operation and sends back the matching result. This is the safer pattern for actions that must remain inside your network or authorization layer.
1const getTicket = {
2 type: "function",
3 name: "get_ticket",
4 description: "Read one support ticket by ID. Never modify ticket state.",
5 parameters: {
6 type: "object",
7 properties: {
8 ticket_id: { type: "string" },
9 },
10 required: ["ticket_id"],
11 },
12};
13
14const interaction = await client.interactions.create({
15 agent: "antigravity-preview-05-2026",
16 input: "Read ticket ACME-1842 and summarize the customer-visible issue.",
17 environment: "remote",
18 tools: [
19 { type: "code_execution" },
20 getTicket,
21 ],
22});
23
24if (interaction.status === "requires_action") {
25 const call = interaction.steps.find(
26 (step) => step.type === "function_call" && step.name === "get_ticket"
27 );
28
29 if (call) {
30 const ticket = await readTicketFromYourService(call.arguments.ticket_id);
31 // Use the SDK's documented function-result submission method here.
32 console.log({ callId: call.id, ticket });
33 }
34}The final submission method and step shape should be checked against the installed SDK version. Do not copy an example that only logs a result into a production integration: the application must send a function-result step with the same call identifier so the agent can continue.
Keep custom tools narrow. A deploy_to_production function is much harder to secure than separate create_release_candidate, run_smoke_tests, and request_human_approval operations. Explicit states make it easier to audit and deny unsafe transitions.
Credential refresh and environment reuse
Long-running agents often outlive short-lived OAuth tokens. Google’s July announcement describes refreshing credentials by passing the existing environment_id with a new network configuration. The environment can retain its filesystem state, installed packages, and cloned repositories while the network layer receives a replacement token.
This is useful, but it is not a reason to inject long-lived secrets. Prefer:
- short-lived tokens with a narrowly scoped audience;
- domain allowlists rather than unrestricted outbound access;
- header transformation or an egress proxy so raw credentials are not placed in prompts or files;
- explicit rotation and revocation events;
- logs that record which credential policy was used without recording the secret itself.
Google’s documentation warns that managed-agent environments have unrestricted outbound network access by default unless you configure an allowlist. That default should be treated as unsafe for sensitive repositories or production data.
Security, privacy, and retention checklist
Before allowing a managed agent to touch real systems, verify:
- Network policy: disable broad egress and allow only required domains.
- Credential scope: use service accounts or tokens that cannot perform unrelated actions.
- Tool permissions: separate read, write, and destructive functions.
- Human approval: gate deployments, data deletion, customer communication, and financial actions.
- Filesystem handling: avoid copying secrets into the sandbox; delete sensitive artifacts after use.
- Prompt and output handling: scan tool results for personal data and prompt injection before reuse.
- Observability: store interaction IDs, tool calls, statuses, and failure reasons.
- Retention: choose
store: falsewhere appropriate, understanding that it prevents background execution andprevious_interaction_idstate management. - Preview risk: review outputs before relying on them in sensitive workflows because Managed Agents remain Public Preview.
The Interactions API stores requests by default to support server-side state, background execution, and observability. Google’s documentation says paid-tier interactions are retained for 55 days and free-tier interactions for one day, with project-level retention controls available for paid projects. Confirm current terms and controls for your account before sending regulated data.
For a broader comparison of sandbox boundaries and agent tool authorization, see the AI agent tool authorization and CoreBreak analysis.
Performance and cost trade-offs
Managed execution trades infrastructure work for API-level operating costs and platform dependence.
Where it helps:
- long-running jobs no longer depend on one open client connection;
- a consistent Linux environment reduces “works on my machine” drift;
- built-in code execution and web tools reduce glue code;
- environment reuse can preserve downloaded dependencies and intermediate files;
- remote MCP avoids a bespoke proxy layer for some integrations.
Where it can hurt:
- an agent may perform many reasoning and tool loops, making token usage unpredictable;
- remote execution adds network latency compared with a local function;
- cold starts and package installation need measurement;
- preview APIs can change behavior or limits;
- data retention and region requirements may rule out the service for some workloads;
- the managed sandbox does not automatically understand your organization’s approval policy.
Measure time to first status, time to completion, tool-call latency, token usage, failure rate, retry rate, and human-review rate. Compare those metrics with a self-hosted runtime rather than comparing only headline API prices.
Managed Agents versus a self-hosted harness
| Decision factor | Gemini Managed Agents | Self-hosted agent harness |
|---|---|---|
| Runtime operations | Google provisions the environment | Your team owns compute and lifecycle |
| Startup effort | Low: API and agent configuration | Higher: sandbox, workers, queues, observability |
| Tool integration | Built-in tools, MCP, custom functions | Full control over adapters and networks |
| Network control | Allowlist and managed credential patterns | Full infrastructure-level control |
| Data residency | Depends on Google availability and account configuration | You choose the hosting boundary |
| Cost profile | Token/tool usage plus platform dependence | Compute, operations, and model/provider costs |
| Best fit | Teams prioritizing fast managed execution | Teams needing deep control or strict isolation |
The right choice can also be hybrid: use Managed Agents for low-risk research and code analysis, while routing sensitive writes through an internal approval service or keeping regulated workloads self-hosted.
Common errors and debugging
The task times out. Use background: true and persist the interaction ID. Do not simply increase a frontend request timeout.
A follow-up cannot find files from the previous run. For a managed-agent continuation, preserve the environment context and use the documented previous_interaction_id and environment fields. Verify that the first interaction completed before chaining.
The agent reaches an internal service but should not. Check the network allowlist, MCP server authentication, and credential transformation rules. Remove broad egress while debugging.
A custom function is called repeatedly. Make the function description and schema deterministic, return structured errors, and keep an idempotency key for operations that could be retried.
The agent produces a plausible but unsafe change. Add deterministic tests, a separate evaluator, and an approval gate. Managed execution does not replace the verification loop described in the harness engineering guide.
Costs are higher than expected. Inspect interaction steps and tool usage, set task budgets in your worker, cache stable context, and use a smaller model for classification or summarization where the agent does not need deep reasoning.
FAQ
What are Managed Agents in the Gemini API?
They are configurable agents that run reasoning, code execution, file operations, and web access inside a Google-managed Linux sandbox. Your application creates interactions and controls tools, network policy, credentials, and approvals.
Is background execution the same as a job queue?
Not completely. It gives the interaction server-side asynchronous execution and a retrievable ID, but your application still needs durable job records, retry policy, user notification, cancellation, and business-level idempotency.
Can Managed Agents connect to MCP servers?
Yes. Google’s July 2026 announcement documents remote MCP server integration. Treat the MCP server as a privileged integration and enforce its own authentication, authorization, validation, and audit logging.
Are Managed Agents production-ready?
The Interactions API is generally available, but Google’s Managed Agents overview labels managed agents Public Preview. Use them with staged rollouts, review gates, and a fallback plan until your workload is covered by a stable service commitment.
Does Google automatically secure the agent’s network?
No. Google’s documentation says outbound network access is unrestricted by default unless you configure an allowlist. Restrict domains and inject only short-lived, least-privilege credentials.
Conclusion
Managed Agents make the runtime side of agent engineering simpler, especially for long-running research, coding, and tool-orchestration tasks. The important design is not “send a prompt to a remote VM.” It is an asynchronous interaction with explicit tool boundaries, controlled network access, durable status handling, and human review for consequential actions.
Start with a read-only workflow, enable background execution, record every interaction ID, and measure cost and latency. Add MCP and custom functions one boundary at a time. If the service’s preview status, retention model, or regional controls do not fit the workload, keep the same verification-first architecture and move the execution layer to a self-hosted harness.
Sources
- Google: Expanding Managed Agents in Gemini API
- Gemini API Agents Overview
- Gemini API Interactions API
- Gemini API Background Execution
- Gemini API Tools
- 24 AI: Google Expands Managed Agents
- Presenc AI: Managed Agents in the Gemini API
Visual: original Mermaid architecture diagram by Essa Mamdani, based on the cited Google API and documentation sources.
Visual: Model execution pipeline
This original flow explains the runtime path behind the model or agent discussed here. It separates context preparation, inference, tools, and output verification.
Visual reading: the model is one stage in the system, not the whole system. Tool calls and generated artifacts need an explicit verification boundary before they are trusted.
| Stage | Main question | Useful signal |
|---|---|---|
| Context | Is the input relevant and complete? | Grounding and prompt size |
| Inference | Is the model meeting the task? | Quality, latency, token use |
| Tools | Are actions permitted? | Success and permission errors |
| Output | Can the result be used safely? | Tests, review, provenance |
Keep reading
Related reading
⚡ Daily AI Model Drop — Get Kimi K3 benchmarks before Twitter
Join 2,400+ AI engineers. 1 email/day, no spam, unsubscribe anytime