useSubscribeStateToAgentContext function allows you to automatically make any Cedar-registered state available to AI agents as context. This enables agents to understand your app’s current state and provide more relevant, contextual responses.
Prerequisite – The state you want to subscribe must first be registered in Cedar using eitheruseCedarStateoruseRegisterState.
useSubscribeStateToAgentContext Overview
TheuseSubscribeStateToAgentContext function subscribes to local state changes and automatically updates the agent’s input context whenever the state changes. This means your AI agent always has access to the most up-to-date information from your application, including any Zod schemas defined for the state.
Function Signature
Parameters
stateKey: string- The registered state key that we want to subscribe tomapFn: (state: T) => Record<string, any>- Function that maps your state to context entriesoptions(optional) - Configuration for visual representation and label extraction:icon?: ReactNode | ((item: ElementType<T>) => ReactNode)- Icon to display for this context. Can be a static React element or a function that returns an icon based on each itemcolor?: string- Hex color for visual stylinglabelField?: string | ((item: ElementType<T>) => string)- How to extract labels from your data. Can be a field name or a functionorder?: number- Display order for context badges (lower numbers appear first)showInChat?: boolean | ((entry: ContextEntry) => boolean)- Whether to show context badges in chat. Can be a boolean or a function to filter specific entries (default = true)collapse?: boolean | number | { threshold: number; label?: string; icon?: ReactNode }- Collapse multiple entries into a single badge. Can be boolean (default threshold 5), number (custom threshold), or object with full configuration
Basic Usage Example
Here’s a simple example with a todo list:Complex State Example
Here’s a more advanced example from the Product Roadmap demo:Using the labelField Option
ThelabelField option allows you to specify how labels should be extracted from your data. This is especially useful when your data has custom field names or when you need custom label logic.
labelField as a String
Specify which field to use as the label:labelField as a Function
Use a function for custom label generation:Dynamic Icons and Conditional Display
Cedar supports dynamic behavior for both icons and chat display through function-based options. This allows you to customize the appearance and visibility of context entries based on their actual data.Dynamic Icon Functions
Theicon option can accept a function that receives each item and returns an appropriate icon:
Conditional Chat Display with showInChat
TheshowInChat option can be a function that determines whether specific entries should appear as badges in the chat UI:
Advanced Dynamic Configuration Example
Here’s a comprehensive example combining dynamic icons, conditional display, and collapsing from the Product Roadmap demo:Function Parameter Types
When using function-based options, the parameters are strongly typed:- Icon Function
- showInChat Function
- labelField Function
item- Individual item from your data array (or the single item if not an array)- Returns - Any valid React node (JSX element, string, emoji, etc.)
Best Practices for Dynamic Options
- Performance: Dynamic functions are called for each item, so keep them lightweight
- Consistency: Use consistent logic patterns across your application
- Fallbacks: Always provide fallback values for unexpected data
- Type Safety: Leverage TypeScript for better development experience
Single Values Support
useSubscribeInputContext now supports single values (not just arrays):
Controlling Display Order
Theorder property allows you to control the display order of context badges in the UI. This is useful when you have multiple context subscriptions and want to prioritize their visibility.
How Order Works
- Lower numbers appear first:
order: 1will appear beforeorder: 10 - Default behavior: Items without an order are treated as having the maximum order value
- Stable sorting: Items with the same order maintain their original relative position
Basic Order Example
Complex Order Example with Mention Providers
When combininguseSubscribeInputContext with mention providers, you can create a well-organized context display:
Order Best Practices
- Use consistent spacing: Leave gaps between order values (1, 10, 20) to allow for future insertions
- Group related contexts: Give similar contexts adjacent order values
- Prioritize by importance: Most relevant context should have lower order values
- Document your ordering: Comment why certain items have specific orders
Collapsing Multiple Entries
Thecollapse option allows you to automatically collapse multiple context entries into a single badge when the number of entries exceeds a threshold. This is particularly useful for managing UI clutter when dealing with large datasets.
Collapse Configuration Types
Thecollapse option supports three different configuration formats:
- Boolean (Default)
- Number (Custom Threshold)
- Object (Full Configuration)
Set to When
true to enable collapsing with default settings:collapse: true, items will collapse into a single badge when more than 5 entries are present.Collapse Label Templates
When using the object format, thelabel field supports template variables:
{count}- Replaced with the actual number of entries- Static text - Any other text is displayed as-is
Real-World Collapse Examples
Dynamic Collapse Behavior
The collapse feature is dynamic and responsive to state changes:Default Label Extraction
When nolabelField is specified, the function looks for labels in this order:
titlefieldlabelfieldnamefieldidfield- String representation of the value
useSubscribeInputContext, entries are automatically marked with source: 'subscription'.
Output Behavior and Structure
What Gets Sent to the Agent
When the agent receives context fromuseSubscribeStateToAgentContext, it gets a simplified structure containing only the essential data:
The agent only receives the
source and data fields. Visual metadata like
icon, color, and label are used only for UI display and are not sent to
the agent.Array Behavior
The output structure depends on how you pass data touseSubscribeStateToAgentContext:
- Single Value → Single Entry
- Array → Array of Entries
- Single-Item Array → Array
When your
mapFn returns a single non-array value, it’s stored as a single context entry:Practical Examples
Here are real-world examples showing the input and output:Multiple Context Keys
When you return multiple keys from yourmapFn, each follows the same behavior rules:
Multiple State Subscriptions
You can subscribe multiple pieces of state:Best Practices
1. Transform Sensitive Data
Don’t expose sensitive information to the agent:2. Use Meaningful Keys
Choose descriptive keys for your context:3. Optimize Large Data Sets
For large data sets, consider filtering or summarizing:Visual Customization
Theoptions parameter allows you to customize how the context appears in the UI:

