# Agent Read-Only Context

> Send UI values to the agent as a one-way, read-only channel with useAgentContext.

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

Sometimes you want the agent to *know* something about the current UI, like the signed-in user, the open screen, or a recent activity log, but you don't want the agent to change 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 write state back to the UI, `useAgentContext` values are pure inputs. The agent sees them on every turn, but it has no setter and no tool to write them back.

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

Use `useAgentContext` instead of full shared state when:

- The value is **UI-owned** and means nothing 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, open screen).
- You want the value to go away when the component unmounts. For example, the "current record" context disappears when the user leaves that screen.

Think of it as "props for the agent".

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

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

<Steps>
  <Step>
    ### Use AG2 1.1.2 or later

    With AG2 1.1.2 or later, `AGUIStream` hands every `useAgentContext` entry
    to the model, so a plain AG-UI endpoint needs no extra code. On AG2 1.0.x
    the entries never reach the model, and nothing reports an error. Upgrade
    first:

    ```bash
    pip install "ag2[ag-ui,openai]>=1.1.2"
    ```

  </Step>
  <Step>
    ### Serve the agent as usual

    `AGUIStream` adds the entries from `RunAgentInput.context` to the run's
    system prompt, after the agent's own prompt, as one block:

    ```text
    ## Context from the application

    - The current user's colleagues: [{"id":1,"name":"John Doe","role":"Developer"}, ...]
    ```

    Each line is the entry's `description`, then its `value` exactly as the
    client sent it. The block is prose for the model, not variables, so tool
    code does not see it.

    Do not add the entries to `dispatch(prompt=...)` yourself. That repeats
    them, and `prompt=` replaces the agent's own prompt rather than adding to
    it.

    To render the entries differently, pass `context_prompt=` to `dispatch`. It
    receives the entries and returns the block, or `None` to leave them out:

    ```python title="agent.py"
    def colleagues_only(entries):
        lines = [f"- {e.value}" for e in entries if "colleagues" in e.description]
        return "## Colleagues\n\n" + "\n".join(lines) if lines else None

    stream.dispatch(message, accept=accept, context_prompt=colleagues_only)
    ```

  </Step>
  <Step>
    ### Pass a context value to your tools (optional)

    To give a tool the value itself, decode the entry from
    `RunAgentInput.context` and pass it as a conversation variable. The
    `Variable()` annotation injects it into the tool, so the model does not
    have to pass it around. A value that the frontend passed as an object or an
    array arrives as a JSON string.

    ```python title="agent.py"
    import json
    from typing import Annotated

    from fastapi import FastAPI, Header
    from fastapi.responses import StreamingResponse

    from ag2 import Agent, Variable, tool
    from ag2.ag_ui import AGUIStream, RunAgentInput
    from ag2.config import OpenAIResponsesConfig

    def get_readable(message: RunAgentInput, description: str):
        raw = next(
            (item.value for item in message.context if item.description == description),
            None,
        )
        if raw is None:
            return None
        # `useAgentContext` JSON-encodes objects and arrays, but passes a
        # plain string through untouched — so decoding is best-effort.
        try:
            return json.loads(raw)
        except json.JSONDecodeError:
            return raw

    @tool
    def get_colleagues(
        colleagues: Annotated[list, Variable(default_factory=list)],
    ) -> list:
        """Return the current user's colleagues from CopilotKit readables."""
        return colleagues

    agent = Agent(
        name="assistant",
        prompt="You are a helpful assistant that can help emailing colleagues.",
        config=OpenAIResponsesConfig(model="gpt-6-luna"),
        tools=[get_colleagues],
    )

    stream = AGUIStream(agent)
    app = FastAPI()

    @app.post("/chat")
    async def run_agent(
        message: RunAgentInput,
        accept: str | None = Header(None),
    ) -> StreamingResponse:
        colleagues = get_readable(message, "The current user's colleagues") or []
        return StreamingResponse(
            stream.dispatch(message, variables={"colleagues": colleagues}, accept=accept),
            media_type=accept or "text/event-stream",
        )
    ```

    Everything in `dispatch(variables=...)` is sent back to the browser in
    `STATE_SNAPSHOT`. Do not put secrets there. Pass them with
    `dispatch(dependencies=...)`, which never leaves the server.

  </Step>
</Steps>

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

- Refreshed whenever `value` changes.
- 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.

```tsx title="src/ProfileScreen.tsx"
import { Text, View } from "react-native";
import { useAgentContext } from "@copilotkit/react-native/headless";

export function ProfileScreen({
  userName,
  timezone,
  recentActivity,
}: {
  userName: string;
  timezone: string;
  recentActivity: string[];
}) {
  useAgentContext({ // [!code highlight:4]
    description: "The signed-in user's name and timezone",
    value: { userName, timezone },
  });

  useAgentContext({
    description: "The last actions the user took in the app, newest first",
    value: recentActivity,
  });

  return (
    <View style={{ padding: 16 }}>
      <Text>Signed in as {userName}</Text>
    </View>
  );
}
```

The `description` matters. It's a short label the agent sees next to 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 entry that is registered at the time of the run.

<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, or your navigation state. The value must be JSON-serializable. Its serialized form is compared on each render, so a new object with the same contents does not register the entry again.

## Rendering data does not send it [#rendering-data-does-not-send-it]

A screen that renders a list has put the list in the view tree, not in the agent's context. Those are separate steps. An agent without the second step still answers: the text reads well, the values look plausible, and nothing errors.

Register the data with `useAgentContext`, and tell the agent in its instructions to refuse to answer about records that the context doesn't carry. Then check one answer against the records your app actually holds.

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

Every entry is a claim your app 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 app and ask again: the answer changes.

For every option, see the [`useAgentContext` reference](/reference/react-native/hooks/useAgentContext).
