Skip to content

AgentContext & AgentResult

The core interfaces that define data flow into and out of agents. AgentContext is the input to every agent execution, and AgentResult is the standardized output. Two supporting interfaces, AgentConfig and AgentCapability, control agent behavior and self-description.

Import

import type {
  AgentContext,
  AgentResult,
  AgentConfig,
  AgentCapability,
} from "@modernpath/agent-framework";

AgentContext

The execution context passed to every agent. Kept intentionally generic so it works in serverless handlers, Express middleware, NestJS controllers, and direct invocation.

interface AgentContext {
  userId: number;
  auditingId: number;
  prompt: string;
  parameters: Record<string, any>;
  metadata?: {
    requestId?: string;
    source?: string;
    parentAgent?: string;
    [key: string]: any;
  };
  documents?: Array<{
    id: string;
    name: string;
    content?: Buffer;
    mimeType?: string;
  }>;
  history?: Array<{
    role: "user" | "assistant" | "system";
    content: string;
    timestamp?: Date;
  }>;
}

Properties

Name Type Required Description
userId number Yes Authenticated user identifier. Used for access control and auditing.
auditingId number Yes Audit trail identifier. Tracks which organization or tenant initiated the request.
prompt string Yes The user's natural language input or instruction.
parameters Record<string, any> Yes Agent-specific parameters. Each agent defines what keys it expects (e.g. store, siteId, action).
metadata object No Request metadata. requestId for correlation, source for the originating system, parentAgent when called by an orchestrator. Accepts arbitrary additional keys.
documents Array<Document> No Binary document attachments (e.g. uploaded files). Each document has an id, name, optional content buffer, and mimeType.
history Array<HistoryEntry> No Conversation history for multi-turn interactions. Each entry has a role (user, assistant, or system), content string, and optional timestamp.

The parameters field is your primary extension point

Each built-in agent documents which keys it reads from parameters. When building custom agents, use parameters for all agent-specific configuration rather than adding top-level fields to AgentContext.

Metadata Keys Set by the Framework

When tracing is enabled, the framework injects a __traceContext key into metadata before calling executeInternal(). This allows downstream services (tool implementations, sub-agents) to record spans on the same trace.

Key Type Set By Description
__traceContext TraceContext BaseAgent.execute() Injected when a TraceStore is attached.
parentAgent string OrchestratorAgent Set when a sub-agent is invoked by the orchestrator.
stepNumber number OrchestratorAgent The plan step number that triggered this execution.
sessionId string Caller Used by TraceStore to group traces into sessions.
parentTraceId string Caller Links child traces to a parent trace.

AgentResult

The standardized result returned by every BaseAgent.execute() call.

interface AgentResult {
  success: boolean;
  data?: any;
  error?: string;
  executionTime: number;
  toolsUsed?: string[];
  tokensUsed?: {
    input: number;
    output: number;
    total: number;
  };
  metadata?: Record<string, any>;
}

Properties

Name Type Always Present Description
success boolean Yes true if executeInternal() completed without throwing.
data any On success The return value from executeInternal(). Structure depends on the agent.
error string On failure The error message if execution failed.
executionTime number Yes Wall-clock execution time in milliseconds.
toolsUsed string[] Yes Names of tools invoked via useTool() during this execution.
tokensUsed TokenUsage No Token counts if the agent tracks them. Set by agent implementations, not the base class.
metadata Record<string, any> No Additional metadata. When tracing is enabled, contains { traceId: string }.

Working with Results

const result = await agent.execute(context);

if (result.success) {
  // Access agent-specific response data
  console.log(result.data);

  // Check which tools were called
  console.log("Tools used:", result.toolsUsed);

  // Check trace ID (if tracing is enabled)
  console.log("Trace ID:", result.metadata?.traceId);
} else {
  // Handle failure
  console.error(`Agent failed after ${result.executionTime}ms: ${result.error}`);
}

AgentConfig

Configuration for an agent instance. Set via BaseAgent.setConfig().

interface AgentConfig {
  name: string;
  version: string;
  description?: string;
  timeout?: number;
  debug?: boolean;
  [key: string]: any;
}

Properties

Name Type Required Default Description
name string Yes Set by constructor Agent name.
version string Yes Set by constructor Agent version.
description string No "" Human-readable description.
timeout number No 60000 Maximum execution time in milliseconds before timeout.
debug boolean No false When true, the agent logs debug messages to console.

The interface is extensible -- you can add custom keys for agent-specific settings:

agent.setConfig({
  timeout: 120_000,
  debug: true,
  maxRetries: 3, // custom key
});

AgentCapability

Declares what an agent can do and which tools it requires.

interface AgentCapability {
  name: string;
  description: string;
  requiredTools?: string[];
  examples?: string[];
}

Properties

Name Type Required Description
name string Yes Capability identifier (e.g. "document-analysis", "rag-qa").
description string Yes Human-readable description of what this capability provides.
requiredTools string[] No Tool names that must be present in the ToolRegistry for this capability to function. Used by BaseAgent.hasCapability().
examples string[] No Example prompts or use cases for documentation and introspection.

Usage

class MyAgent extends BaseAgent {
  protected capabilities: AgentCapability[] = [
    {
      name: "invoice-extraction",
      description: "Extracts line items from invoice PDFs",
      requiredTools: ["documentRetrieve", "documentExtract"],
      examples: [
        "Extract all line items from the Q4 invoice",
        "What is the total amount on invoice #1234?",
      ],
    },
  ];

  // ...
}

// Runtime check
const agent = new MyAgent(registry);
const cap = agent.getCapabilities()[0];

if (agent.hasCapability(cap)) {
  console.log("All required tools are available");
} else {
  console.log("Missing tools -- capability unavailable");
}

  • BaseAgent -- the abstract class that uses these interfaces
  • ToolRegistry -- manages the tools referenced by AgentCapability.requiredTools
  • Built-in Agents -- see which parameters each agent expects