API Reference
Toolpack Class
The main entry point for the SDK.
Initialization
import { Toolpack } from 'toolpack-sdk';
const toolpack = await Toolpack.init(config: ToolpackInitConfig);
ToolpackInitConfig
interface ToolpackInitConfig {
// Single provider (shorthand)
provider?: string; // 'openai' | 'anthropic' | 'gemini' | 'ollama' | 'openrouter' | 'vertexai' | 'anthropic-vertex'
apiKey?: string; // API key for the provider
model?: string; // Default model
// Multi-provider
providers?: Record<string, ProviderOptions>;
defaultProvider?: string;
// Custom providers
customProviders?: ProviderAdapter[] | Record<string, ProviderAdapter>;
// Tools
tools?: boolean; // Enable built-in tools
toolsConfig?: Partial<ToolsConfig>; // Global tool behavior (maxToolRounds, etc.)
toolOverrides?: ToolProject[]; // Replace built-ins by name (loaded after built-ins)
// Modes
customModes?: ModeConfig[]; // Custom modes
defaultMode?: string; // Mode to start in (default: 'chat')
// Logging
logging?: LoggingConfig; // File logging settings
// HITL
hitl?: HitlConfig; // Human-in-the-loop confirmation settings
onToolConfirm?: ToolConfirmCallback; // Confirmation handler (also enables HITL)
// Per-user tools
actor?: ToolActor | (() => ToolActor | null | undefined); // Passed to tools as ctx.actor
// Prompt
disableToolGuidance?: boolean; // Turn off the automatic tool usage guidance
disableBaseContext?: boolean; // Do not add the base agent context
// Vertex AI / Anthropic on Vertex
projectId?: string;
location?: string; // Vertex AI region (default 'us-central1')
googleAuthOptions?: { keyFilename?: string; credentials?: Record<string, unknown> };
thinkingBudget?: number; // Gemini 2.5+ thinking budget (0 turns it off)
region?: string; // Anthropic on Vertex region (default 'us-east5')
// Other
contextWindow?: ContextWindowConfig; // Conversation pruning/summarization
mcp?: McpToolsConfig; // MCP servers to load tools from
knowledge?: KnowledgeInstance | KnowledgeInstance[] | null; // Added as knowledge_search
confirmationMode?: 'off' | 'high-only' | 'all';
conversationId?: string; // Passed to onToolConfirm
interceptors?: ToolpackInterceptor[]; // Wrap every generate() call
}
customTools — use ModeConfig.customTools per agent instead.
modeOverrides — configure modes directly via customModes / registerMode().
configPath — all configuration is now passed inline to Toolpack.init().
Methods
generate()
Generate a completion (non-streaming).
// Full request
const response = await toolpack.generate({
messages: [{ role: 'user', content: 'Hello' }],
model: 'gpt-4o',
});
// Shorthand
const response = await toolpack.generate('Hello');
// With specific provider
const response = await toolpack.generate(request, 'anthropic');
stream()
Stream a completion.
const stream = toolpack.stream({
messages: [{ role: 'user', content: 'Hello' }],
model: 'gpt-4o',
});
for await (const chunk of stream) {
process.stdout.write(chunk.delta);
}
embed()
Generate embeddings.
const response = await toolpack.embed({
input: 'Hello world',
model: 'text-embedding-3-small',
});
console.log(response.embeddings); // number[][]
setProvider()
Switch the active provider.
toolpack.setProvider('anthropic');
getProvider()
Get the current provider adapter.
const provider = toolpack.getProvider();
loadToolProject() / loadToolProjects()
Load custom tool projects dynamically at runtime. Prefer loadToolProjects() when registering several projects — the BM25 tool-search index rebuilds once at the end.
import { myCustomTools } from './my-tools';
await toolpack.loadToolProject(myCustomTools);
await toolpack.loadToolProjects([projectA, projectB]);
To replace built-ins by name at init time, pass toolOverrides to Toolpack.init() instead.
loadRequestToolProject() / registerRequestTools()
Register tools that bypass mode filtering entirely and are always passed to the model regardless of allowedToolCategories. This is the same mechanism used internally by knowledge and mind tools.
Use loadRequestToolProject() when you have a ToolProject (the usual case), or registerRequestTools() when you have a plain RequestToolDefinition[].
import { RequestToolDefinition } from 'toolpack-sdk';
// From a ToolProject:
toolpack.loadRequestToolProject(myProject);
// From raw definitions:
const tools: RequestToolDefinition[] = [{ name: 'my_tool', ... }];
toolpack.registerRequestTools(tools);
Tools registered this way are deduplicated by name — registering the same name twice replaces the existing entry.
searchTools() / getRegisteredToolNames()
Inspect registered tools (useful in tests):
const { found, tools } = toolpack.searchTools('http get', 'http');
const names = toolpack.getRegisteredToolNames();
listProviders()
List all configured providers and their models.
const providers = await toolpack.listProviders();
// [{ name, displayName, type, models }]
listModels()
Get a flat list of all models.
const models = await toolpack.listModels();
// [{ id, displayName, capabilities, provider }]
setMode()
Switch the active mode.
toolpack.setMode('chat');
getMode()
Get the current mode configuration.
const mode = toolpack.getMode();
getModes()
Get all registered modes.
const modes = toolpack.getModes();
cycleMode()
Cycle to the next mode.
const nextMode = toolpack.cycleMode();
registerMode()
Register a custom mode at runtime.
toolpack.registerMode(modeConfig);
getClient()
Get the underlying AIClient instance.
const client = toolpack.getClient();
client.on('tool:progress', handler);
getWorkflowExecutor()
Get the workflow executor.
const executor = toolpack.getWorkflowExecutor();
disconnect()
Disconnect the active provider.
await toolpack.disconnect();
Types
Message
interface Message {
role: 'system' | 'user' | 'assistant' | 'tool';
content: string | MessageContent[] | null;
name?: string;
tool_call_id?: string;
tool_calls?: ToolCallMessage[];
}
CompletionRequest
interface CompletionRequest {
messages: Message[];
model: string;
temperature?: number;
max_tokens?: number;
top_p?: number;
response_format?: 'text' | 'json_object';
stream?: boolean;
tools?: ToolCallRequest[];
tool_choice?: 'auto' | 'none' | 'required';
signal?: AbortSignal;
interceptTool?: ToolInterceptor; // wraps every tool call of this request (v3.6.0); never sent to the provider
}
ToolInterceptor
Wraps every tool call of one request (v3.6.0). Call run() to run the tool and use or change its result, or return text without calling it to stop the call: the model then sees that text as the tool's result. See Stopping or changing a tool call.
interface InterceptedToolCall {
toolName: string;
args: Record<string, any>;
round: number; // tool round of the request, 1 for the first; parallel calls of one round share it
}
type ToolInterceptor = (call: InterceptedToolCall, run: () => Promise<string>) => Promise<string> | string;
CompletionResponse
interface CompletionResponse {
content: string | null;
usage?: Usage;
finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'error';
tool_calls?: ToolCallResult[];
}
CompletionChunk
interface CompletionChunk {
delta: string;
usage?: Usage;
finish_reason?: 'stop' | 'length' | 'tool_calls' | 'content_filter' | 'error' | 'aborted'; // 'aborted': stopped by the request's signal
tool_calls?: ToolCallResult[];
workflowStep?: { number: number; description: string };
}
ModeConfig
interface ModeConfig {
name: string;
displayName: string;
description: string;
systemPrompt: string;
allowedToolCategories: string[];
blockedToolCategories: string[];
allowedTools: string[];
blockedTools: string[];
blockAllTools: boolean;
baseContext?: { ... } | false;
workflow?: WorkflowConfig;
}
ProviderAdapter
abstract class ProviderAdapter {
name?: string;
abstract generate(request: CompletionRequest): Promise<CompletionResponse>;
abstract stream(request: CompletionRequest): AsyncGenerator<CompletionChunk>;
abstract embed(request: EmbeddingRequest): Promise<EmbeddingResponse>;
async getModels(): Promise<ProviderModelInfo[]>;
getDisplayName(): string;
}
ToolContext
Context passed to custom tools during execution.
interface ToolActor {
id: string; // the host application's stable id for the actor
kind?: string; // e.g. 'user'
}
interface ToolContext {
workspaceRoot: string;
actor?: ToolActor; // who this run acts for, when the host set one
config: Record<string, any>; // from toolsConfig.additionalConfigurations
log: (msg: string) => void;
signal?: AbortSignal; // aborted when the run was stopped; a long tool can watch it
}
createToolProject
Factory function to build and validate a ToolProject.
import { createToolProject, ToolDefinition, ToolProject } from 'toolpack-sdk';
const myToolProject: ToolProject = createToolProject({
key: 'my-project',
name: 'My Custom Tools',
displayName: 'My Custom Tools Package',
version: '1.0.0',
description: 'Example custom tool project',
category: 'custom',
tools: [ /* ToolDefinition objects */ ]
});
Errors
All SDK errors extend SDKError (message, code, statusCode?, cause?) and are exported from the package root.
| Error | code | Status | When |
|---|---|---|---|
AuthenticationError | AUTHENTICATION_ERROR | 401 | Invalid or missing API key |
RateLimitError | RATE_LIMIT_ERROR | 429 | Rate limited. retryAfter holds the wait when the provider gives one |
InvalidRequestError | INVALID_REQUEST_ERROR | 400 | The provider rejected the request |
ProviderError | PROVIDER_ERROR (default) | 500 | Any other provider failure |
ConnectionError | CONNECTION_ERROR | 503 | Provider unreachable |
TimeoutError | TIMEOUT_ERROR | 504 | Request timed out. phase says where |
PageError | PAGE_ERROR | 502 | A web page could not be loaded. pageUrl holds the address |
AbortedError | ABORTED | - | generate() was stopped by its signal (name is 'AbortError'). See Stopping a request |
ContextWindowExceededError | CONTEXT_WINDOW_EXCEEDED | 400 | The conversation is over the context window and could not be pruned or summarized |
InsufficientContextError | INSUFFICIENT_CONTEXT | 400 | Too little room is left for the request after pruning or summarizing |
SummarizationError | SUMMARIZATION_ERROR | 500 | Summarizing the conversation failed. failureReason says why |
ContextWindowConfigError | CONTEXT_WINDOW_CONFIG_ERROR | 400 | Invalid contextWindow settings. configField names the field |
ConversationNotFoundError | CONVERSATION_NOT_FOUND | 404 | The conversation ID is unknown |
import { RateLimitError, AuthenticationError, AbortedError } from 'toolpack-sdk';
try {
await toolpack.generate({ model, messages, signal });
} catch (err) {
if (err instanceof AbortedError) return; // stopped on purpose
if (err instanceof RateLimitError) { /* wait, then try again */ }
if (err instanceof AuthenticationError) { /* check the API key */ }
throw err;
}
MCP connections throw McpConnectionError (with exitCode when the server process ended) and McpTimeoutError. These extend Error, not SDKError.
Events
Toolpack Events
toolpack.on('status', (message: string) => {});
toolpack.on('workflow:plan_created', (plan) => {});
toolpack.on('workflow:started', (plan) => {});
toolpack.on('workflow:step_start', (step, plan) => {});
toolpack.on('workflow:step_complete', (step, plan) => {});
toolpack.on('workflow:step_failed', (step, error, plan) => {});
toolpack.on('workflow:progress', (progress) => {});
toolpack.on('workflow:completed', (plan, result) => {});
toolpack.on('workflow:failed', (plan, error) => {});
Client Events
const client = toolpack.getClient();
client.on('tool:progress', (event: ToolProgressEvent) => {});
client.on('tool:log', (event: ToolLogEvent) => {});