Type of the context object passed through agent and action execution. This allows for type-safe context propagation throughout the execution hierarchy. TContext may be a class instance with getters and methods — never spread it. Defaults to any for backward compatibility.
Type of the payload passed to the agent execution
Type of agent-type-specific execution parameters. Flow agents use FlowAgentExecuteParams, Loop agents could define their own. Defaults to unknown for backward compatibility.
OptionalabsoluteOptional absolute maximum number of iterations (steps) for the agent run. This provides a hard limit safety net to prevent infinite loops in case of configuration errors or unexpected agent behavior. This value overrides any agent-level MaxIterationsPerRun setting if it is lower.
If not specified, defaults to 5000 iterations as a safety measure. Use a higher value only if you have a legitimate need for very long-running agents.
This is different from MaxIterationsPerRun (agent metadata guardrail):
OptionalactionOptional runtime modifications to the agent's available actions.
Action changes allow dynamic customization of which actions are available to agents at runtime, without modifying database configuration. This is particularly useful for:
Changes are applied in order. For each agent in the hierarchy:
Changes are propagated to sub-agents based on scope:
// Add LMS and CRM integrations for a specific tenant
const params: ExecuteAgentParams = {
agent: myAgent,
conversationMessages: messages,
actionChanges: [
{
scope: 'global',
mode: 'add',
actionIds: ['lms-query-action-id', 'crm-search-action-id']
}
]
};
// Remove dangerous actions from sub-agents
const params: ExecuteAgentParams = {
agent: myAgent,
conversationMessages: messages,
actionChanges: [
{
scope: 'all-subagents',
mode: 'remove',
actionIds: ['delete-record-action-id', 'execute-sql-action-id']
}
]
};
// Different actions for specific sub-agent
const params: ExecuteAgentParams = {
agent: myAgent,
conversationMessages: messages,
actionChanges: [
{ scope: 'global', mode: 'add', actionIds: ['common-action-id'] },
{
scope: 'specific',
mode: 'add',
actionIds: ['special-data-action-id'],
agentIds: ['data-gatherer-sub-agent-id']
}
]
};
The agent entity to execute, containing all metadata and configuration
OptionalagentThe persisted MJ: AI Agent Sessions record ID this run belongs to, if the run is part of
a real-time/long-lived session. Distinct from the transport sessionID (per-connection
correlation id). Used to group the multiple AIAgentRuns of one session and to stamp
ConversationDetail/AIAgentRun rows.
OptionalagentOptional agent-type-specific execution parameters.
Different agent types can define their own parameter interfaces for type-specific configuration that doesn't belong in the general ExecuteAgentParams.
Examples:
The type is determined by the TAgentTypeParams generic parameter. When using a specific agent type, import and use its params interface for type safety.
import { FlowAgentExecuteParams } from '@memberjunction/ai-agents';
const params: ExecuteAgentParams<any, any, FlowAgentExecuteParams> = {
agent: myFlowAgent,
conversationMessages: messages,
agentTypeParams: {
startAtStep: AIEngine.Instance.GetAgentSteps(agentId).find(s => s.Name === 'Approval'),
skipSteps: [debugStep, testStep]
}
};
OptionalapiOptional array of API keys to use for AI provider access during agent execution. When provided, these keys will be used instead of the default keys configured in the system. This allows for runtime-specific API key usage, useful for:
Each key should specify the driverClass (e.g., 'OpenAILLM', 'AnthropicLLM') and the corresponding apiKey value.
OptionalassignmentOptional per-invocation override for feedback request assignment. Takes highest precedence over all metadata-driven defaults (agent type, category, request type).
When an agent creates a feedback request via Chat step, this strategy determines who the request is assigned to and how. If not provided, the framework walks the resolution chain:
OptionalautoOptional flag to automatically populate the payload from the last run. When true and lastRunId is provided, the framework will:
OptionalcancellationOptional cancellation token to abort the agent execution
OptionalclientOptional runtime override for client tool timeout (ms). Takes precedence over the agent's DefaultClientToolTimeoutMs config.
OptionalcompanyOptional company ID for scoping context memory (notes/examples)
OptionalconfigurationOptional AI Configuration ID to use for this agent execution. When provided, this configuration will be passed to all prompts executed by this agent and its sub-agents, enabling environment-specific model selection (e.g., Prod vs Dev configurations).
The configuration ID filters which AI models are available for prompt execution and can provide configuration parameters for dynamic behavior.
OptionalcontextOptional additional context data to pass to the agent execution. This context is propagated to all sub-agents and actions throughout the execution hierarchy. Use this for runtime-specific data such as:
IMPORTANT — class instances are supported and must be preserved.
TContext may be a class with getters, methods, and private state
(e.g., Skip's SkipAgentContext). Any code that touches this object
must NOT spread it into a plain object ({...context}) because the
spread operator strips the prototype chain, destroying all getters
and methods. Instead, mutate properties directly on the original
object when augmentation is needed.
Note: Avoid including sensitive data like passwords or API keys unless absolutely necessary, as context may be passed to multiple agents and actions.
OptionalcontextOptional user context for permission checking and personalization
OptionalconversationOptional conversation detail ID to associate with this agent execution. When provided, this value is stored in the ConversationDetailID column within the to be created AIAgentRun record. This allows for linking the agent run to a specific conversation detail for tracking and reporting purposes.
OptionalconversationOptional conversation ID — the PREFERRED input for conversation-driven runs.
All durable cross-turn context features (persistent summary compaction, the
summary-windowed context assembly via ConversationEngine.AssembleContextWindow
over LoadWindowRowsFresh rows, and conversation-history retrieval tools) are
gated on this being present.
When absent, the agent behaves exactly as before: the caller supplies
conversationMessages and only in-turn (per-run) context management applies —
programmatic runs, internal sub-agent invocations, and tests need no change.
When present alongside caller-supplied conversationMessages, the supplied
messages win (deliberate override/escape hatch); the id still flows to the run
record and gates the compaction/retrieval features.
Array of chat messages representing the conversation history
OptionalconvertOptional flag to convert UI markup (@{...} syntax) in user messages to plain text before passing to the agent.
When true (default), special UI syntax like mentions (@{_mode:"mention",...}) and form responses (@{_mode:"form",...}) are converted to human-readable plain text:
When false, the raw @{...} JSON is preserved in conversation history.
This prevents agents from:
// Default behavior - convert to plain text
const params: ExecuteAgentParams = {
agent: myAgent,
conversationMessages: messages, // "@{_mode:"mention",...}" becomes "@Agent Name"
};
// Preserve raw markup (not recommended)
const params: ExecuteAgentParams = {
agent: myAgent,
conversationMessages: messages,
convertUIMarkupToPlainText: false, // Keep raw @{...} syntax
};
OptionaldataOptional data for template rendering and prompt execution, passed to the agent's prompt as well as all sub-agents
OptionaldisableOptional flag to disable data preloading from AIAgentDataSource metadata. When true, the agent will not automatically preload data sources even if they are configured in the database. This is useful for:
Default: false (data preloading is enabled)
Note: Caller-provided data in the data parameter always takes precedence over preloaded data, even when preloading is enabled.
OptionaleffortOptional effort level for all prompt executions in this agent run (1-100).
Higher values request more thorough reasoning and analysis from AI models. This effort level takes precedence over the agent's DefaultPromptEffortLevel and individual prompt EffortLevel settings for all prompts executed during this agent run.
Each provider maps the 1-100 scale to their specific effort parameters:
This setting is inherited by all sub-agents unless they explicitly override it.
Precedence hierarchy (highest to lowest priority):
OptionalinputOptional input artifacts for this run. Consumed by the agent's
ArtifactToolManager: each artifact is registered, surfaced in the
_ARTIFACT_MANIFEST template variable, and reached by the LLM via
artifact tool calls (json_path, json_search, etc.).
Not propagated to sub-agents — sub-agents that need artifact access
gather their own from the conversation in AgentRunner.
OptionallastOptional ID of the last run in a run chain. When provided, this links the new run to a previous run, allowing agents to maintain context across multiple interactions. Different from parentRun which is for sub-agent hierarchy.
OptionalmaxOptional wall-clock timeout for the entire agent run, in milliseconds.
When set, BaseAgent wraps the execution in an internal AbortController
that fires after this many ms. The abort propagates through the existing
cancellationToken chain — sub-agents, pending prompt calls, and
actions (which carry their own RunActionParams.AbortSignal) all see
the cancellation. On timeout, the run terminates with an Aborted result
whose message identifies the timeout origin.
When omitted, BaseAgent falls back to its DefaultAgentTimeoutMS
(currently 2 hours) — generous by default because some Loop agents do
legitimate long iteration; tighten per-run for anything interactive.
OptionalmessageOptional runtime override for message expiration behavior. When specified, these values take precedence over the AIAgentAction configuration for all action results in this agent run. Useful for testing, debugging, or implementing custom expiration strategies.
OptionalonOptional callback fired immediately after the AgentRun record is created and saved. Provides the AgentRun ID for immediate tracking/monitoring purposes.
This callback is useful for:
The callback is invoked after the AgentRun is successfully saved but before the actual agent execution begins. If the callback throws an error, it will be logged but won't fail the agent execution.
The ID of the newly created AIAgentRun record
OptionalonOptional callback for message lifecycle events. Called when messages are expired, compacted, removed, or expanded during agent execution. Useful for monitoring, debugging, and tracking token savings.
OptionalonOptional callback for receiving execution progress updates
OptionalonOptional callback for receiving streaming content updates
OptionaloverrideOptional runtime override for agent execution. When specified, these values take precedence over all other model selection methods. Currently supports model and vendor overrides, but can be extended in the future.
Model selection precedence (highest to lowest):
This override is passed to all prompt executions within the agent, allowing consistent model usage throughout the agent's execution hierarchy.
OptionalmodelId?: stringOptionalstorageAccountId?: stringRuntime override for the file storage account used when creating file artifacts. Highest priority in the resolution chain: Runtime → Agent → Category tree → Type → system fallback. Resolves to a FileStorageAccount record which carries both the provider driver (via ProviderID) and credentials (via CredentialID).
OptionalvendorId?: stringOptionalparentOptional parent agent hierarchy for sub-agent execution
OptionalparentOptional parent depth for sub-agent execution
OptionalparentOptional parent agent run entity for nested sub-agent execution
Optional InternalparentOptional parent step counts from root to immediate parent agent. Used to build hierarchical step display (e.g., "2.1.3" for nested agents).
OptionalpayloadOptional payload to pass to the agent execution, type depends on agent implementation. Payload is the ongoing dynamic state of the agent run.
OptionalplanPer-request Plan Mode toggle. Defaults OFF (undefined/false) — no behavior change unless
explicitly set. When true AND agent.SupportsPlanMode is on (the agent-level capability
gate, default ON/opt-out) AND this is a root agent (depth 0), the agent must present a
Plan next step and get human approval via the standard MJ: AI Agent Requests /
response-form HITL flow before it may execute Actions or Sub-Agents. Ignored entirely for
Realtime/session-driven and Proxy agents (those opt the capability OFF at the agent level).
On a continuation run (lastRunId set, after the user responds to the plan-approval
request), the framework re-resolves whether that prior run's plan was approved — callers
do not need to re-derive or persist this themselves.
OptionalPrimaryPrimary scope entity name (e.g., 'Organizations', 'Skip Tenants'). Resolved to PrimaryScopeEntityID on the AIAgentRun record. Used by external applications for multi-tenant memory scoping. Not used by MJ's own chat infrastructure.
OptionalPrimaryPrimary scope record ID — the actual record ID within the primary entity. Stored as an indexed column on AIAgentRun/AIAgentNote for fast filtering. Used by external applications for multi-tenant memory scoping. Not used by MJ's own chat infrastructure.
OptionalproviderOptional per-request metadata provider for multi-user server isolation. Pass the request-scoped provider from the GraphQL context so agent DB operations never share the global singleton's transaction state with concurrent requests. When omitted, falls back to the global Metadata.Provider (safe for single-user/client-side use).
OptionalrequestedSkills the caller (typically an end user via a /skill-name mention in the composer)
explicitly requests be active for this run, identified by AISkill.ID. The framework
treats these as pre-activation hints: at run start each requested skill is activated
(its Instructions appended + bundled Actions/sub-agents surfaced) only if it survives
the guard — it must be in the set the agent accepts (MJAIAgentEntityExtended.AcceptsSkills
gate) AND the requesting user must have Run permission on it (open-by-default via
AISkillPermissionHelper). Requested skills that fail either check are silently dropped,
never surfaced to the model — so a client can never smuggle in a skill the user or agent
isn't entitled to. Root-agent only (skills don't cascade to sub-agents). Defaults to none.
OptionalSecondaryArbitrary key/value dimensions for external-app scoping. Stored as JSON in the SecondaryScopes column on AIAgentRun/AIAgentNote. Used by external applications (Skip, Izzy, etc.) to segment agent memory by custom dimensions. MJ's own chat infrastructure does not use this.
OptionalsessionOptional session ID for client tool communication. When provided, enables the agent to invoke client-side tools via PubSub. The session ID correlates tool requests/responses between server and client.
OptionalsubOptional runtime modifications to the agent's available sub-agents.
The sub-agent counterpart of actionChanges. Lets callers dynamically add or remove which sub-agents are available to agents at runtime, without modifying database configuration. Changes are applied per agent in the hierarchy and propagated to sub-agents by the same scope rules as action changes ('global'/'root'/'all-subagents'/'specific').
OptionaltestOptional test run ID to associate with this agent execution. When provided, this value is stored in the TestRunID column within the AIAgentRun record, linking the agent run to a specific test run from the MemberJunction testing framework for tracking and reporting purposes.
OptionaluserOptional user ID for scoping context memory (notes/examples). If not provided, uses contextUser.ID
OptionalverboseOptional flag to enable verbose logging during agent execution. When true, detailed information about agent decision-making, action selection, sub-agent invocations, and execution flow will be logged. Can also be controlled via MJ_VERBOSE environment variable.
Parameters required to execute an AI Agent.
Example