Agent Read-Only Context
Publish UI values to the agent as a one-way read-only channel via useAgentContext.
See this in Inspector
Open Inspector on localhost. Go to Inspect, then Context.
The values you publish with useAgentContext appear here.
More detail: Inspector.
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?
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. To stream agent-written state to the UI during a run, see State streaming.
How it works in code
Pydantic AI does not pass context to your agent
Pydantic AI's AG-UI adapter passes messages, tools, and state to your
agent. It does not pass context, and it does not warn when it drops the
entries. An agent that never received your entries still answers confidently
about them. This is deliberate: entries are client-submitted, so Pydantic AI
leaves it to you to decide what to trust. Read them off run_input and hand
them to the agent yourself. See Pydantic AI's
AG-UI Context guide.
Pass the entries to the agent through deps
The entries arrive on RunAgentInput.context. Build the adapter in two
steps so you can reach run_input, pass the entries into deps, and
expose them to the model through a tool.
import json
from dataclasses import dataclass
from ag_ui.core import Context
from pydantic_ai import Agent, RunContext
from pydantic_ai.ui.ag_ui import AGUIAdapter
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Route
@dataclass
class AppContextDeps:
"""The entries the frontend shared on this run."""
context: list[Context]
agent = Agent(
"openai:gpt-6-luna",
instructions="You are a helpful assistant that can help emailing colleagues.",
deps_type=AppContextDeps,
)
@agent.tool
def colleagues(ctx: RunContext[AppContextDeps]) -> list[dict]:
"""The current user's colleagues, as the app shared them."""
for entry in ctx.deps.context:
if entry.description == "The current user's colleagues":
# `useAgentContext` JSON-stringifies `value` before it leaves the
# browser, and AG-UI types `Context.value` as a string, so parse it.
return json.loads(entry.value)
return []
async def run_agent(request: Request) -> Response:
# `dispatch_request` parses the request internally, so build the adapter in
# two steps instead: `run_input` is what carries the frontend's entries.
adapter = await AGUIAdapter.from_request(request, agent=agent)
deps = AppContextDeps(context=adapter.run_input.context)
return adapter.streaming_response(adapter.run_stream(deps=deps))
app = Starlette(routes=[Route("/", run_agent, methods=["POST"])])Two details are easy to miss:
valueis a string, not your object.useAgentContextcallsJSON.stringifyon the value before the run leaves the browser, and AG-UI typesContext.valueas a string on both ends. Sojson.loadsis required, and a shape check likeisinstance(entry.value, list)can never pass.- Use
from_request, notdispatch_request. The one-lineAGUIAdapter.dispatch_request(request, agent=agent)parses the request for you, which leaves you norun_inputto builddepsfrom.
Keep entries as data, not instructions
Every entry is a claim your frontend made. It never establishes who is
making the request. Deliver entries to the model as data, the way the
tool above does. Do not build
instructions out of
them: instructions carry operator authority, so composing them from
client-submitted text lets a prompt injection inherit that authority.
Facts your server established (the authenticated user, the workspace, the tenant) are what belong in instructions.
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
valuechanges (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
CopilotKitMiddlewareto 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.
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.
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.
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.
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
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
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.
How is this guide?