Skip to main content

Overview

ToolContext provides the execution context for a tool invocation. It gives tools access to the current session, memory services, artifact services, event actions, and other contextual information needed during execution. Every tool’s runAsync() method receives a ToolContext instance as its second parameter.

Properties

functionCallId
string | undefined
The function call ID for this tool invocation. This ID is returned by the LLM to identify a specific function call, or assigned by ADK if not provided. Used to map function call responses to their original requests.
actions
EventActions
Event actions that can be used to interact with the agent system during tool execution.Provides methods for:
  • Sending events
  • Triggering callbacks
  • Communicating with the agent orchestrator
session
Session
The current session object containing:
  • Session ID
  • User ID
  • Session metadata
  • Conversation history
  • Session state
sessionService
BaseSessionService
Service for managing session persistence and retrieval. Use this to:
  • Update session data
  • Store session state
  • Query session information
memoryService
MemoryService | undefined
Memory service for storing and retrieving long-term memories (if configured).
Check if memoryService is defined before using it, as it may not be configured.

Methods

listArtifacts()

async listArtifacts(): Promise<string[]>
Lists the filenames of all artifacts attached to the current session.
return
string[]
Array of artifact filenames/keys.
async runAsync(args: any, context: ToolContext) {
  const artifacts = await context.listArtifacts();
  console.log('Available artifacts:', artifacts);
  // Output: ['document.pdf', 'data.csv', 'image.png']
  
  return { artifactCount: artifacts.length };
}
Throws an error if the artifact service is not initialized.

searchMemory()

async searchMemory(query: string): Promise<MemorySearchResult[]>
Searches the user’s long-term memory using semantic search.
query
string
required
The search query string.
return
MemorySearchResult[]
Array of memory search results, each containing:
  • content - The memory content
  • score - Relevance score
  • metadata - Associated metadata
async runAsync(args: { topic: string }, context: ToolContext) {
  const memories = await context.searchMemory(args.topic);
  
  const relevantMemories = memories
    .filter(m => m.score > 0.7)
    .map(m => m.content);
  
  return {
    found: relevantMemories.length,
    memories: relevantMemories
  };
}
Throws an error if the memory service is not configured.

Usage Examples

Accessing Session Information

import { BaseTool, ToolContext } from '@iqai/adk';

export class SessionInfoTool extends BaseTool {
  constructor() {
    super({
      name: 'session_info',
      description: 'Get current session information'
    });
  }

  async runAsync(args: any, context: ToolContext) {
    return {
      sessionId: context.session.id,
      userId: context.session.userId,
      messageCount: context.session.messages.length
    };
  }
}

Using Memory Service

import { BaseTool, ToolContext } from '@iqai/adk';

export class ContextualSearchTool extends BaseTool {
  constructor() {
    super({
      name: 'contextual_search',
      description: 'Search user memories for relevant context'
    });
  }

  async runAsync(
    args: { query: string },
    context: ToolContext
  ) {
    // Check if memory service is available
    if (!context.memoryService) {
      return { error: 'Memory service not configured' };
    }

    // Search memories
    const results = await context.searchMemory(args.query);
    
    // Filter and format results
    const topResults = results
      .slice(0, 5)
      .map(r => ({
        content: r.content,
        relevance: r.score
      }));

    return { results: topResults };
  }
}

Working with Artifacts

import { BaseTool, ToolContext } from '@iqai/adk';

export class ArtifactManagerTool extends BaseTool {
  constructor() {
    super({
      name: 'list_artifacts',
      description: 'List all artifacts in current session'
    });
  }

  async runAsync(args: any, context: ToolContext) {
    try {
      const artifacts = await context.listArtifacts();
      
      return {
        count: artifacts.length,
        artifacts: artifacts,
        sessionId: context.session.id
      };
    } catch (error) {
      return {
        error: 'Failed to list artifacts',
        message: error instanceof Error ? error.message : String(error)
      };
    }
  }
}

Accessing Invocation Context

import { BaseTool, ToolContext } from '@iqai/adk';

export class UserContextTool extends BaseTool {
  constructor() {
    super({
      name: 'user_context',
      description: 'Get user and app context information'
    });
  }

  async runAsync(args: any, context: ToolContext) {
    // Access the internal invocation context
    const invocationContext = context['_invocationContext'];
    
    return {
      appName: invocationContext.appName,
      userId: invocationContext.userId,
      sessionId: invocationContext.session.id,
      functionCallId: context.functionCallId
    };
  }
}

Type Definition

export class ToolContext extends CallbackContext {
  functionCallId?: string;
  
  constructor(
    invocationContext: InvocationContext,
    options?: {
      functionCallId?: string;
      eventActions?: EventActions;
    }
  );
  
  get actions(): EventActions;
  get session(): Session;
  get sessionService(): BaseSessionService;
  get memoryService(): MemoryService | undefined;
  
  async listArtifacts(): Promise<string[]>;
  async searchMemory(query: string): Promise<MemorySearchResult[]>;
}

See Also

Build docs developers (and LLMs) love