showcase/shell-docs/src/content/reference/hooks/useAgentContext.mdx
useAgentContext registers a dynamic context object with the active Copilot runtime for the lifetime of the component. The hook adds the context on mount and removes it on unmount, so the agent always sees an up-to-date snapshot of your application state without manual cleanup.
Update the incoming context object to refresh what the agent sees. This is the v2 equivalent of useCopilotReadable -- it lets you surface any serializable application state (user preferences, selected items, computed values, etc.) as context that agents can reference when generating responses or making decisions.
import { useAgentContext } from "@copilotkit/react-core/v2";
function useAgentContext(context: AgentContextInput): void;
Provide simple application state as context for the agent.
function UserGreeting({ user }: { user: { name: string; role: string } }) {
useAgentContext({
description: "The currently logged-in user",
value: { name: user.name, role: user.role },
});
return <div>Welcome, {user.name}</div>;
}
The context updates automatically when the value changes between renders.
function ProductCatalog() {
const [selectedCategory, setSelectedCategory] = useState("electronics");
const [priceRange, setPriceRange] = useState({ min: 0, max: 500 });
useAgentContext({
description: "The user's current product filter settings",
value: {
category: selectedCategory,
priceRange,
},
});
return (
<div>
<select
value={selectedCategory}
onChange={(e) => setSelectedCategory(e.target.value)}
>
<option value="electronics">Electronics</option>
<option value="books">Books</option>
<option value="clothing">Clothing</option>
</select>
</div>
);
}
Each component can register its own context. All registered contexts are visible to the agent simultaneously.
function Dashboard() {
useAgentContext({
description: "Current dashboard view and layout",
value: { view: "analytics", columns: 3 },
});
return (
<div>
<Sidebar />
<MainPanel />
</div>
);
}
function Sidebar() {
const [collapsed, setCollapsed] = useState(false);
useAgentContext({
description: "Sidebar navigation state",
value: { collapsed, activeSection: "reports" },
});
return <nav></nav>;
}
context object changes between renders, the agent immediately sees the updated value.value must conform to JsonSerializable (string | number | boolean | null | JsonSerializable[] | { [key: string]: JsonSerializable }). Non-serializable values such as functions, class instances, or symbols will cause errors.useAgentContext calls across your component tree are all visible to the agent concurrently. Each is identified by its description and value.void. Unlike useCopilotReadable, it does not return an ID for parent-child hierarchies.useCopilotReadable -- v1 equivalent for providing context