# Agent Read-Only Context

> Publish UI values to the agent as a one-way read-only channel via useAgentContext.

<!-- interactive demo: readonly-state-agent-context -->

<Callout type="info" title="See this in Inspector">
  Open Inspector on localhost. Go to **Inspect**, then **Context**.
  The values you publish with `useAgentContext` appear here.

  More detail: [Inspector](/google-adk/inspector).
</Callout>

## What is this? [#what-is-this]

Sometimes you want the agent to *know* something about the current UI, like the logged-in user, the current page, or a recent activity log, but you don't want the agent to be able to modify it. That's what
`useAgentContext` is for: a one-way **UI → agent** channel for
read-only context.

Unlike full shared state (where the agent can call tools that mutate
the state back to the UI), `useAgentContext` values are pure inputs.
The agent sees them on every turn via the runtime's context injection,
but it has no setter and no tool to write them back.

## When should I use this? [#when-should-i-use-this]

Reach for `useAgentContext` instead of full shared state when:

- The value is **UI-owned** and has no meaning to the agent beyond
  "what the user is looking at right now".
- The agent should read but never write (user identity, feature flags,
  selected record, scroll position).
- You want the value to automatically unregister on unmount (e.g. the
  "current record" context disappears when you leave the page).

Think of it as "props for the agent".

If the agent must also write the value, use **[shared state](/google-adk/shared-state)**. To stream agent-written state to the UI during a run, see [State streaming](/google-adk/shared-state/streaming).

## How it works in code [#how-it-works-in-code]

<Callout type="warn" title="ADK agents must put the context in the prompt">
  Unlike the Built-in Agent, an ADK agent does **not** receive this context
  automatically. The AG-UI adapter stores it in ADK session state under
  `CONTEXT_STATE_KEY` (`"_ag_ui_context"`) and stops there. Nothing puts it in
  the prompt.

  An `LlmAgent` built with a plain string `instruction` therefore never sees
  it. The agent still answers, fluently and in the right shape, from nothing.
  That reads like a working integration until you check the answer against
  your own records. The instruction provider below is the step that connects
  them.
</Callout>

<Steps>
  <Step>
    ### Install the ADK + AG-UI bridge

    ```bash
    pip install ag-ui-adk
    ```

  </Step>
  <Step>
    ### Read CopilotKit context before each model call

    The adapter copies the AG-UI request's `context` list into ADK session
    state at `CONTEXT_STATE_KEY` (the public constant for `"_ag_ui_context"`).
    Read it from an instruction provider's `ctx.state`, a callback's
    `callback_context.state`, or a tool's `tool_context.state`.

    Each entry is a dictionary with `description` and `value` strings.
    Object and array values registered with `useAgentContext` arrive as JSON
    strings; use `json.loads(entry["value"])` when you need structured data.

    An instruction provider can include the context in the model's prompt.
    The fully defined callback preserves the Gemini termination safeguard
    without stopping partial responses or pending tool calls:

    ```python
    from ag_ui_adk import AGUIToolset, CONTEXT_STATE_KEY
    from google.adk.agents import LlmAgent
    from google.adk.agents.readonly_context import ReadonlyContext
    from google.adk.agents.callback_context import CallbackContext
    from google.adk.models.llm_response import LlmResponse

    def stop_on_terminal_text(
        callback_context: CallbackContext, llm_response: LlmResponse
    ) -> None:
        content = llm_response.content
        if llm_response.partial or not content or content.role != "model":
            return
        finish_reason = llm_response.finish_reason
        if getattr(finish_reason, "name", finish_reason) != "STOP":
            return
        parts = content.parts or []
        if not any(part.text for part in parts) or any(part.function_call for part in parts):
            return
        # ADK's invocation context is private; tolerate SDK changes.
        invocation = getattr(callback_context, "_invocation_context", None)
        if invocation is not None:
            try:
                invocation.end_invocation = True
            except AttributeError:
                pass

    def instructions(ctx: ReadonlyContext) -> str:
        entries = ctx.state.get(CONTEXT_STATE_KEY, [])
        context = "\n".join(
            f"{entry['description']}: {entry['value']}" for entry in entries
        )
        return (
            "Help the user using the following read-only application context.\n"
            + context
        )

    agent = LlmAgent(
        name="assistant",
        model="gemini-3.1-flash-lite",
        instruction=instructions,
        tools=[AGUIToolset()],
        after_model_callback=stop_on_terminal_text,
    )
    ```

    `AGUIToolset()` exposes frontend tools; it does not automatically add
    context to the model's instructions. The instruction provider above
    performs that step. Expose this agent through your `ADKAgent` endpoint.

    When only one tool needs the data, read the same entries from
    `tool_context.state[CONTEXT_STATE_KEY]` inside that tool instead of adding
    them to the whole prompt. On `google-adk` 1.22.0 or later,
    `ctx.run_config.custom_metadata["ag_ui_context"]` holds the same entries.

  </Step>
  <Step>
    ### Check that the agent really reads it

    This is the one integration that fails quietly, so check the answer
    against your own records. The reliable check is a control: send the same
    request once with the context and once with an empty context. Two answers
    that describe the same record mean the context changed nothing, and the
    agent is answering from its own invention.

  </Step>
</Steps>

Call `useAgentContext({ description, value })` once per value you want
to publish. Each call registers a dynamic context entry with the
runtime that is:

- Refreshed whenever `value` changes (React re-renders).
- Automatically removed when the component unmounts.
- Sent to the agent with every run. The Built-in Agent adds each entry to
  the system prompt. Python LangGraph agents need `CopilotKitMiddleware`
  to add the entries, and ADK agents need an instruction provider.
  Microsoft Agent Framework, CrewAI Flows and Pydantic AI agents drop the
  entries silently unless you wire them. The setup above shows the code
  for your framework.

```typescript title="src/app/demos/readonly-state-agent-context/page.tsx"
  useAgentContext({
    description: "The currently logged-in user's display name",
    value: userName,
  });
  useAgentContext({
    description: "The user's IANA timezone (used when mentioning times)",
    value: userTimezone,
  });
  useAgentContext({
    description: "The user's recent activity in the app, newest first",
    value: recentActivity,
  });
```

The `description` is important: it's a short human-readable label the
agent sees alongside the value, so it knows what to do with it. Treat
it like a parameter docstring.

Call `useAgentContext` in as many components as you like. The agent
receives every registered entry.

<Callout type="warn" title="Context values arrive as JSON strings">
  The AG-UI protocol defines a context value as a string. Therefore
  `useAgentContext` calls `JSON.stringify` on any `value` that is not already a
  string, and your agent receives the JSON text instead of the object or the
  array.

  Parse the value before you read a field from it. Use `json.loads(item["value"])`
  in Python, or `JSON.parse(item.value)` in TypeScript. If you skip the parse
  step, an index such as `colleagues[0]` returns a single character, and a shape
  check such as `isinstance(value, list)` can never pass.

  Do not stringify the value again, because that produces double encoding. A
  `value` that is already a string is sent unchanged, so no parse step is needed
  for it.
</Callout>

## Wire it to your own state [#wire-it-to-your-own-state]

`useAgentContext` doesn't care where the value comes from: local
state, a React Context, Redux, a query cache, anything. The only
requirement is that the identity of the value is stable enough for
React to avoid a render loop. In the demo we use a handful of
`useState` hooks; in a real app these would likely come from an auth
provider, a router hook, and your domain state stores.

```typescript title="src/app/demos/readonly-state-agent-context/page.tsx"
import React, { useState } from "react";
import {
  CopilotKit,
  CopilotPopup,
  useAgentContext,
} from "@copilotkit/react-core/v2";

import { ACTIVITIES, DemoLayout } from "./demo-layout";
import { useReadonlyStateAgentContextSuggestions } from "./suggestions";

export default function ReadonlyStateAgentContextDemo() {
  return (
    <CopilotKit
      runtimeUrl="/api/copilotkit"
      agent="readonly-state-agent-context"
    >
      <DemoContent />
      <CopilotPopup
        agentId="readonly-state-agent-context"
        defaultOpen={true}
        labels={{ chatInputPlaceholder: "Ask about your context..." }}
      />
    </CopilotKit>
  );
}

function DemoContent() {
  const [userName, setUserName] = useState("Atai");
  const [userTimezone, setUserTimezone] = useState("America/Los_Angeles");
  const [recentActivity, setRecentActivity] = useState<string[]>([
    ACTIVITIES[0],
    ACTIVITIES[2],
  ]);
```

## Treat entries as untrusted input [#treat-entries-as-untrusted-input]

Every entry is a claim your frontend made, and a user can change it. It
never proves who is making the request. Let entries inform the agent's
answer, but take facts that grant access, such as the authenticated user,
the workspace, or the tenant, from your server. If your agent builds its
prompt from entries, keep them apart from your own instructions, so text in
an entry can't override them.

## Try it [#try-it]

Ask the agent: "What is my name?" It answers with the value of `userName`. Change the name in your UI and ask again: the answer changes.
