toolpack-sdk 2.1.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -4
- package/dist/index.cjs +157 -152
- package/dist/index.d.cts +851 -471
- package/dist/index.d.ts +851 -471
- package/dist/index.js +156 -151
- package/package.json +22 -6
package/dist/index.d.cts
CHANGED
|
@@ -1,4 +1,264 @@
|
|
|
1
|
+
import * as zod from 'zod';
|
|
1
2
|
import { EventEmitter } from 'events';
|
|
3
|
+
import { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
|
|
4
|
+
export { AuthInfo } from '@modelcontextprotocol/sdk/server/auth/types.js';
|
|
5
|
+
|
|
6
|
+
interface PlanStep {
|
|
7
|
+
/** Unique step ID */
|
|
8
|
+
id: string;
|
|
9
|
+
/** Step number (1-indexed) */
|
|
10
|
+
number: number;
|
|
11
|
+
/** Human-readable description */
|
|
12
|
+
description: string;
|
|
13
|
+
/** Expected tools to be used (optional, for validation) */
|
|
14
|
+
expectedTools?: string[];
|
|
15
|
+
/** Dependencies on other step IDs (must complete first) */
|
|
16
|
+
dependsOn?: string[];
|
|
17
|
+
/** Step status */
|
|
18
|
+
status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped';
|
|
19
|
+
/** Result after completion */
|
|
20
|
+
result?: {
|
|
21
|
+
success: boolean;
|
|
22
|
+
output?: string;
|
|
23
|
+
error?: string;
|
|
24
|
+
toolsUsed?: string[];
|
|
25
|
+
duration?: number;
|
|
26
|
+
response?: CompletionResponse;
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
interface Plan {
|
|
30
|
+
/** Unique plan ID */
|
|
31
|
+
id: string;
|
|
32
|
+
/** Original user request */
|
|
33
|
+
request: string;
|
|
34
|
+
/** Plan summary/goal */
|
|
35
|
+
summary: string;
|
|
36
|
+
/** Ordered steps */
|
|
37
|
+
steps: PlanStep[];
|
|
38
|
+
/** Plan status */
|
|
39
|
+
status: 'draft' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'cancelled';
|
|
40
|
+
/** Timestamps */
|
|
41
|
+
createdAt: Date;
|
|
42
|
+
startedAt?: Date;
|
|
43
|
+
completedAt?: Date;
|
|
44
|
+
/** Raw response from the planning phase */
|
|
45
|
+
planningResponse?: CompletionResponse;
|
|
46
|
+
/** Metrics */
|
|
47
|
+
metrics?: {
|
|
48
|
+
totalDuration: number;
|
|
49
|
+
stepsCompleted: number;
|
|
50
|
+
stepsFailed: number;
|
|
51
|
+
retriesUsed: number;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
interface WorkflowConfig {
|
|
56
|
+
/**
|
|
57
|
+
* Workflow name for display purposes.
|
|
58
|
+
*/
|
|
59
|
+
name?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Planning phase configuration.
|
|
62
|
+
* If enabled, AI generates a plan before executing.
|
|
63
|
+
*/
|
|
64
|
+
planning?: {
|
|
65
|
+
/** Enable planning phase. Default: false */
|
|
66
|
+
enabled: boolean;
|
|
67
|
+
/** Pause for user approval before executing plan. Default: false */
|
|
68
|
+
requireApproval?: boolean;
|
|
69
|
+
/** Custom system prompt for plan generation. */
|
|
70
|
+
planningPrompt?: string;
|
|
71
|
+
/** Maximum number of steps allowed in a plan. Default: 20 */
|
|
72
|
+
maxSteps?: number;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Progress reporting configuration.
|
|
76
|
+
*/
|
|
77
|
+
progress?: {
|
|
78
|
+
/** Emit progress events. Default: true */
|
|
79
|
+
enabled: boolean;
|
|
80
|
+
/** Report estimated completion percentage. Default: true */
|
|
81
|
+
reportPercentage?: boolean;
|
|
82
|
+
};
|
|
83
|
+
/**
|
|
84
|
+
* Query complexity routing configuration.
|
|
85
|
+
* Routes simple queries to faster execution paths based on query classification.
|
|
86
|
+
*/
|
|
87
|
+
complexityRouting?: {
|
|
88
|
+
/** Enable complexity-based routing. Default: false (opt-in) */
|
|
89
|
+
enabled: boolean;
|
|
90
|
+
/** Routing strategy for simple queries. Default: 'single-step' */
|
|
91
|
+
strategy: 'single-step' | 'bypass' | 'disabled';
|
|
92
|
+
/** Confidence threshold for routing analytical queries. Default: 0.6 */
|
|
93
|
+
confidenceThreshold?: number;
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Default workflow config (direct execution, no planning).
|
|
98
|
+
*/
|
|
99
|
+
declare const DEFAULT_WORKFLOW_CONFIG: WorkflowConfig;
|
|
100
|
+
interface WorkflowEvents {
|
|
101
|
+
/** Emitted when a plan is created (before approval if required) */
|
|
102
|
+
'workflow:plan_created': (plan: Plan) => void;
|
|
103
|
+
/** Emitted when user approves/rejects a plan */
|
|
104
|
+
'workflow:plan_decision': (plan: Plan, approved: boolean) => void;
|
|
105
|
+
/** Emitted when plan execution starts */
|
|
106
|
+
'workflow:started': (plan: Plan) => void;
|
|
107
|
+
/** Emitted for progress updates */
|
|
108
|
+
'workflow:progress': (progress: WorkflowProgress) => void;
|
|
109
|
+
/** Emitted when context window usage is high (approaching limit) */
|
|
110
|
+
'workflow:context_warning': (event: ContextWindowWarningEvent) => void;
|
|
111
|
+
/** Emitted when context window would be exceeded */
|
|
112
|
+
'workflow:context_exceeded': (event: ContextWindowExceededEvent) => void;
|
|
113
|
+
/** Emitted when messages are pruned to recover context */
|
|
114
|
+
'workflow:context_pruned': (event: ContextPrunedEvent) => void;
|
|
115
|
+
/** Emitted when conversation is summarized for context recovery */
|
|
116
|
+
'workflow:conversation_summarized': (event: ConversationSummarizedEvent) => void;
|
|
117
|
+
/** Emitted when workflow completes */
|
|
118
|
+
'workflow:completed': (plan: Plan, result: WorkflowResult) => void;
|
|
119
|
+
/** Emitted when workflow fails */
|
|
120
|
+
'workflow:failed': (plan: Plan, error: Error) => void;
|
|
121
|
+
}
|
|
122
|
+
interface ContextWindowWarningEvent {
|
|
123
|
+
currentTokens: number;
|
|
124
|
+
contextWindow: number;
|
|
125
|
+
percentage: number;
|
|
126
|
+
model: string;
|
|
127
|
+
conversationId?: string;
|
|
128
|
+
}
|
|
129
|
+
interface ContextWindowExceededEvent {
|
|
130
|
+
currentTokens: number;
|
|
131
|
+
contextWindow: number;
|
|
132
|
+
maxOutputTokens: number;
|
|
133
|
+
model: string;
|
|
134
|
+
strategy: 'prune' | 'summarize' | 'fail';
|
|
135
|
+
conversationId?: string;
|
|
136
|
+
}
|
|
137
|
+
interface ContextPrunedEvent {
|
|
138
|
+
removed: number;
|
|
139
|
+
tokensReclaimed: number;
|
|
140
|
+
newTotal: number;
|
|
141
|
+
conversationId?: string;
|
|
142
|
+
beforeCount: number;
|
|
143
|
+
afterCount: number;
|
|
144
|
+
}
|
|
145
|
+
interface ConversationSummarizedEvent {
|
|
146
|
+
summarized: number;
|
|
147
|
+
summaryTokens: number;
|
|
148
|
+
tokensSaved: number;
|
|
149
|
+
conversationId?: string;
|
|
150
|
+
}
|
|
151
|
+
interface WorkflowProgress {
|
|
152
|
+
planId: string;
|
|
153
|
+
currentStep: number;
|
|
154
|
+
totalSteps: number;
|
|
155
|
+
percentage: number;
|
|
156
|
+
currentStepDescription: string;
|
|
157
|
+
status: 'planning' | 'awaiting_approval' | 'executing' | 'completed' | 'failed';
|
|
158
|
+
}
|
|
159
|
+
interface WorkflowResult {
|
|
160
|
+
success: boolean;
|
|
161
|
+
plan: Plan;
|
|
162
|
+
output?: string;
|
|
163
|
+
error?: string;
|
|
164
|
+
response?: CompletionResponse;
|
|
165
|
+
metrics: {
|
|
166
|
+
totalDuration: number;
|
|
167
|
+
stepsCompleted: number;
|
|
168
|
+
stepsFailed: number;
|
|
169
|
+
retriesUsed: number;
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Configuration for an AI agent mode.
|
|
175
|
+
* A mode shapes AI behavior by controlling which tools are available
|
|
176
|
+
* and injecting a persona-specific system prompt.
|
|
177
|
+
*/
|
|
178
|
+
interface ModeConfig {
|
|
179
|
+
/** Unique identifier for the mode (e.g., "all", "ask", "code") */
|
|
180
|
+
name: string;
|
|
181
|
+
/** Human-readable display name (e.g., "All", "Ask", "Code") */
|
|
182
|
+
displayName: string;
|
|
183
|
+
/** Short description for UI tooltips */
|
|
184
|
+
description: string;
|
|
185
|
+
/**
|
|
186
|
+
* System prompt prepended to every request in this mode.
|
|
187
|
+
* Empty string means no system prompt injection (passthrough).
|
|
188
|
+
*/
|
|
189
|
+
systemPrompt: string;
|
|
190
|
+
/**
|
|
191
|
+
* Base agent context configuration for this mode.
|
|
192
|
+
* Controls whether working directory and tool categories are injected into system prompt.
|
|
193
|
+
*
|
|
194
|
+
* - undefined: Use global default behavior (include everything)
|
|
195
|
+
* - false: Disable base context entirely
|
|
196
|
+
* - object: Fine-grained control over what is included
|
|
197
|
+
*/
|
|
198
|
+
baseContext?: {
|
|
199
|
+
/** Include working directory in system prompt. Default: true */
|
|
200
|
+
includeWorkingDirectory?: boolean;
|
|
201
|
+
/** Include available tool categories. Default: true */
|
|
202
|
+
includeToolCategories?: boolean;
|
|
203
|
+
/** Custom base context string (overrides auto-generated). */
|
|
204
|
+
custom?: string;
|
|
205
|
+
} | false;
|
|
206
|
+
/** Workflow configuration controlling planning, steps, and progress. */
|
|
207
|
+
workflow?: WorkflowConfig;
|
|
208
|
+
/**
|
|
209
|
+
* Tool search configuration specific to this mode.
|
|
210
|
+
* Overrides or extends the global toolSearch config.
|
|
211
|
+
*/
|
|
212
|
+
toolSearch?: {
|
|
213
|
+
/** Enable/disable tool search for this mode */
|
|
214
|
+
enabled?: boolean;
|
|
215
|
+
/** Tools to always include (never defer) for this mode */
|
|
216
|
+
alwaysLoadedTools?: string[];
|
|
217
|
+
/** Categories to always include for this mode */
|
|
218
|
+
alwaysLoadedCategories?: string[];
|
|
219
|
+
};
|
|
220
|
+
/**
|
|
221
|
+
* Tool categories allowed in this mode.
|
|
222
|
+
* Empty array means all categories are allowed (unless blocked).
|
|
223
|
+
*/
|
|
224
|
+
allowedToolCategories: string[];
|
|
225
|
+
/**
|
|
226
|
+
* Tool categories explicitly blocked in this mode.
|
|
227
|
+
* Takes precedence over allowedToolCategories.
|
|
228
|
+
*/
|
|
229
|
+
blockedToolCategories: string[];
|
|
230
|
+
/**
|
|
231
|
+
* Specific tool names allowed in this mode.
|
|
232
|
+
* Empty array means all tools are allowed (unless blocked).
|
|
233
|
+
*/
|
|
234
|
+
allowedTools: string[];
|
|
235
|
+
/**
|
|
236
|
+
* Specific tool names explicitly blocked in this mode.
|
|
237
|
+
* Takes precedence over allowedTools.
|
|
238
|
+
*/
|
|
239
|
+
blockedTools: string[];
|
|
240
|
+
/**
|
|
241
|
+
* If true, ALL tools are blocked regardless of other settings.
|
|
242
|
+
* Shorthand for "no tool calls at all".
|
|
243
|
+
*/
|
|
244
|
+
blockAllTools: boolean;
|
|
245
|
+
/**
|
|
246
|
+
* Response format constraint for all requests in this mode.
|
|
247
|
+
* - 'json_object': instructs the model to return valid JSON as its text content.
|
|
248
|
+
* Useful for evaluator/parser agents whose final response must be machine-readable.
|
|
249
|
+
* Tool-call rounds are unaffected — the model still returns functionCall parts
|
|
250
|
+
* normally; the format only applies to text content.
|
|
251
|
+
* - 'text' (default): plain text, no constraint.
|
|
252
|
+
*/
|
|
253
|
+
response_format?: 'text' | 'json_object';
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* A lightweight reference to a mode, used in tool-blocked hints.
|
|
257
|
+
*/
|
|
258
|
+
interface ModeBlockedHint {
|
|
259
|
+
blockedToolNames: string[];
|
|
260
|
+
suggestedMode: string;
|
|
261
|
+
}
|
|
2
262
|
|
|
3
263
|
/**
|
|
4
264
|
* Core type definitions for the Tool Calling System.
|
|
@@ -26,6 +286,45 @@ interface ToolContext {
|
|
|
26
286
|
/** Scoped logger — writes to toolpack-sdk.log */
|
|
27
287
|
log: (message: string) => void;
|
|
28
288
|
}
|
|
289
|
+
/**
|
|
290
|
+
* Hints about tool behaviour sent to MCP clients in tools/list.
|
|
291
|
+
* All fields are optional — clients use them for safety UX (e.g. confirmation
|
|
292
|
+
* dialogs before destructive actions) but must not rely on them for security.
|
|
293
|
+
*
|
|
294
|
+
* MCP spec defaults when annotations are omitted entirely:
|
|
295
|
+
* readOnlyHint: false, destructiveHint: true, openWorldHint: true, idempotentHint: false
|
|
296
|
+
*
|
|
297
|
+
* The MCP server auto-derives annotations when this field is not set:
|
|
298
|
+
* - confirmation present → { destructiveHint: true }
|
|
299
|
+
* - neither set → annotations omitted (MCP spec defaults apply)
|
|
300
|
+
* Set explicitly to override.
|
|
301
|
+
*/
|
|
302
|
+
interface ToolAnnotations {
|
|
303
|
+
/**
|
|
304
|
+
* Tool only reads data — never writes, calls APIs, or modifies state.
|
|
305
|
+
* MCP spec default (when absent): false.
|
|
306
|
+
* Set to true for pure read tools: fs.read_file, search, list-dir.
|
|
307
|
+
*/
|
|
308
|
+
readOnlyHint?: boolean;
|
|
309
|
+
/**
|
|
310
|
+
* Tool may cause irreversible side-effects (delete, overwrite, deploy, send).
|
|
311
|
+
* MCP spec default (when absent): true — clients assume worst case.
|
|
312
|
+
* Set to false for safe write operations (e.g. create-if-not-exists).
|
|
313
|
+
*/
|
|
314
|
+
destructiveHint?: boolean;
|
|
315
|
+
/**
|
|
316
|
+
* Calling the tool multiple times with the same args has no additional effect.
|
|
317
|
+
* MCP spec default (when absent): false.
|
|
318
|
+
* Set to true for idempotent operations.
|
|
319
|
+
*/
|
|
320
|
+
idempotentHint?: boolean;
|
|
321
|
+
/**
|
|
322
|
+
* Tool may interact with external systems: web, APIs, databases, shell, filesystem.
|
|
323
|
+
* MCP spec default (when absent): true.
|
|
324
|
+
* Set to false only for purely in-process, local tools with no side-effects.
|
|
325
|
+
*/
|
|
326
|
+
openWorldHint?: boolean;
|
|
327
|
+
}
|
|
29
328
|
type ConfirmationLevel$1 = 'high' | 'medium';
|
|
30
329
|
interface ToolConfirmation {
|
|
31
330
|
level: ConfirmationLevel$1;
|
|
@@ -51,6 +350,15 @@ interface ToolDefinition {
|
|
|
51
350
|
* Note: Only effective when onToolConfirm callback is provided to AIClient.
|
|
52
351
|
*/
|
|
53
352
|
confirmation?: ToolConfirmation;
|
|
353
|
+
/**
|
|
354
|
+
* MCP annotation hints describing tool behaviour to clients.
|
|
355
|
+
* When omitted, the MCP server auto-derives from `confirmation`:
|
|
356
|
+
* - confirmation set → { destructiveHint: true }
|
|
357
|
+
* - no confirmation → annotations omitted (MCP spec defaults apply)
|
|
358
|
+
* Set explicitly to override — particularly useful for marking read-only tools
|
|
359
|
+
* (readOnlyHint: true) or idempotent tools (idempotentHint: true).
|
|
360
|
+
*/
|
|
361
|
+
annotations?: ToolAnnotations;
|
|
54
362
|
}
|
|
55
363
|
/**
|
|
56
364
|
* Schema-only version of ToolDefinition (no execute function).
|
|
@@ -68,6 +376,8 @@ interface ToolSchema {
|
|
|
68
376
|
* Default: true
|
|
69
377
|
*/
|
|
70
378
|
cacheable?: boolean;
|
|
379
|
+
/** MCP annotation hints. See ToolAnnotations for details. */
|
|
380
|
+
annotations?: ToolAnnotations;
|
|
71
381
|
}
|
|
72
382
|
interface ToolProjectManifest {
|
|
73
383
|
key: string;
|
|
@@ -227,13 +537,30 @@ interface ToolCallResult {
|
|
|
227
537
|
result?: string;
|
|
228
538
|
duration?: number;
|
|
229
539
|
}
|
|
230
|
-
interface CompletionRequest {
|
|
540
|
+
interface CompletionRequest<T = unknown> {
|
|
231
541
|
messages: Message[];
|
|
232
542
|
model: string;
|
|
233
543
|
temperature?: number;
|
|
234
544
|
max_tokens?: number;
|
|
235
545
|
top_p?: number;
|
|
236
|
-
|
|
546
|
+
/**
|
|
547
|
+
* Controls the output format:
|
|
548
|
+
* - `'text'` — plain text (default)
|
|
549
|
+
* - `'json_object'` — unstructured JSON; you parse `response.content` yourself
|
|
550
|
+
* - `ZodType<T>` — structured JSON matching the schema; parsed and validated result
|
|
551
|
+
* available in `response.data` as fully typed `T`
|
|
552
|
+
*
|
|
553
|
+
* @example structured output
|
|
554
|
+
* ```typescript
|
|
555
|
+
* import { z } from 'zod'
|
|
556
|
+
* const result = await sdk.generate({
|
|
557
|
+
* messages,
|
|
558
|
+
* response_format: z.object({ sentiment: z.string(), score: z.number() }),
|
|
559
|
+
* })
|
|
560
|
+
* result.data.sentiment // typed as string
|
|
561
|
+
* ```
|
|
562
|
+
*/
|
|
563
|
+
response_format?: 'text' | 'json_object' | zod.ZodType<T>;
|
|
237
564
|
stream?: boolean;
|
|
238
565
|
tools?: ToolCallRequest[];
|
|
239
566
|
requestTools?: RequestToolDefinition[];
|
|
@@ -249,14 +576,32 @@ interface CompletionRequest {
|
|
|
249
576
|
* Useful for agents that should only ever make one tool call (e.g. routers).
|
|
250
577
|
*/
|
|
251
578
|
maxToolRounds?: number;
|
|
579
|
+
/**
|
|
580
|
+
* Per-request mode override. Snapshotted for the entire duration of the
|
|
581
|
+
* request — concurrent `setMode()` calls (e.g. from another agent sharing
|
|
582
|
+
* this Toolpack instance during awaited delegation) cannot affect an
|
|
583
|
+
* in-flight request's system prompt, tool filtering, or response format.
|
|
584
|
+
*
|
|
585
|
+
* - `ModeConfig` — use this mode for the request
|
|
586
|
+
* - `string` — mode name, resolved from Toolpack's mode registry
|
|
587
|
+
* - `null` — explicitly run without a mode
|
|
588
|
+
* - omitted — snapshot the instance's active mode at request start
|
|
589
|
+
*/
|
|
590
|
+
mode?: ModeConfig | string | null;
|
|
252
591
|
}
|
|
253
592
|
interface Usage {
|
|
254
593
|
prompt_tokens: number;
|
|
255
594
|
completion_tokens?: number;
|
|
256
595
|
total_tokens: number;
|
|
257
596
|
}
|
|
258
|
-
interface CompletionResponse {
|
|
597
|
+
interface CompletionResponse<T = unknown> {
|
|
259
598
|
content: string | null;
|
|
599
|
+
/**
|
|
600
|
+
* Parsed and validated structured output.
|
|
601
|
+
* Only present when `response_format` is a ZodType.
|
|
602
|
+
* TypeScript type is inferred from the schema via the generic on `generate<T>()`.
|
|
603
|
+
*/
|
|
604
|
+
data?: T;
|
|
260
605
|
usage?: Usage;
|
|
261
606
|
/** Detailed breakdown of token usage when executed in agent/workflow mode */
|
|
262
607
|
usage_details?: {
|
|
@@ -493,520 +838,263 @@ declare class ContextWindowExceededError extends SDKError {
|
|
|
493
838
|
strategy: 'prune' | 'summarize' | 'fail';
|
|
494
839
|
constructor(message: string, conversationId: string, currentTokens: number, contextWindowLimit: number, strategy: 'prune' | 'summarize' | 'fail', cause?: any);
|
|
495
840
|
/**
|
|
496
|
-
* Get the number of tokens over the limit
|
|
497
|
-
*/
|
|
498
|
-
getOverageTokens(): number;
|
|
499
|
-
/**
|
|
500
|
-
* Get the percentage of the context window being used
|
|
501
|
-
*/
|
|
502
|
-
getUsagePercentage(): number;
|
|
503
|
-
/**
|
|
504
|
-
* Get a detailed error report
|
|
505
|
-
*/
|
|
506
|
-
getDetailedReport(): string;
|
|
507
|
-
}
|
|
508
|
-
/**
|
|
509
|
-
* Thrown when there is insufficient context remaining to process a request
|
|
510
|
-
* after pruning or summarization, even though tokens are within limits
|
|
511
|
-
*/
|
|
512
|
-
declare class InsufficientContextError extends SDKError {
|
|
513
|
-
conversationId: string;
|
|
514
|
-
requiredTokens: number;
|
|
515
|
-
availableTokens: number;
|
|
516
|
-
minimumRequiredTokens: number;
|
|
517
|
-
constructor(message: string, conversationId: string, requiredTokens: number, availableTokens: number, minimumRequiredTokens: number, cause?: any);
|
|
518
|
-
/**
|
|
519
|
-
* Get the token deficit
|
|
520
|
-
*/
|
|
521
|
-
getDeficit(): number;
|
|
522
|
-
/**
|
|
523
|
-
* Whether the deficit could be recovered by adjusting the strategy
|
|
524
|
-
*/
|
|
525
|
-
isRecoverable(): boolean;
|
|
526
|
-
/**
|
|
527
|
-
* Get a detailed error report
|
|
528
|
-
*/
|
|
529
|
-
getDetailedReport(): string;
|
|
530
|
-
}
|
|
531
|
-
/**
|
|
532
|
-
* Thrown when summarization fails or produces inadequate results
|
|
533
|
-
*/
|
|
534
|
-
declare class SummarizationError extends SDKError {
|
|
535
|
-
conversationId: string;
|
|
536
|
-
messageCount: number;
|
|
537
|
-
failureReason: 'provider_error' | 'invalid_response' | 'insufficient_tokens' | 'invalid_quality' | 'unknown';
|
|
538
|
-
summaryAttempt?: string | undefined;
|
|
539
|
-
constructor(message: string, conversationId: string, messageCount: number, failureReason: 'provider_error' | 'invalid_response' | 'insufficient_tokens' | 'invalid_quality' | 'unknown', summaryAttempt?: string | undefined, cause?: any);
|
|
540
|
-
/**
|
|
541
|
-
* Whether the error is retryable
|
|
542
|
-
*/
|
|
543
|
-
isRetryable(): boolean;
|
|
544
|
-
/**
|
|
545
|
-
* Get suggested recovery action
|
|
546
|
-
*/
|
|
547
|
-
getSuggestedRecovery(): string;
|
|
548
|
-
/**
|
|
549
|
-
* Get a detailed error report
|
|
550
|
-
*/
|
|
551
|
-
getDetailedReport(): string;
|
|
552
|
-
}
|
|
553
|
-
/**
|
|
554
|
-
* Thrown when context window configuration is invalid
|
|
555
|
-
*/
|
|
556
|
-
declare class ContextWindowConfigError extends SDKError {
|
|
557
|
-
configField: string;
|
|
558
|
-
providedValue: any;
|
|
559
|
-
constraint: string;
|
|
560
|
-
constructor(message: string, configField: string, providedValue: any, constraint: string, cause?: any);
|
|
561
|
-
/**
|
|
562
|
-
* Get a detailed error report
|
|
563
|
-
*/
|
|
564
|
-
getDetailedReport(): string;
|
|
565
|
-
}
|
|
566
|
-
/**
|
|
567
|
-
* Thrown when a state operation is performed on a non-existent conversation
|
|
568
|
-
*/
|
|
569
|
-
declare class ConversationNotFoundError extends SDKError {
|
|
570
|
-
conversationId: string;
|
|
571
|
-
constructor(message: string, conversationId: string, cause?: any);
|
|
572
|
-
}
|
|
573
|
-
/**
|
|
574
|
-
* Utility function to check if an error is context window related
|
|
575
|
-
*/
|
|
576
|
-
declare function isContextWindowError(error: any): error is SDKError & {
|
|
577
|
-
code: string;
|
|
578
|
-
};
|
|
579
|
-
/**
|
|
580
|
-
* Utility function to handle context window errors
|
|
581
|
-
*/
|
|
582
|
-
declare function handleContextWindowError(error: SDKError, _conversationId?: string): {
|
|
583
|
-
shouldRetry: boolean;
|
|
584
|
-
shouldFallback: boolean;
|
|
585
|
-
action: 'prune' | 'summarize' | 'fail' | 'none';
|
|
586
|
-
message: string;
|
|
587
|
-
};
|
|
588
|
-
|
|
589
|
-
declare abstract class ProviderAdapter {
|
|
590
|
-
/**
|
|
591
|
-
* Provider name used for registration and routing.
|
|
592
|
-
* Custom adapters should set this in their constructor.
|
|
593
|
-
*/
|
|
594
|
-
name?: string;
|
|
595
|
-
/**
|
|
596
|
-
* Generates a text completion for the given request.
|
|
597
|
-
*/
|
|
598
|
-
abstract generate(request: CompletionRequest): Promise<CompletionResponse>;
|
|
599
|
-
/**
|
|
600
|
-
* Streams text completion chunks for the given request.
|
|
601
|
-
*/
|
|
602
|
-
abstract stream(request: CompletionRequest): AsyncGenerator<CompletionChunk>;
|
|
603
|
-
/**
|
|
604
|
-
* Generates embeddings for the given input.
|
|
605
|
-
*/
|
|
606
|
-
abstract embed(request: EmbeddingRequest): Promise<EmbeddingResponse>;
|
|
607
|
-
/**
|
|
608
|
-
* Optional: Provide image generation if supported.
|
|
609
|
-
* Defined as any for now to avoid circular deps or complex types in base.
|
|
610
|
-
*/
|
|
611
|
-
/**
|
|
612
|
-
* Returns the list of models available from this provider.
|
|
613
|
-
* Override to provide a curated list or fetch from the provider's API.
|
|
614
|
-
*
|
|
615
|
-
* Default: returns an empty array.
|
|
616
|
-
*/
|
|
617
|
-
getModels(): Promise<ProviderModelInfo[]>;
|
|
618
|
-
/**
|
|
619
|
-
* Returns a human-readable display name for this provider.
|
|
620
|
-
* Override to customize.
|
|
621
|
-
*
|
|
622
|
-
* Default: uses `this.name` if set, otherwise derives from class name.
|
|
623
|
-
*/
|
|
624
|
-
getDisplayName(): string;
|
|
625
|
-
/**
|
|
626
|
-
* Check if this provider supports the file upload API natively.
|
|
627
|
-
*/
|
|
628
|
-
supportsFileUpload(): boolean;
|
|
629
|
-
/**
|
|
630
|
-
* Upload a file to the provider (if supported).
|
|
631
|
-
* @throws InvalidRequestError if not supported by this provider.
|
|
632
|
-
*/
|
|
633
|
-
uploadFile(_request: FileUploadRequest): Promise<FileUploadResponse>;
|
|
634
|
-
/**
|
|
635
|
-
* Delete an uploaded file (if supported).
|
|
636
|
-
* @throws InvalidRequestError if not supported by this provider.
|
|
637
|
-
*/
|
|
638
|
-
deleteFile(_fileId: string): Promise<void>;
|
|
639
|
-
/**
|
|
640
|
-
* Estimates the number of tokens for the given messages and model.
|
|
641
|
-
* @param _messages The messages to count.
|
|
642
|
-
* @param _model The model to count for.
|
|
643
|
-
* @returns The number of tokens or null if not supported.
|
|
644
|
-
*/
|
|
645
|
-
countTokens(_messages: Message[], _model: string): Promise<number | null>;
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
/**
|
|
649
|
-
* Central registry for all tools (built-in + custom).
|
|
650
|
-
* Handles registration, lookup, filtering by category, schema extraction,
|
|
651
|
-
* and loading tool projects.
|
|
652
|
-
*/
|
|
653
|
-
declare class ToolRegistry {
|
|
654
|
-
private tools;
|
|
655
|
-
private projects;
|
|
656
|
-
private config;
|
|
657
|
-
/**
|
|
658
|
-
* Register a tool (built-in or custom).
|
|
659
|
-
*/
|
|
660
|
-
register(tool: ToolDefinition): void;
|
|
661
|
-
/**
|
|
662
|
-
* Register a custom tool provided by the consumer.
|
|
663
|
-
* Identical to register() but semantically distinct for clarity.
|
|
664
|
-
*/
|
|
665
|
-
registerCustom(tool: ToolDefinition): void;
|
|
666
|
-
/**
|
|
667
|
-
* Get a tool by name.
|
|
668
|
-
*/
|
|
669
|
-
get(name: string): ToolDefinition | undefined;
|
|
670
|
-
/**
|
|
671
|
-
* Check if a tool exists.
|
|
672
|
-
*/
|
|
673
|
-
has(name: string): boolean;
|
|
674
|
-
/**
|
|
675
|
-
* Get all registered tool names.
|
|
676
|
-
*/
|
|
677
|
-
getNames(): string[];
|
|
678
|
-
/**
|
|
679
|
-
* Get all tools in a specific category.
|
|
680
|
-
*/
|
|
681
|
-
getByCategory(category: string): ToolDefinition[];
|
|
682
|
-
/**
|
|
683
|
-
* Get all enabled tools based on config.
|
|
684
|
-
* If enabledTools and enabledToolCategories are both empty, returns all registered tools.
|
|
685
|
-
* Otherwise, returns only tools from enabledTools[] + enabledToolCategories[].
|
|
686
|
-
*/
|
|
687
|
-
getEnabled(): ToolDefinition[];
|
|
688
|
-
/**
|
|
689
|
-
* Get tool schemas suitable for sending to AI providers.
|
|
690
|
-
* If toolNames is provided, only return schemas for those tools.
|
|
691
|
-
* Otherwise, return schemas for all enabled tools.
|
|
692
|
-
*/
|
|
693
|
-
getSchemas(toolNames?: string[]): ToolSchema[];
|
|
694
|
-
/**
|
|
695
|
-
* Get all tools matching a list of names.
|
|
696
|
-
*/
|
|
697
|
-
getByNames(names: string[]): ToolDefinition[];
|
|
698
|
-
/**
|
|
699
|
-
* Get all tools matching a list of categories.
|
|
700
|
-
*/
|
|
701
|
-
getByCategories(categories: string[]): ToolDefinition[];
|
|
702
|
-
/**
|
|
703
|
-
* Get all registered categories (derived from tools).
|
|
704
|
-
*/
|
|
705
|
-
getCategories(): string[];
|
|
706
|
-
/**
|
|
707
|
-
* Get all registered tools.
|
|
708
|
-
* Used by BM25SearchEngine for indexing.
|
|
709
|
-
*/
|
|
710
|
-
getAll(): ToolDefinition[];
|
|
711
|
-
/**
|
|
712
|
-
* Update the config (called by config loader).
|
|
841
|
+
* Get the number of tokens over the limit
|
|
713
842
|
*/
|
|
714
|
-
|
|
843
|
+
getOverageTokens(): number;
|
|
715
844
|
/**
|
|
716
|
-
* Get the
|
|
845
|
+
* Get the percentage of the context window being used
|
|
717
846
|
*/
|
|
718
|
-
|
|
847
|
+
getUsagePercentage(): number;
|
|
719
848
|
/**
|
|
720
|
-
* Get
|
|
849
|
+
* Get a detailed error report
|
|
721
850
|
*/
|
|
722
|
-
|
|
851
|
+
getDetailedReport(): string;
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Thrown when there is insufficient context remaining to process a request
|
|
855
|
+
* after pruning or summarization, even though tokens are within limits
|
|
856
|
+
*/
|
|
857
|
+
declare class InsufficientContextError extends SDKError {
|
|
858
|
+
conversationId: string;
|
|
859
|
+
requiredTokens: number;
|
|
860
|
+
availableTokens: number;
|
|
861
|
+
minimumRequiredTokens: number;
|
|
862
|
+
constructor(message: string, conversationId: string, requiredTokens: number, availableTokens: number, minimumRequiredTokens: number, cause?: any);
|
|
723
863
|
/**
|
|
724
|
-
*
|
|
725
|
-
* Returns an array of missing package names (empty = all good).
|
|
864
|
+
* Get the token deficit
|
|
726
865
|
*/
|
|
727
|
-
|
|
866
|
+
getDeficit(): number;
|
|
728
867
|
/**
|
|
729
|
-
*
|
|
730
|
-
* Validates dependencies before loading — throws if any are missing.
|
|
868
|
+
* Whether the deficit could be recovered by adjusting the strategy
|
|
731
869
|
*/
|
|
732
|
-
|
|
870
|
+
isRecoverable(): boolean;
|
|
733
871
|
/**
|
|
734
|
-
*
|
|
872
|
+
* Get a detailed error report
|
|
735
873
|
*/
|
|
736
|
-
|
|
874
|
+
getDetailedReport(): string;
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* Thrown when summarization fails or produces inadequate results
|
|
878
|
+
*/
|
|
879
|
+
declare class SummarizationError extends SDKError {
|
|
880
|
+
conversationId: string;
|
|
881
|
+
messageCount: number;
|
|
882
|
+
failureReason: 'provider_error' | 'invalid_response' | 'insufficient_tokens' | 'invalid_quality' | 'unknown';
|
|
883
|
+
summaryAttempt?: string | undefined;
|
|
884
|
+
constructor(message: string, conversationId: string, messageCount: number, failureReason: 'provider_error' | 'invalid_response' | 'insufficient_tokens' | 'invalid_quality' | 'unknown', summaryAttempt?: string | undefined, cause?: any);
|
|
737
885
|
/**
|
|
738
|
-
*
|
|
886
|
+
* Whether the error is retryable
|
|
739
887
|
*/
|
|
740
|
-
|
|
888
|
+
isRetryable(): boolean;
|
|
741
889
|
/**
|
|
742
|
-
* Get
|
|
890
|
+
* Get suggested recovery action
|
|
743
891
|
*/
|
|
744
|
-
|
|
892
|
+
getSuggestedRecovery(): string;
|
|
745
893
|
/**
|
|
746
|
-
* Get
|
|
894
|
+
* Get a detailed error report
|
|
747
895
|
*/
|
|
748
|
-
|
|
896
|
+
getDetailedReport(): string;
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Thrown when context window configuration is invalid
|
|
900
|
+
*/
|
|
901
|
+
declare class ContextWindowConfigError extends SDKError {
|
|
902
|
+
configField: string;
|
|
903
|
+
providedValue: any;
|
|
904
|
+
constraint: string;
|
|
905
|
+
constructor(message: string, configField: string, providedValue: any, constraint: string, cause?: any);
|
|
749
906
|
/**
|
|
750
|
-
*
|
|
907
|
+
* Get a detailed error report
|
|
751
908
|
*/
|
|
752
|
-
|
|
753
|
-
}
|
|
754
|
-
|
|
755
|
-
interface PlanStep {
|
|
756
|
-
/** Unique step ID */
|
|
757
|
-
id: string;
|
|
758
|
-
/** Step number (1-indexed) */
|
|
759
|
-
number: number;
|
|
760
|
-
/** Human-readable description */
|
|
761
|
-
description: string;
|
|
762
|
-
/** Expected tools to be used (optional, for validation) */
|
|
763
|
-
expectedTools?: string[];
|
|
764
|
-
/** Dependencies on other step IDs (must complete first) */
|
|
765
|
-
dependsOn?: string[];
|
|
766
|
-
/** Step status */
|
|
767
|
-
status: 'pending' | 'in_progress' | 'completed' | 'failed' | 'skipped';
|
|
768
|
-
/** Result after completion */
|
|
769
|
-
result?: {
|
|
770
|
-
success: boolean;
|
|
771
|
-
output?: string;
|
|
772
|
-
error?: string;
|
|
773
|
-
toolsUsed?: string[];
|
|
774
|
-
duration?: number;
|
|
775
|
-
response?: CompletionResponse;
|
|
776
|
-
};
|
|
909
|
+
getDetailedReport(): string;
|
|
777
910
|
}
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
summary: string;
|
|
785
|
-
/** Ordered steps */
|
|
786
|
-
steps: PlanStep[];
|
|
787
|
-
/** Plan status */
|
|
788
|
-
status: 'draft' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'cancelled';
|
|
789
|
-
/** Timestamps */
|
|
790
|
-
createdAt: Date;
|
|
791
|
-
startedAt?: Date;
|
|
792
|
-
completedAt?: Date;
|
|
793
|
-
/** Raw response from the planning phase */
|
|
794
|
-
planningResponse?: CompletionResponse;
|
|
795
|
-
/** Metrics */
|
|
796
|
-
metrics?: {
|
|
797
|
-
totalDuration: number;
|
|
798
|
-
stepsCompleted: number;
|
|
799
|
-
stepsFailed: number;
|
|
800
|
-
retriesUsed: number;
|
|
801
|
-
};
|
|
911
|
+
/**
|
|
912
|
+
* Thrown when a state operation is performed on a non-existent conversation
|
|
913
|
+
*/
|
|
914
|
+
declare class ConversationNotFoundError extends SDKError {
|
|
915
|
+
conversationId: string;
|
|
916
|
+
constructor(message: string, conversationId: string, cause?: any);
|
|
802
917
|
}
|
|
918
|
+
/**
|
|
919
|
+
* Utility function to check if an error is context window related
|
|
920
|
+
*/
|
|
921
|
+
declare function isContextWindowError(error: any): error is SDKError & {
|
|
922
|
+
code: string;
|
|
923
|
+
};
|
|
924
|
+
/**
|
|
925
|
+
* Utility function to handle context window errors
|
|
926
|
+
*/
|
|
927
|
+
declare function handleContextWindowError(error: SDKError, _conversationId?: string): {
|
|
928
|
+
shouldRetry: boolean;
|
|
929
|
+
shouldFallback: boolean;
|
|
930
|
+
action: 'prune' | 'summarize' | 'fail' | 'none';
|
|
931
|
+
message: string;
|
|
932
|
+
};
|
|
803
933
|
|
|
804
|
-
|
|
934
|
+
declare abstract class ProviderAdapter {
|
|
805
935
|
/**
|
|
806
|
-
*
|
|
936
|
+
* Provider name used for registration and routing.
|
|
937
|
+
* Custom adapters should set this in their constructor.
|
|
807
938
|
*/
|
|
808
939
|
name?: string;
|
|
809
940
|
/**
|
|
810
|
-
*
|
|
811
|
-
* If enabled, AI generates a plan before executing.
|
|
812
|
-
*/
|
|
813
|
-
planning?: {
|
|
814
|
-
/** Enable planning phase. Default: false */
|
|
815
|
-
enabled: boolean;
|
|
816
|
-
/** Pause for user approval before executing plan. Default: false */
|
|
817
|
-
requireApproval?: boolean;
|
|
818
|
-
/** Custom system prompt for plan generation. */
|
|
819
|
-
planningPrompt?: string;
|
|
820
|
-
/** Maximum number of steps allowed in a plan. Default: 20 */
|
|
821
|
-
maxSteps?: number;
|
|
822
|
-
};
|
|
823
|
-
/**
|
|
824
|
-
* Progress reporting configuration.
|
|
941
|
+
* Generates a text completion for the given request.
|
|
825
942
|
*/
|
|
826
|
-
|
|
827
|
-
/** Emit progress events. Default: true */
|
|
828
|
-
enabled: boolean;
|
|
829
|
-
/** Report estimated completion percentage. Default: true */
|
|
830
|
-
reportPercentage?: boolean;
|
|
831
|
-
};
|
|
943
|
+
abstract generate(request: CompletionRequest): Promise<CompletionResponse>;
|
|
832
944
|
/**
|
|
833
|
-
*
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
/**
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
/**
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
currentTokens: number;
|
|
880
|
-
contextWindow: number;
|
|
881
|
-
maxOutputTokens: number;
|
|
882
|
-
model: string;
|
|
883
|
-
strategy: 'prune' | 'summarize' | 'fail';
|
|
884
|
-
conversationId?: string;
|
|
885
|
-
}
|
|
886
|
-
interface ContextPrunedEvent {
|
|
887
|
-
removed: number;
|
|
888
|
-
tokensReclaimed: number;
|
|
889
|
-
newTotal: number;
|
|
890
|
-
conversationId?: string;
|
|
891
|
-
beforeCount: number;
|
|
892
|
-
afterCount: number;
|
|
893
|
-
}
|
|
894
|
-
interface ConversationSummarizedEvent {
|
|
895
|
-
summarized: number;
|
|
896
|
-
summaryTokens: number;
|
|
897
|
-
tokensSaved: number;
|
|
898
|
-
conversationId?: string;
|
|
899
|
-
}
|
|
900
|
-
interface WorkflowProgress {
|
|
901
|
-
planId: string;
|
|
902
|
-
currentStep: number;
|
|
903
|
-
totalSteps: number;
|
|
904
|
-
percentage: number;
|
|
905
|
-
currentStepDescription: string;
|
|
906
|
-
status: 'planning' | 'awaiting_approval' | 'executing' | 'completed' | 'failed';
|
|
907
|
-
}
|
|
908
|
-
interface WorkflowResult {
|
|
909
|
-
success: boolean;
|
|
910
|
-
plan: Plan;
|
|
911
|
-
output?: string;
|
|
912
|
-
error?: string;
|
|
913
|
-
response?: CompletionResponse;
|
|
914
|
-
metrics: {
|
|
915
|
-
totalDuration: number;
|
|
916
|
-
stepsCompleted: number;
|
|
917
|
-
stepsFailed: number;
|
|
918
|
-
retriesUsed: number;
|
|
919
|
-
};
|
|
945
|
+
* Streams text completion chunks for the given request.
|
|
946
|
+
*/
|
|
947
|
+
abstract stream(request: CompletionRequest): AsyncGenerator<CompletionChunk>;
|
|
948
|
+
/**
|
|
949
|
+
* Generates embeddings for the given input.
|
|
950
|
+
*/
|
|
951
|
+
abstract embed(request: EmbeddingRequest): Promise<EmbeddingResponse>;
|
|
952
|
+
/**
|
|
953
|
+
* Optional: Provide image generation if supported.
|
|
954
|
+
* Defined as any for now to avoid circular deps or complex types in base.
|
|
955
|
+
*/
|
|
956
|
+
/**
|
|
957
|
+
* Returns the list of models available from this provider.
|
|
958
|
+
* Override to provide a curated list or fetch from the provider's API.
|
|
959
|
+
*
|
|
960
|
+
* Default: returns an empty array.
|
|
961
|
+
*/
|
|
962
|
+
getModels(): Promise<ProviderModelInfo[]>;
|
|
963
|
+
/**
|
|
964
|
+
* Returns a human-readable display name for this provider.
|
|
965
|
+
* Override to customize.
|
|
966
|
+
*
|
|
967
|
+
* Default: uses `this.name` if set, otherwise derives from class name.
|
|
968
|
+
*/
|
|
969
|
+
getDisplayName(): string;
|
|
970
|
+
/**
|
|
971
|
+
* Check if this provider supports the file upload API natively.
|
|
972
|
+
*/
|
|
973
|
+
supportsFileUpload(): boolean;
|
|
974
|
+
/**
|
|
975
|
+
* Upload a file to the provider (if supported).
|
|
976
|
+
* @throws InvalidRequestError if not supported by this provider.
|
|
977
|
+
*/
|
|
978
|
+
uploadFile(_request: FileUploadRequest): Promise<FileUploadResponse>;
|
|
979
|
+
/**
|
|
980
|
+
* Delete an uploaded file (if supported).
|
|
981
|
+
* @throws InvalidRequestError if not supported by this provider.
|
|
982
|
+
*/
|
|
983
|
+
deleteFile(_fileId: string): Promise<void>;
|
|
984
|
+
/**
|
|
985
|
+
* Estimates the number of tokens for the given messages and model.
|
|
986
|
+
* @param _messages The messages to count.
|
|
987
|
+
* @param _model The model to count for.
|
|
988
|
+
* @returns The number of tokens or null if not supported.
|
|
989
|
+
*/
|
|
990
|
+
countTokens(_messages: Message[], _model: string): Promise<number | null>;
|
|
920
991
|
}
|
|
921
992
|
|
|
922
993
|
/**
|
|
923
|
-
*
|
|
924
|
-
*
|
|
925
|
-
* and
|
|
994
|
+
* Central registry for all tools (built-in + custom).
|
|
995
|
+
* Handles registration, lookup, filtering by category, schema extraction,
|
|
996
|
+
* and loading tool projects.
|
|
926
997
|
*/
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
displayName: string;
|
|
932
|
-
/** Short description for UI tooltips */
|
|
933
|
-
description: string;
|
|
998
|
+
declare class ToolRegistry {
|
|
999
|
+
private tools;
|
|
1000
|
+
private projects;
|
|
1001
|
+
private config;
|
|
934
1002
|
/**
|
|
935
|
-
*
|
|
936
|
-
* Empty string means no system prompt injection (passthrough).
|
|
1003
|
+
* Register a tool (built-in or custom).
|
|
937
1004
|
*/
|
|
938
|
-
|
|
1005
|
+
register(tool: ToolDefinition): void;
|
|
939
1006
|
/**
|
|
940
|
-
*
|
|
941
|
-
*
|
|
942
|
-
*
|
|
943
|
-
* - undefined: Use global default behavior (include everything)
|
|
944
|
-
* - false: Disable base context entirely
|
|
945
|
-
* - object: Fine-grained control over what is included
|
|
1007
|
+
* Register a custom tool provided by the consumer.
|
|
1008
|
+
* Identical to register() but semantically distinct for clarity.
|
|
946
1009
|
*/
|
|
947
|
-
|
|
948
|
-
/** Include working directory in system prompt. Default: true */
|
|
949
|
-
includeWorkingDirectory?: boolean;
|
|
950
|
-
/** Include available tool categories. Default: true */
|
|
951
|
-
includeToolCategories?: boolean;
|
|
952
|
-
/** Custom base context string (overrides auto-generated). */
|
|
953
|
-
custom?: string;
|
|
954
|
-
} | false;
|
|
955
|
-
/** Workflow configuration controlling planning, steps, and progress. */
|
|
956
|
-
workflow?: WorkflowConfig;
|
|
1010
|
+
registerCustom(tool: ToolDefinition): void;
|
|
957
1011
|
/**
|
|
958
|
-
*
|
|
959
|
-
* Overrides or extends the global toolSearch config.
|
|
1012
|
+
* Get a tool by name.
|
|
960
1013
|
*/
|
|
961
|
-
|
|
962
|
-
/** Enable/disable tool search for this mode */
|
|
963
|
-
enabled?: boolean;
|
|
964
|
-
/** Tools to always include (never defer) for this mode */
|
|
965
|
-
alwaysLoadedTools?: string[];
|
|
966
|
-
/** Categories to always include for this mode */
|
|
967
|
-
alwaysLoadedCategories?: string[];
|
|
968
|
-
};
|
|
1014
|
+
get(name: string): ToolDefinition | undefined;
|
|
969
1015
|
/**
|
|
970
|
-
*
|
|
971
|
-
* Empty array means all categories are allowed (unless blocked).
|
|
1016
|
+
* Check if a tool exists.
|
|
972
1017
|
*/
|
|
973
|
-
|
|
1018
|
+
has(name: string): boolean;
|
|
974
1019
|
/**
|
|
975
|
-
*
|
|
976
|
-
* Takes precedence over allowedToolCategories.
|
|
1020
|
+
* Get all registered tool names.
|
|
977
1021
|
*/
|
|
978
|
-
|
|
1022
|
+
getNames(): string[];
|
|
979
1023
|
/**
|
|
980
|
-
*
|
|
981
|
-
* Empty array means all tools are allowed (unless blocked).
|
|
1024
|
+
* Get all tools in a specific category.
|
|
982
1025
|
*/
|
|
983
|
-
|
|
1026
|
+
getByCategory(category: string): ToolDefinition[];
|
|
984
1027
|
/**
|
|
985
|
-
*
|
|
986
|
-
*
|
|
1028
|
+
* Get all enabled tools based on config.
|
|
1029
|
+
* If enabledTools and enabledToolCategories are both empty, returns all registered tools.
|
|
1030
|
+
* Otherwise, returns only tools from enabledTools[] + enabledToolCategories[].
|
|
987
1031
|
*/
|
|
988
|
-
|
|
1032
|
+
getEnabled(): ToolDefinition[];
|
|
989
1033
|
/**
|
|
990
|
-
*
|
|
991
|
-
*
|
|
1034
|
+
* Get tool schemas suitable for sending to AI providers.
|
|
1035
|
+
* If toolNames is provided, only return schemas for those tools.
|
|
1036
|
+
* Otherwise, return schemas for all enabled tools.
|
|
992
1037
|
*/
|
|
993
|
-
|
|
1038
|
+
getSchemas(toolNames?: string[]): ToolSchema[];
|
|
994
1039
|
/**
|
|
995
|
-
*
|
|
996
|
-
* - 'json_object': instructs the model to return valid JSON as its text content.
|
|
997
|
-
* Useful for evaluator/parser agents whose final response must be machine-readable.
|
|
998
|
-
* Tool-call rounds are unaffected — the model still returns functionCall parts
|
|
999
|
-
* normally; the format only applies to text content.
|
|
1000
|
-
* - 'text' (default): plain text, no constraint.
|
|
1040
|
+
* Get all tools matching a list of names.
|
|
1001
1041
|
*/
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1042
|
+
getByNames(names: string[]): ToolDefinition[];
|
|
1043
|
+
/**
|
|
1044
|
+
* Get all tools matching a list of categories.
|
|
1045
|
+
*/
|
|
1046
|
+
getByCategories(categories: string[]): ToolDefinition[];
|
|
1047
|
+
/**
|
|
1048
|
+
* Get all registered categories (derived from tools).
|
|
1049
|
+
*/
|
|
1050
|
+
getCategories(): string[];
|
|
1051
|
+
/**
|
|
1052
|
+
* Get all registered tools.
|
|
1053
|
+
* Used by BM25SearchEngine for indexing.
|
|
1054
|
+
*/
|
|
1055
|
+
getAll(): ToolDefinition[];
|
|
1056
|
+
/**
|
|
1057
|
+
* Update the config (called by config loader).
|
|
1058
|
+
*/
|
|
1059
|
+
setConfig(config: ToolsConfig): void;
|
|
1060
|
+
/**
|
|
1061
|
+
* Get the current config.
|
|
1062
|
+
*/
|
|
1063
|
+
getConfig(): ToolsConfig;
|
|
1064
|
+
/**
|
|
1065
|
+
* Get the total number of registered tools.
|
|
1066
|
+
*/
|
|
1067
|
+
get size(): number;
|
|
1068
|
+
/**
|
|
1069
|
+
* Validate that a tool project's declared dependencies are resolvable.
|
|
1070
|
+
* Returns an array of missing package names (empty = all good).
|
|
1071
|
+
*/
|
|
1072
|
+
validateDependencies(project: ToolProject): Promise<string[]>;
|
|
1073
|
+
/**
|
|
1074
|
+
* Load a single tool project into the registry.
|
|
1075
|
+
* Validates dependencies before loading — throws if any are missing.
|
|
1076
|
+
*/
|
|
1077
|
+
loadProject(project: ToolProject): Promise<void>;
|
|
1078
|
+
/**
|
|
1079
|
+
* Load multiple tool projects.
|
|
1080
|
+
*/
|
|
1081
|
+
loadProjects(projects: ToolProject[]): Promise<void>;
|
|
1082
|
+
/**
|
|
1083
|
+
* Get a loaded project by name.
|
|
1084
|
+
*/
|
|
1085
|
+
getProject(name: string): ToolProject | undefined;
|
|
1086
|
+
/**
|
|
1087
|
+
* Get all loaded projects.
|
|
1088
|
+
*/
|
|
1089
|
+
getProjects(): ToolProject[];
|
|
1090
|
+
/**
|
|
1091
|
+
* Get all loaded project names.
|
|
1092
|
+
*/
|
|
1093
|
+
getProjectNames(): string[];
|
|
1094
|
+
/**
|
|
1095
|
+
* Load all built-in tool projects.
|
|
1096
|
+
*/
|
|
1097
|
+
loadBuiltIn(): Promise<void>;
|
|
1010
1098
|
}
|
|
1011
1099
|
|
|
1012
1100
|
type ConfirmationLevel = 'high' | 'medium';
|
|
@@ -1251,7 +1339,7 @@ declare class AIClient extends EventEmitter {
|
|
|
1251
1339
|
* When tools are enabled and autoExecute is true, handles the full
|
|
1252
1340
|
* tool call → execute → send result → get final answer loop.
|
|
1253
1341
|
*/
|
|
1254
|
-
generate(request: CompletionRequest
|
|
1342
|
+
generate<T = unknown>(request: CompletionRequest<T>, providerName?: string): Promise<CompletionResponse<T>>;
|
|
1255
1343
|
/**
|
|
1256
1344
|
* unified stream completion
|
|
1257
1345
|
* When tools are enabled and autoExecute is true, handles tool calls
|
|
@@ -1266,6 +1354,11 @@ declare class AIClient extends EventEmitter {
|
|
|
1266
1354
|
* Enrich a request with tools based on the router config.
|
|
1267
1355
|
* Applies mode-based tool filtering when an active mode is set.
|
|
1268
1356
|
*/
|
|
1357
|
+
/**
|
|
1358
|
+
* @param mode Mode snapshot taken at request start. Passed explicitly (not
|
|
1359
|
+
* read from `this.activeMode`) so that per-round re-enrichment inside the
|
|
1360
|
+
* tool loop is immune to concurrent `setMode()` calls on this instance.
|
|
1361
|
+
*/
|
|
1269
1362
|
private enrichRequestWithTools;
|
|
1270
1363
|
private buildRequestToolMap;
|
|
1271
1364
|
private requestToolToSchema;
|
|
@@ -1274,13 +1367,24 @@ declare class AIClient extends EventEmitter {
|
|
|
1274
1367
|
private mergeToolCallRequests;
|
|
1275
1368
|
private injectRequestToolGuidance;
|
|
1276
1369
|
private stripRequestTools;
|
|
1370
|
+
/**
|
|
1371
|
+
* Resolve the mode snapshot for a request.
|
|
1372
|
+
*
|
|
1373
|
+
* - `request.mode` omitted → snapshot the instance's activeMode now
|
|
1374
|
+
* - `request.mode === null` → explicitly no mode
|
|
1375
|
+
* - `request.mode` is a ModeConfig → use it directly
|
|
1376
|
+
* - `request.mode` is a string → mode names are resolved by Toolpack (which
|
|
1377
|
+
* owns the mode registry) before reaching the client; if an unresolved
|
|
1378
|
+
* name gets here, warn and fall back to the activeMode snapshot
|
|
1379
|
+
*/
|
|
1380
|
+
private resolveRequestMode;
|
|
1277
1381
|
/**
|
|
1278
1382
|
* Filter tool schemas based on mode permissions.
|
|
1279
1383
|
* blockedTools/blockedToolCategories always take precedence.
|
|
1280
1384
|
*/
|
|
1281
1385
|
private filterSchemasByMode;
|
|
1282
1386
|
/**
|
|
1283
|
-
* Inject the
|
|
1387
|
+
* Inject the given mode's system prompt into the request messages.
|
|
1284
1388
|
* For the "All" mode (empty systemPrompt), this is a no-op.
|
|
1285
1389
|
*/
|
|
1286
1390
|
private injectModeSystemPrompt;
|
|
@@ -1314,7 +1418,7 @@ declare class AIClient extends EventEmitter {
|
|
|
1314
1418
|
/**
|
|
1315
1419
|
* Execute tool.search using BM25 engine.
|
|
1316
1420
|
*/
|
|
1317
|
-
|
|
1421
|
+
executeToolSearch(args: Record<string, any>, mode?: ModeConfig | null): string;
|
|
1318
1422
|
private wrapError;
|
|
1319
1423
|
/**
|
|
1320
1424
|
* Truncate a tool result to fit within the remaining round budget.
|
|
@@ -2072,8 +2176,12 @@ declare const execRunShellTool: ToolDefinition;
|
|
|
2072
2176
|
|
|
2073
2177
|
declare const execRunBackgroundTool: ToolDefinition;
|
|
2074
2178
|
|
|
2179
|
+
declare const execRunBlockingTool: ToolDefinition;
|
|
2180
|
+
|
|
2075
2181
|
declare const execReadOutputTool: ToolDefinition;
|
|
2076
2182
|
|
|
2183
|
+
declare const execTailOutputTool: ToolDefinition;
|
|
2184
|
+
|
|
2077
2185
|
declare const execKillTool: ToolDefinition;
|
|
2078
2186
|
|
|
2079
2187
|
declare const execListProcessesTool: ToolDefinition;
|
|
@@ -2588,6 +2696,210 @@ type ToolpackInterceptor = {
|
|
|
2588
2696
|
init?(): Promise<void>;
|
|
2589
2697
|
};
|
|
2590
2698
|
|
|
2699
|
+
type McpTransport = 'stdio' | 'http';
|
|
2700
|
+
|
|
2701
|
+
interface McpServerExposeConfig {
|
|
2702
|
+
/** Expose only tools in these categories. Mutually exclusive with `tools`. */
|
|
2703
|
+
categories?: string[];
|
|
2704
|
+
/** Expose only these exact tool names. Mutually exclusive with `categories`. */
|
|
2705
|
+
tools?: string[];
|
|
2706
|
+
}
|
|
2707
|
+
interface McpStaticAuthConfig {
|
|
2708
|
+
mode: 'static';
|
|
2709
|
+
/**
|
|
2710
|
+
* One or more pre-shared bearer tokens that grant access.
|
|
2711
|
+
* Generate with: crypto.randomBytes(32).toString('hex')
|
|
2712
|
+
* All tokens in the array are valid — useful for token rotation.
|
|
2713
|
+
*/
|
|
2714
|
+
tokens: string[];
|
|
2715
|
+
}
|
|
2716
|
+
interface McpJwtAuthConfig {
|
|
2717
|
+
mode: 'jwt';
|
|
2718
|
+
/**
|
|
2719
|
+
* JWKS endpoint URL for JWT signature verification.
|
|
2720
|
+
* @example 'https://your-tenant.auth0.com/.well-known/jwks.json'
|
|
2721
|
+
* @example 'https://your-project.supabase.co/auth/v1/jwks'
|
|
2722
|
+
*/
|
|
2723
|
+
jwksUrl: string;
|
|
2724
|
+
/**
|
|
2725
|
+
* Expected `aud` claim in the JWT.
|
|
2726
|
+
* Required for most OIDC providers — omitting may accept tokens intended for other services.
|
|
2727
|
+
*/
|
|
2728
|
+
audience?: string;
|
|
2729
|
+
/**
|
|
2730
|
+
* Expected `iss` claim in the JWT. Recommended.
|
|
2731
|
+
* Also used to populate the `authorization_servers` field in
|
|
2732
|
+
* /.well-known/oauth-protected-resource when serverUrl is set.
|
|
2733
|
+
*/
|
|
2734
|
+
issuer?: string;
|
|
2735
|
+
/** JWT must have all of these scopes. Checked after signature verification. */
|
|
2736
|
+
requiredScopes?: string[];
|
|
2737
|
+
}
|
|
2738
|
+
interface McpCustomAuthConfig {
|
|
2739
|
+
mode: 'custom';
|
|
2740
|
+
/**
|
|
2741
|
+
* Your own token verification logic.
|
|
2742
|
+
* Throw any error to reject the token — the caller receives a 401.
|
|
2743
|
+
* Return a valid AuthInfo on success.
|
|
2744
|
+
*
|
|
2745
|
+
* @example
|
|
2746
|
+
* ```typescript
|
|
2747
|
+
* verifyAccessToken: async (token) => {
|
|
2748
|
+
* const user = await db.findByToken(token);
|
|
2749
|
+
* if (!user) throw new Error('Invalid token');
|
|
2750
|
+
* return { token, clientId: user.id, scopes: user.scopes };
|
|
2751
|
+
* }
|
|
2752
|
+
* ```
|
|
2753
|
+
*/
|
|
2754
|
+
verifyAccessToken(token: string): Promise<AuthInfo>;
|
|
2755
|
+
/** Token must have all of these scopes. Checked after verifyAccessToken resolves. */
|
|
2756
|
+
requiredScopes?: string[];
|
|
2757
|
+
}
|
|
2758
|
+
type McpAuthConfig = McpStaticAuthConfig | McpJwtAuthConfig | McpCustomAuthConfig;
|
|
2759
|
+
/**
|
|
2760
|
+
* Minimal contract for exposing an agent as an MCP tool.
|
|
2761
|
+
* Satisfied by McpChannel.asAgentDefinition() from toolpack-agents,
|
|
2762
|
+
* or by any plain object with these four fields.
|
|
2763
|
+
*/
|
|
2764
|
+
interface McpAgentDefinition {
|
|
2765
|
+
/** Exposed as "agent.<name>" in tools/list. Must be unique across all agents. */
|
|
2766
|
+
name: string;
|
|
2767
|
+
/** Shown to the MCP client as the tool description. */
|
|
2768
|
+
description: string;
|
|
2769
|
+
/** JSON Schema for the arguments the agent accepts. Defaults to empty object schema. */
|
|
2770
|
+
inputSchema?: Record<string, unknown>;
|
|
2771
|
+
/**
|
|
2772
|
+
* Called when tools/call arrives for this agent.
|
|
2773
|
+
* Must return the agent's output as a string.
|
|
2774
|
+
* Throw to signal an error — the MCP client receives isError: true.
|
|
2775
|
+
*/
|
|
2776
|
+
invoke(args: Record<string, unknown>): Promise<string>;
|
|
2777
|
+
}
|
|
2778
|
+
interface ToolpackMcpServerConfig {
|
|
2779
|
+
/** Transport type. 'stdio' for Claude Desktop / Cursor. 'http' for remote use. */
|
|
2780
|
+
transport: McpTransport;
|
|
2781
|
+
/** Port for HTTP transport. Default: 3000. Only used when transport is 'http'. */
|
|
2782
|
+
port?: number;
|
|
2783
|
+
/** Filter which tools to expose. Exposes all enabled tools when omitted. */
|
|
2784
|
+
expose?: McpServerExposeConfig;
|
|
2785
|
+
/** Server name shown to MCP clients. Default: 'Toolpack SDK'. */
|
|
2786
|
+
serverName?: string;
|
|
2787
|
+
/** Server version shown to MCP clients. Default: '2.0.0'. */
|
|
2788
|
+
serverVersion?: string;
|
|
2789
|
+
/**
|
|
2790
|
+
* Authentication for the HTTP transport. Ignored when transport is 'stdio'.
|
|
2791
|
+
*
|
|
2792
|
+
* When omitted, the HTTP server accepts all requests — safe for localhost only.
|
|
2793
|
+
* When set, every request must carry a valid Bearer token; missing or invalid
|
|
2794
|
+
* tokens are rejected with 401. Scope violations are rejected with 403.
|
|
2795
|
+
*
|
|
2796
|
+
* @example Static tokens (dev / self-hosted)
|
|
2797
|
+
* ```typescript
|
|
2798
|
+
* auth: { mode: 'static', tokens: [process.env.MCP_TOKEN!] }
|
|
2799
|
+
* ```
|
|
2800
|
+
*
|
|
2801
|
+
* @example JWT with Auth0 / Supabase / Clerk
|
|
2802
|
+
* ```typescript
|
|
2803
|
+
* auth: {
|
|
2804
|
+
* mode: 'jwt',
|
|
2805
|
+
* jwksUrl: 'https://your-tenant.auth0.com/.well-known/jwks.json',
|
|
2806
|
+
* audience: 'https://your-mcp-server.example.com',
|
|
2807
|
+
* issuer: 'https://your-tenant.auth0.com/',
|
|
2808
|
+
* }
|
|
2809
|
+
* ```
|
|
2810
|
+
*
|
|
2811
|
+
* @example Custom verification
|
|
2812
|
+
* ```typescript
|
|
2813
|
+
* auth: {
|
|
2814
|
+
* mode: 'custom',
|
|
2815
|
+
* verifyAccessToken: async (token) => {
|
|
2816
|
+
* const user = await db.findByToken(token);
|
|
2817
|
+
* if (!user) throw new Error('invalid');
|
|
2818
|
+
* return { token, clientId: user.id, scopes: user.scopes };
|
|
2819
|
+
* }
|
|
2820
|
+
* }
|
|
2821
|
+
* ```
|
|
2822
|
+
*/
|
|
2823
|
+
auth?: McpAuthConfig;
|
|
2824
|
+
/**
|
|
2825
|
+
* Agents to expose as MCP tools alongside regular tools.
|
|
2826
|
+
* Each agent appears in tools/list as "agent.<name>".
|
|
2827
|
+
*
|
|
2828
|
+
* Agents run to completion before returning — synchronous from the MCP
|
|
2829
|
+
* client's perspective. For long-running agents, ensure the MCP client's
|
|
2830
|
+
* timeout is set appropriately.
|
|
2831
|
+
*
|
|
2832
|
+
* The easiest way to produce an entry is via McpChannel.asAgentDefinition()
|
|
2833
|
+
* from toolpack-agents. A plain object with { name, description, invoke }
|
|
2834
|
+
* also works — no import from toolpack-agents required.
|
|
2835
|
+
*
|
|
2836
|
+
* @example using McpChannel (toolpack-agents)
|
|
2837
|
+
* ```typescript
|
|
2838
|
+
* const ch = new McpChannel();
|
|
2839
|
+
* const agent = new PrReviewerAgent({ channels: [ch] });
|
|
2840
|
+
* await agent.start();
|
|
2841
|
+
* await sdk.startMcpServer({
|
|
2842
|
+
* transport: 'stdio',
|
|
2843
|
+
* agents: [ch.asAgentDefinition(agent)],
|
|
2844
|
+
* });
|
|
2845
|
+
* ```
|
|
2846
|
+
*
|
|
2847
|
+
* @example plain object (no extra dependency)
|
|
2848
|
+
* ```typescript
|
|
2849
|
+
* await sdk.startMcpServer({
|
|
2850
|
+
* transport: 'stdio',
|
|
2851
|
+
* agents: [{
|
|
2852
|
+
* name: 'pr_reviewer',
|
|
2853
|
+
* description: 'Reviews a pull request end-to-end.',
|
|
2854
|
+
* inputSchema: { type: 'object', properties: { pr_url: { type: 'string' } }, required: ['pr_url'] },
|
|
2855
|
+
* invoke: async (args) => {
|
|
2856
|
+
* const result = await prReviewer.invokeAgent({ data: args });
|
|
2857
|
+
* return result.output;
|
|
2858
|
+
* },
|
|
2859
|
+
* }],
|
|
2860
|
+
* });
|
|
2861
|
+
* ```
|
|
2862
|
+
*/
|
|
2863
|
+
agents?: McpAgentDefinition[];
|
|
2864
|
+
/**
|
|
2865
|
+
* Enable tool search mode.
|
|
2866
|
+
*
|
|
2867
|
+
* When true, tools/list returns only `tool.search` plus any always-loaded tools
|
|
2868
|
+
* configured in ToolSearchConfig (alwaysLoadedTools / alwaysLoadedCategories).
|
|
2869
|
+
* MCP clients call `tool.search` first to discover tools on-demand, dramatically
|
|
2870
|
+
* reducing context token usage for registries with 110+ tools.
|
|
2871
|
+
*
|
|
2872
|
+
* Requires the system prompt to instruct the client to use tool.search.
|
|
2873
|
+
* See docs/examples/mcp-server-example.ts for the recommended prompt snippet.
|
|
2874
|
+
*
|
|
2875
|
+
* Default: false — all enabled tools sent upfront.
|
|
2876
|
+
*/
|
|
2877
|
+
searchMode?: boolean;
|
|
2878
|
+
/**
|
|
2879
|
+
* Public base URL of this MCP server (e.g. 'https://mcp.example.com').
|
|
2880
|
+
* Only used when auth.mode is 'jwt'.
|
|
2881
|
+
*
|
|
2882
|
+
* When provided alongside jwt auth, the server mounts
|
|
2883
|
+
* /.well-known/oauth-protected-resource so MCP clients can
|
|
2884
|
+
* auto-discover which OAuth server issues tokens for this server.
|
|
2885
|
+
*
|
|
2886
|
+
* Ignored for static and custom auth modes.
|
|
2887
|
+
*/
|
|
2888
|
+
serverUrl?: string;
|
|
2889
|
+
}
|
|
2890
|
+
interface McpServerHandle {
|
|
2891
|
+
/** Stop the MCP server and release all resources. */
|
|
2892
|
+
stop(): Promise<void>;
|
|
2893
|
+
/** Number of tools currently exposed. */
|
|
2894
|
+
toolCount: number;
|
|
2895
|
+
/**
|
|
2896
|
+
* Actual bound port (HTTP transport only). Useful when port:0 is passed and
|
|
2897
|
+
* the OS assigns a free port — integration tests read this to know where to connect.
|
|
2898
|
+
* Always 0 for stdio transport.
|
|
2899
|
+
*/
|
|
2900
|
+
port: number;
|
|
2901
|
+
}
|
|
2902
|
+
|
|
2591
2903
|
interface ProviderOptions {
|
|
2592
2904
|
/**
|
|
2593
2905
|
* API key for the provider.
|
|
@@ -2756,6 +3068,13 @@ declare class Toolpack extends EventEmitter {
|
|
|
2756
3068
|
*/
|
|
2757
3069
|
private static createProvider;
|
|
2758
3070
|
generate(request: CompletionRequest | string, providerName?: string): Promise<CompletionResponse>;
|
|
3071
|
+
/**
|
|
3072
|
+
* Resolve a string `mode` on the request to its registered ModeConfig.
|
|
3073
|
+
* The AIClient cannot resolve names (the mode registry lives here), so
|
|
3074
|
+
* names must be resolved before the request reaches the client.
|
|
3075
|
+
* Throws for unknown names — same contract as setMode().
|
|
3076
|
+
*/
|
|
3077
|
+
private resolveRequestModeName;
|
|
2759
3078
|
private _buildInterceptorChain;
|
|
2760
3079
|
stream(request: CompletionRequest, providerName?: string): AsyncGenerator<CompletionChunk>;
|
|
2761
3080
|
embed(request: EmbeddingRequest, providerName?: string): Promise<EmbeddingResponse>;
|
|
@@ -2793,6 +3112,67 @@ declare class Toolpack extends EventEmitter {
|
|
|
2793
3112
|
* Validates dependencies and registers all tools.
|
|
2794
3113
|
*/
|
|
2795
3114
|
loadToolProject(project: ToolProject): Promise<void>;
|
|
3115
|
+
/**
|
|
3116
|
+
* Expose Toolpack's built-in tools as an MCP server.
|
|
3117
|
+
*
|
|
3118
|
+
* Any MCP-compatible client (Claude Desktop, Cursor, Windsurf, custom agents)
|
|
3119
|
+
* can connect and use the full tool catalog without importing this SDK.
|
|
3120
|
+
*
|
|
3121
|
+
* Requires `@modelcontextprotocol/sdk` to be installed:
|
|
3122
|
+
* npm install @modelcontextprotocol/sdk
|
|
3123
|
+
*
|
|
3124
|
+
* @example stdio — Claude Desktop / Cursor
|
|
3125
|
+
* ```typescript
|
|
3126
|
+
* const sdk = await Toolpack.init({ provider: 'anthropic', tools: true });
|
|
3127
|
+
* await sdk.startMcpServer({ transport: 'stdio' });
|
|
3128
|
+
* ```
|
|
3129
|
+
*
|
|
3130
|
+
* @example HTTP — open (localhost only)
|
|
3131
|
+
* ```typescript
|
|
3132
|
+
* await sdk.startMcpServer({ transport: 'http', port: 3000 });
|
|
3133
|
+
* ```
|
|
3134
|
+
*
|
|
3135
|
+
* @example HTTP — with static bearer token auth (dev / self-hosted)
|
|
3136
|
+
* ```typescript
|
|
3137
|
+
* await sdk.startMcpServer({
|
|
3138
|
+
* transport: 'http',
|
|
3139
|
+
* port: 3000,
|
|
3140
|
+
* auth: { mode: 'static', tokens: [process.env.MCP_TOKEN!] },
|
|
3141
|
+
* });
|
|
3142
|
+
* ```
|
|
3143
|
+
*
|
|
3144
|
+
* @example HTTP — with JWT auth (Auth0 / Supabase / Clerk / any OIDC provider)
|
|
3145
|
+
* ```typescript
|
|
3146
|
+
* await sdk.startMcpServer({
|
|
3147
|
+
* transport: 'http',
|
|
3148
|
+
* port: 3000,
|
|
3149
|
+
* auth: {
|
|
3150
|
+
* mode: 'jwt',
|
|
3151
|
+
* jwksUrl: 'https://your-tenant.auth0.com/.well-known/jwks.json',
|
|
3152
|
+
* audience: 'https://your-mcp-server.example.com',
|
|
3153
|
+
* issuer: 'https://your-tenant.auth0.com/',
|
|
3154
|
+
* },
|
|
3155
|
+
* serverUrl: 'https://your-mcp-server.example.com',
|
|
3156
|
+
* });
|
|
3157
|
+
* ```
|
|
3158
|
+
*
|
|
3159
|
+
* @example expose only specific categories
|
|
3160
|
+
* ```typescript
|
|
3161
|
+
* await sdk.startMcpServer({
|
|
3162
|
+
* transport: 'stdio',
|
|
3163
|
+
* expose: { categories: ['filesystem', 'github', 'slack'] },
|
|
3164
|
+
* });
|
|
3165
|
+
* ```
|
|
3166
|
+
*
|
|
3167
|
+
* @example search mode — reduces context token usage for 110+ tools
|
|
3168
|
+
* ```typescript
|
|
3169
|
+
* // tools/list returns only tool.search; clients discover tools on-demand.
|
|
3170
|
+
* // Add this to your system prompt:
|
|
3171
|
+
* // "Use tool.search to discover tools before calling them."
|
|
3172
|
+
* await sdk.startMcpServer({ transport: 'stdio', searchMode: true });
|
|
3173
|
+
* ```
|
|
3174
|
+
*/
|
|
3175
|
+
startMcpServer(config: ToolpackMcpServerConfig): Promise<McpServerHandle>;
|
|
2796
3176
|
/**
|
|
2797
3177
|
* Convenience method to get a flat list of all models across all providers.
|
|
2798
3178
|
*/
|
|
@@ -3346,4 +3726,4 @@ interface McpServerCapabilities {
|
|
|
3346
3726
|
|
|
3347
3727
|
declare function createSkillInterceptor(options?: SkillInterceptorOptions): ToolpackInterceptor;
|
|
3348
3728
|
|
|
3349
|
-
export { AGENT_MODE, AGENT_PLANNING_PROMPT, AGENT_WORKFLOW, AIClient, type AIClientConfig, type AddBypassRuleOptions, AnthropicAdapter, type AssembledPrompt, type AssemblerOptions, AuthenticationError, BM25SearchEngine, BUILT_IN_MODES, type BypassRuleType, CHAT_MODE, CHAT_WORKFLOW, CODING_MODE, CODING_PLANNING_PROMPT, CODING_WORKFLOW, CONFIG_DIR_NAME, CONFIG_FILE_NAME, type CompletionChunk, type CompletionOptions, type CompletionRequest, type CompletionResponse, type ConfirmationDecision, type ConfirmationLevel$1 as ConfirmationLevel, ConnectionError, type ContextPrunedEvent, type ContextWindowConfig, ContextWindowConfigError, ContextWindowExceededError, type ContextWindowExceededEvent, type ContextWindowState, ContextWindowStateManager, type ContextWindowStrategy, type ContextWindowWarningEvent, ConversationNotFoundError, type ConversationScope, type ConversationSearchOptions, type ConversationStore, type ConversationSummarizedEvent, DEFAULT_MODE_NAME, DEFAULT_TOOLS_CONFIG, DEFAULT_TOOL_SEARCH_CONFIG, DEFAULT_WORKFLOW, DEFAULT_WORKFLOW_CONFIG, type EmbeddingRequest, type EmbeddingResponse, type FileUploadRequest, type FileUploadResponse, GeminiAdapter, type GetOptions, type HitlConfig, type ImageDataPart, type ImageFilePart, type ImagePart, type ImageUrlPart, InMemoryConversationStore, type InMemoryConversationStoreConfig, InsufficientContextError, InvalidRequestError, type JsonRpcRequest, type JsonRpcResponse, type KnowledgeInstance, McpClient, type McpClientConfig, McpConnectionError, type McpServerCapabilities, type McpServerConfig, McpTimeoutError, type McpTool, McpToolManager, type McpToolsConfig, type MediaOptions, type MediaUploadStrategy, type Message, type MessageContent, type ModeBlockedHint, type ModeConfig, ModeRegistry, OllamaAdapter, type OllamaAdapterConfig, type OllamaModelInfo, OllamaProvider, type OllamaProviderEntry, type OnToolConfirmCallback, OpenAIAdapter, OpenRouterAdapter, type OpenRouterOptions, PageError, type Participant, type Plan, type PlanStep, Planner, type PromptMessage, ProviderAdapter, type ProviderConfig, ProviderError, type ProviderInfo, type ProviderModelInfo, type ProviderOptions, type PruneResult, RateLimitError, type RequestToolDefinition, type Role, type RuntimeConfigStatus, SDKError, SQLiteConversationStore, type SQLiteConversationStoreConfig, type SearchHistoryEntry, type SearchOptions, type SearchResult, type Skill, type SkillInterceptorOptions, type SkillSection, type SkillToolsOptions, type SkillValidationMode, type SlmModelEntry, type StoredMessage, SummarizationError, type SummarizationOptions, type SummarizationResult, TOOLPACK_DIR_NAME, TOOL_SEARCH_NAME, type TextPart, TimeoutError, type ToolCall, type ToolCallFunction, type ToolCallMessage, type ToolCallRequest, type ToolCallResult, type ToolCategory, type ToolConfirmation, type ToolConfirmationRequestedEvent, type ToolConfirmationResolvedEvent, type ToolContext, type ToolDefinition, ToolDiscoveryCache, type ToolLogEvent, type ToolParameterProperty, type ToolParameters, type ToolProgressEvent, type ToolProject, type ToolProjectDependencies, type ToolProjectManifest, ToolRegistry, type ToolResult, ToolRouter, type ToolSchema, type ToolSearchConfig, Toolpack, type ToolpackConfig, type ToolpackInitConfig, type ToolpackInterceptor, type ToolpackNextFunction, type ToolsConfig, type Usage, VertexAIAdapter, type VertexAIConfig, type WorkflowConfig, type WorkflowEvents, WorkflowExecutor, type WorkflowProgress, type WorkflowResult, addBypassRule, buildSummarizedHistory, cloudDeployTool, cloudListTool, cloudStatusTool, cloudToolsProject, codingExtractFunctionTool, codingFindReferencesTool, codingFindSymbolTool, codingGetCallHierarchyTool, codingGetDiagnosticsTool, codingGetExportsTool, codingGetImportsTool, codingGetOutlineTool, codingGetSymbolsTool, codingGoToDefinitionTool, codingMultiFileEditTool, codingRefactorRenameTool, codingToolsProject, countTokens, createContextWindowStateManager, createMcpToolProject, createMode, createSkillInterceptor, createSkillTools, createSummarizationReport, createSummarySystemMessage, createToolProject, dbCountTool, dbDeleteTool, dbInsertTool, dbQueryTool, dbSchemaTool, dbTablesTool, dbToolsProject, dbUpdateTool, diffApplyTool, diffCreateTool, diffPreviewTool, diffToolsProject, disconnectMcpToolProject, ensureGlobalConfigDir, ensureLocalConfigDir, estimateSummaryTokens, estimateTokenCount, execKillTool, execListProcessesTool, execReadOutputTool, execRunBackgroundTool, execRunShellTool, execRunTool, execToolsProject, extractConversationKeypoints, fetchUrlAsBase64, fsAppendFileTool, fsBatchReadTool, fsBatchWriteTool, fsCopyTool, fsCreateDirTool, fsDeleteDirTool, fsDeleteFileTool, fsExistsTool, fsGlobTool, fsListDirTool, fsMoveTool, fsReadFileRangeTool, fsReadFileTool, fsReplaceInFileTool, fsSearchTool, fsStatTool, fsToolsProject, fsTreeTool, fsWriteFileTool, generateSummarizationPrompt, generateToolCategoriesPrompt, getContextWindowPercentage, getDefaultSlmModel, getGlobalConfigDir, getGlobalConfigPath, getGlobalToolpackDir, getLocalConfigDir, getLocalConfigPath, getLocalToolpackDir, getMessageStats, getMimeType, getOllamaBaseUrl, getOllamaProviderEntries, getRegisteredSlmModels, getRuntimeConfigStatus, getSafeOutputReserve, getToolSearchSchema, getToolpackConfig, getUserHomeDir, gitAddTool, gitBlameTool, gitBranchCreateTool, gitBranchListTool, gitCheckoutTool, gitCloneTool, gitCommitTool, gitDiffTool, gitLogTool, gitStatusTool, gitToolsProject, githubContentsGetTextTool, githubGraphqlExecuteTool, githubIssuesCommentsCreateTool, githubPrDiffGetTool, githubPrFilesListTool, githubPrReviewCommentsReplyTool, githubPrReviewThreadsListTool, githubPrReviewThreadsResolveTool, githubPrReviewsSubmitTool, githubToolsProject, groupMessagesByRole, handleContextWindowError, httpDeleteTool, httpDownloadTool, httpGetTool, httpPostTool, httpPutTool, httpToolsProject, initializeGlobalConfigIfFirstRun, isContextWindowError, isDataUri, isRegisteredSlm, isToolSearchTool, k8sApplyManifestTool, k8sDeleteResourceTool, k8sDescribeTool, k8sGetConfigMapTool, k8sGetLogsTool, k8sGetNamespacesTool, k8sListDeploymentsTool, k8sListPodsTool, k8sListServicesTool, k8sSwitchContextTool, k8sToolsProject, k8sWaitForDeploymentTool, loadFullConfig, loadRuntimeConfig, loadToolsConfig, mergeSummarizationResults, normalizeImagePart, ollamaRequest, ollamaStream, parseDataUri, parseSummarizationResponse, prepareSummarizationRequest, pruneMessages, readFileAsBase64, reloadToolpackConfig, removeBypassRule, saveToolsConfig, slackAuthTestTool, slackChatPostEphemeralTool, slackChatPostMessageTool, slackConversationsHistoryTool, slackConversationsRepliesTool, slackReactionsAddTool, slackToolsProject, systemCwdTool, systemDiskUsageTool, systemEnvTool, systemInfoTool, systemSetEnvTool, systemToolsProject, toDataUri, toolSearchDefinition, truncateMessage, validateSummarizationResult, webExtractLinksTool, webFeedTool, webFetchTool, webMapTool, webMetadataTool, webScrapeTool, webScreenshotTool, webSearchTool, webSitemapTool, webToolsProject, wouldExceedContextWindow };
|
|
3729
|
+
export { AGENT_MODE, AGENT_PLANNING_PROMPT, AGENT_WORKFLOW, AIClient, type AIClientConfig, type AddBypassRuleOptions, AnthropicAdapter, type AssembledPrompt, type AssemblerOptions, AuthenticationError, BM25SearchEngine, BUILT_IN_MODES, type BypassRuleType, CHAT_MODE, CHAT_WORKFLOW, CODING_MODE, CODING_PLANNING_PROMPT, CODING_WORKFLOW, CONFIG_DIR_NAME, CONFIG_FILE_NAME, type CompletionChunk, type CompletionOptions, type CompletionRequest, type CompletionResponse, type ConfirmationDecision, type ConfirmationLevel$1 as ConfirmationLevel, ConnectionError, type ContextPrunedEvent, type ContextWindowConfig, ContextWindowConfigError, ContextWindowExceededError, type ContextWindowExceededEvent, type ContextWindowState, ContextWindowStateManager, type ContextWindowStrategy, type ContextWindowWarningEvent, ConversationNotFoundError, type ConversationScope, type ConversationSearchOptions, type ConversationStore, type ConversationSummarizedEvent, DEFAULT_MODE_NAME, DEFAULT_TOOLS_CONFIG, DEFAULT_TOOL_SEARCH_CONFIG, DEFAULT_WORKFLOW, DEFAULT_WORKFLOW_CONFIG, type EmbeddingRequest, type EmbeddingResponse, type FileUploadRequest, type FileUploadResponse, GeminiAdapter, type GetOptions, type HitlConfig, type ImageDataPart, type ImageFilePart, type ImagePart, type ImageUrlPart, InMemoryConversationStore, type InMemoryConversationStoreConfig, InsufficientContextError, InvalidRequestError, type JsonRpcRequest, type JsonRpcResponse, type KnowledgeInstance, type McpAgentDefinition, type McpAuthConfig, McpClient, type McpClientConfig, McpConnectionError, type McpCustomAuthConfig, type McpJwtAuthConfig, type McpServerCapabilities, type McpServerConfig, type McpServerExposeConfig, type McpServerHandle, type McpStaticAuthConfig, McpTimeoutError, type McpTool, McpToolManager, type McpToolsConfig, type McpTransport, type MediaOptions, type MediaUploadStrategy, type Message, type MessageContent, type ModeBlockedHint, type ModeConfig, ModeRegistry, OllamaAdapter, type OllamaAdapterConfig, type OllamaModelInfo, OllamaProvider, type OllamaProviderEntry, type OnToolConfirmCallback, OpenAIAdapter, OpenRouterAdapter, type OpenRouterOptions, PageError, type Participant, type Plan, type PlanStep, Planner, type PromptMessage, ProviderAdapter, type ProviderConfig, ProviderError, type ProviderInfo, type ProviderModelInfo, type ProviderOptions, type PruneResult, RateLimitError, type RequestToolDefinition, type Role, type RuntimeConfigStatus, SDKError, SQLiteConversationStore, type SQLiteConversationStoreConfig, type SearchHistoryEntry, type SearchOptions, type SearchResult, type Skill, type SkillInterceptorOptions, type SkillSection, type SkillToolsOptions, type SkillValidationMode, type SlmModelEntry, type StoredMessage, SummarizationError, type SummarizationOptions, type SummarizationResult, TOOLPACK_DIR_NAME, TOOL_SEARCH_NAME, type TextPart, TimeoutError, type ToolAnnotations, type ToolCall, type ToolCallFunction, type ToolCallMessage, type ToolCallRequest, type ToolCallResult, type ToolCategory, type ToolConfirmation, type ToolConfirmationRequestedEvent, type ToolConfirmationResolvedEvent, type ToolContext, type ToolDefinition, ToolDiscoveryCache, type ToolLogEvent, type ToolParameterProperty, type ToolParameters, type ToolProgressEvent, type ToolProject, type ToolProjectDependencies, type ToolProjectManifest, ToolRegistry, type ToolResult, ToolRouter, type ToolSchema, type ToolSearchConfig, Toolpack, type ToolpackConfig, type ToolpackInitConfig, type ToolpackInterceptor, type ToolpackMcpServerConfig, type ToolpackNextFunction, type ToolsConfig, type Usage, VertexAIAdapter, type VertexAIConfig, type WorkflowConfig, type WorkflowEvents, WorkflowExecutor, type WorkflowProgress, type WorkflowResult, addBypassRule, buildSummarizedHistory, cloudDeployTool, cloudListTool, cloudStatusTool, cloudToolsProject, codingExtractFunctionTool, codingFindReferencesTool, codingFindSymbolTool, codingGetCallHierarchyTool, codingGetDiagnosticsTool, codingGetExportsTool, codingGetImportsTool, codingGetOutlineTool, codingGetSymbolsTool, codingGoToDefinitionTool, codingMultiFileEditTool, codingRefactorRenameTool, codingToolsProject, countTokens, createContextWindowStateManager, createMcpToolProject, createMode, createSkillInterceptor, createSkillTools, createSummarizationReport, createSummarySystemMessage, createToolProject, dbCountTool, dbDeleteTool, dbInsertTool, dbQueryTool, dbSchemaTool, dbTablesTool, dbToolsProject, dbUpdateTool, diffApplyTool, diffCreateTool, diffPreviewTool, diffToolsProject, disconnectMcpToolProject, ensureGlobalConfigDir, ensureLocalConfigDir, estimateSummaryTokens, estimateTokenCount, execKillTool, execListProcessesTool, execReadOutputTool, execRunBackgroundTool, execRunBlockingTool, execRunShellTool, execRunTool, execTailOutputTool, execToolsProject, extractConversationKeypoints, fetchUrlAsBase64, fsAppendFileTool, fsBatchReadTool, fsBatchWriteTool, fsCopyTool, fsCreateDirTool, fsDeleteDirTool, fsDeleteFileTool, fsExistsTool, fsGlobTool, fsListDirTool, fsMoveTool, fsReadFileRangeTool, fsReadFileTool, fsReplaceInFileTool, fsSearchTool, fsStatTool, fsToolsProject, fsTreeTool, fsWriteFileTool, generateSummarizationPrompt, generateToolCategoriesPrompt, getContextWindowPercentage, getDefaultSlmModel, getGlobalConfigDir, getGlobalConfigPath, getGlobalToolpackDir, getLocalConfigDir, getLocalConfigPath, getLocalToolpackDir, getMessageStats, getMimeType, getOllamaBaseUrl, getOllamaProviderEntries, getRegisteredSlmModels, getRuntimeConfigStatus, getSafeOutputReserve, getToolSearchSchema, getToolpackConfig, getUserHomeDir, gitAddTool, gitBlameTool, gitBranchCreateTool, gitBranchListTool, gitCheckoutTool, gitCloneTool, gitCommitTool, gitDiffTool, gitLogTool, gitStatusTool, gitToolsProject, githubContentsGetTextTool, githubGraphqlExecuteTool, githubIssuesCommentsCreateTool, githubPrDiffGetTool, githubPrFilesListTool, githubPrReviewCommentsReplyTool, githubPrReviewThreadsListTool, githubPrReviewThreadsResolveTool, githubPrReviewsSubmitTool, githubToolsProject, groupMessagesByRole, handleContextWindowError, httpDeleteTool, httpDownloadTool, httpGetTool, httpPostTool, httpPutTool, httpToolsProject, initializeGlobalConfigIfFirstRun, isContextWindowError, isDataUri, isRegisteredSlm, isToolSearchTool, k8sApplyManifestTool, k8sDeleteResourceTool, k8sDescribeTool, k8sGetConfigMapTool, k8sGetLogsTool, k8sGetNamespacesTool, k8sListDeploymentsTool, k8sListPodsTool, k8sListServicesTool, k8sSwitchContextTool, k8sToolsProject, k8sWaitForDeploymentTool, loadFullConfig, loadRuntimeConfig, loadToolsConfig, mergeSummarizationResults, normalizeImagePart, ollamaRequest, ollamaStream, parseDataUri, parseSummarizationResponse, prepareSummarizationRequest, pruneMessages, readFileAsBase64, reloadToolpackConfig, removeBypassRule, saveToolsConfig, slackAuthTestTool, slackChatPostEphemeralTool, slackChatPostMessageTool, slackConversationsHistoryTool, slackConversationsRepliesTool, slackReactionsAddTool, slackToolsProject, systemCwdTool, systemDiskUsageTool, systemEnvTool, systemInfoTool, systemSetEnvTool, systemToolsProject, toDataUri, toolSearchDefinition, truncateMessage, validateSummarizationResult, webExtractLinksTool, webFeedTool, webFetchTool, webMapTool, webMetadataTool, webScrapeTool, webScreenshotTool, webSearchTool, webSitemapTool, webToolsProject, wouldExceedContextWindow };
|