Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 | 1x 1x 1x 1x 25x 25x 25x 1x 24x 24x 25x 25x 25x 25x 25x 25x 25x 25x 24x 24x 23x 23x 23x 23x 23x 23x 23x 24x 4x 4x 10x 10x 5x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 5x 5x 10x 10x 10x 10x 12x 12x 12x 12x 12x 12x 32x 12x 10x 10x 3x 2x 8x 8x 10x 4x 20x 10x 8x 14x 14x 10x 8x 8x 38x 38x 38x 12x 2x 10x 12x 12x 12x 12x 10x 10x 32x 32x 32x 32x 32x | import { defu } from 'defu';
import type { Arrayable } from 'type-fest';
import { DEFAULT_BASE_URL } from './consts';
import { createFeedbackTool } from './feedback';
import { type StackOneHeaders, normaliseHeaders, stackOneHeadersSchema } from './headers';
import { createMCPClient } from './mcp-client';
import { type RpcActionResponse, RpcClient } from './rpc-client';
import { BaseTool, type StackOneTool, Tools } from './tool';
import type {
ExecuteOptions,
JsonDict,
JsonSchemaProperties,
RpcExecuteConfig,
ToolParameters,
} from './types';
import { toArray } from './utils/array';
import { StackOneError } from './utils/errors';
/**
* Converts RpcActionResponse to JsonDict in a type-safe manner.
* RpcActionResponse uses z.passthrough() which preserves additional fields,
* making it structurally compatible with Record<string, unknown>.
*/
function rpcResponseToJsonDict(response: RpcActionResponse): JsonDict {
// RpcActionResponse with passthrough() has the shape:
// { next?: string | null, data?: ..., [key: string]: unknown }
// We extract all properties into a plain object
const result: JsonDict = {};
for (const [key, value] of Object.entries(response)) {
result[key] = value;
}
return result;
}
type ToolInputSchema = Awaited<
ReturnType<Awaited<ReturnType<typeof createMCPClient>>['client']['listTools']>
>['tools'][number]['inputSchema'];
/**
* Base exception for toolset errors
*/
export class ToolSetError extends Error {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ToolSetError';
}
}
/**
* Raised when there is an error in the toolset configuration
*/
export class ToolSetConfigError extends ToolSetError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ToolSetConfigError';
}
}
/**
* Raised when there is an error loading tools
*/
export class ToolSetLoadError extends ToolSetError {
constructor(message: string, options?: ErrorOptions) {
super(message, options);
this.name = 'ToolSetLoadError';
}
}
/**
* Authentication configuration for toolsets
*/
export interface AuthenticationConfig {
type: 'basic' | 'bearer';
credentials?: {
username?: string;
password?: string;
token?: string;
};
headers?: Record<string, string>;
}
/**
* Base configuration for all toolsets
*/
export interface BaseToolSetConfig {
baseUrl?: string;
authentication?: AuthenticationConfig;
headers?: Record<string, string>;
rpcClient?: RpcClient;
}
/**
* Configuration for StackOne toolset
*/
export interface StackOneToolSetConfig extends BaseToolSetConfig {
apiKey?: string;
accountId?: string;
strict?: boolean;
}
/**
* Options for filtering tools when fetching from MCP
*/
interface FetchToolsOptions {
/**
* Filter tools by account IDs
* Only tools available on these accounts will be returned
*/
accountIds?: string[];
/**
* Filter tools by provider names
* Only tools from these providers will be returned
* @example ['hibob', 'bamboohr']
*/
providers?: string[];
/**
* Filter tools by action patterns with glob support
* Only tools matching these patterns will be returned
* @example ['*_list_employees', 'hibob_create_employees']
*/
actions?: string[];
}
/**
* Configuration for workflow
*/
interface WorkflowConfig {
key: string;
input: string;
model: string;
tools: string[];
accountIds: string[];
cache?: boolean;
}
/**
* Class for loading StackOne tools via MCP
*/
export class StackOneToolSet {
private baseUrl?: string;
private authentication?: AuthenticationConfig;
private headers: Record<string, string>;
private rpcClient?: RpcClient;
/**
* Account ID for StackOne API
*/
private accountId?: string;
private accountIds: string[] = [];
/**
* Initialise StackOne toolset with API key and optional account ID
* @param config Configuration object containing API key and optional account ID
*/
constructor(config?: StackOneToolSetConfig) {
const apiKey = config?.apiKey || process.env.STACKONE_API_KEY;
if (!apiKey && config?.strict) {
throw new ToolSetConfigError(
'No API key provided. Set STACKONE_API_KEY environment variable or pass apiKey in config.',
);
}
Iif (!apiKey) {
console.warn(
'No API key provided. Set STACKONE_API_KEY environment variable or pass apiKey in config.',
);
}
const authentication: AuthenticationConfig = {
type: 'basic',
credentials: {
username: apiKey || '',
password: '',
},
};
const accountId = config?.accountId || process.env.STACKONE_ACCOUNT_ID;
const configHeaders = {
...config?.headers,
...(accountId ? { 'x-account-id': accountId } : {}),
};
// Initialise base properties
this.baseUrl = config?.baseUrl ?? process.env.STACKONE_BASE_URL ?? DEFAULT_BASE_URL;
this.authentication = authentication;
this.headers = configHeaders;
this.rpcClient = config?.rpcClient;
this.accountId = accountId;
// Set Authentication headers if provided
if (this.authentication) {
// Only set auth headers if they don't already exist in custom headers
const needsAuthHeader = !('Authorization' in this.headers);
if (needsAuthHeader) {
switch (this.authentication.type) {
case 'basic':
Eif (this.authentication.credentials?.username) {
const username = this.authentication.credentials.username;
const password = this.authentication.credentials.password || '';
const authString = Buffer.from(`${username}:${password}`).toString('base64');
this.headers.Authorization = `Basic ${authString}`;
}
break;
case 'bearer':
if (this.authentication.credentials?.token) {
this.headers.Authorization = `Bearer ${this.authentication.credentials.token}`;
}
break;
default:
this.authentication.type satisfies never;
throw new ToolSetError(
`Unsupported authentication type: ${String(this.authentication.type)}`,
);
}
}
// Add any additional headers from authentication config, but don't override existing ones
Iif (this.authentication.headers) {
this.headers = { ...this.authentication.headers, ...this.headers };
}
}
}
/**
* Set account IDs for filtering tools
* @param accountIds Array of account IDs to filter tools by
* @returns This toolset instance for chaining
*/
setAccounts(accountIds: string[]): this {
this.accountIds = accountIds;
return this;
}
/**
* Fetch tools from MCP with optional filtering
* @param options Optional filtering options for account IDs, providers, and actions
* @returns Collection of tools matching the filter criteria
*/
async fetchTools(options?: FetchToolsOptions): Promise<Tools> {
// Use account IDs from options, or fall back to instance state
const effectiveAccountIds = options?.accountIds || this.accountIds;
// Fetch tools (with account filtering if needed)
let tools: Tools;
if (effectiveAccountIds.length > 0) {
const toolsPromises = effectiveAccountIds.map(async (accountId) => {
const headers = { 'x-account-id': accountId };
const mergedHeaders = { ...this.headers, ...headers };
// Create a temporary toolset instance with the account-specific headers
const tempHeaders = mergedHeaders;
const originalHeaders = this.headers;
this.headers = tempHeaders;
try {
const tools = await this.fetchToolsFromMcp();
return tools.toArray();
} finally {
// Restore original headers
this.headers = originalHeaders;
}
});
const toolArrays = await Promise.all(toolsPromises);
const allTools = toolArrays.flat();
tools = new Tools(allTools);
} else {
// No account filtering - fetch all tools
tools = await this.fetchToolsFromMcp();
}
// Apply provider and action filters
const filteredTools = this.filterTools(tools, options);
// Add feedback tool
const feedbackTool = createFeedbackTool(undefined, this.accountId, this.baseUrl);
const toolsWithFeedback = new Tools([...filteredTools.toArray(), feedbackTool]);
return toolsWithFeedback;
}
/**
* Fetch tool definitions from MCP
*/
private async fetchToolsFromMcp(): Promise<Tools> {
Iif (!this.baseUrl) {
throw new ToolSetConfigError('baseUrl is required to fetch MCP tools');
}
await using clients = await createMCPClient({
baseUrl: `${this.baseUrl}/mcp`,
headers: this.headers,
});
await clients.client.connect(clients.transport);
const listToolsResult = await clients.client.listTools();
const actionsClient = this.getActionsClient();
const tools = listToolsResult.tools.map(({ name, description, inputSchema }) =>
this.createRpcBackedTool({
actionsClient,
name,
description,
inputSchema,
}),
);
return new Tools(tools);
}
/**
* Filter tools by providers and actions
* @param tools Tools collection to filter
* @param options Filtering options
* @returns Filtered tools collection
*/
private filterTools(tools: Tools, options?: FetchToolsOptions): Tools {
let filteredTools = tools.toArray();
// Filter by providers if specified
if (options?.providers && options.providers.length > 0) {
const providerSet = new Set(options.providers.map((p) => p.toLowerCase()));
filteredTools = filteredTools.filter((tool) => {
// Extract provider from tool name (assuming format: provider_action)
const provider = tool.name.split('_')[0]?.toLowerCase();
return provider && providerSet.has(provider);
});
}
// Filter by actions if specified (with glob support)
if (options?.actions && options.actions.length > 0) {
filteredTools = filteredTools.filter((tool) =>
options.actions?.some((pattern) => this.matchGlob(tool.name, pattern)),
);
}
return new Tools(filteredTools);
}
/**
* Check if a tool name matches a filter pattern
* @param toolName Tool name to check
* @param filterPattern Filter pattern or array of patterns
* @returns True if the tool name matches the filter pattern
*/
private matchesFilter(toolName: string, filterPattern: Arrayable<string>): boolean {
// Convert to array to handle both single string and array patterns
const patterns = toArray(filterPattern);
// Split into positive and negative patterns
const positivePatterns = patterns.filter((p) => !p.startsWith('!'));
const negativePatterns = patterns.filter((p) => p.startsWith('!')).map((p) => p.substring(1));
// If no positive patterns, treat as match all
const matchesPositive =
positivePatterns.length === 0 || positivePatterns.some((p) => this.matchGlob(toolName, p));
// If any negative pattern matches, exclude the tool
const matchesNegative = negativePatterns.some((p) => this.matchGlob(toolName, p));
return matchesPositive && !matchesNegative;
}
/**
* Check if a string matches a glob pattern
* @param str String to check
* @param pattern Glob pattern
* @returns True if the string matches the pattern
*/
private matchGlob(str: string, pattern: string): boolean {
// Convert glob pattern to regex
const regexPattern = pattern.replace(/\./g, '\\.').replace(/\*/g, '.*').replace(/\?/g, '.');
// Create regex with start and end anchors
const regex = new RegExp(`^${regexPattern}$`);
// Test if the string matches the pattern
return regex.test(str);
}
private getActionsClient(): RpcClient {
if (this.rpcClient) {
return this.rpcClient;
}
const credentials = this.authentication?.credentials ?? {};
const apiKeyFromAuth =
this.authentication?.type === 'basic'
? credentials.username
: this.authentication?.type === 'bearer'
? credentials.token
: credentials.username;
const apiKey = apiKeyFromAuth || process.env.STACKONE_API_KEY;
const password = this.authentication?.type === 'basic' ? (credentials.password ?? '') : '';
Iif (!apiKey) {
throw new ToolSetConfigError(
'StackOne API key is required to create an actions client. Provide rpcClient, configure authentication credentials, or set the STACKONE_API_KEY environment variable.',
);
}
this.rpcClient = new RpcClient({
serverURL: this.baseUrl,
security: {
username: apiKey,
password,
},
});
return this.rpcClient;
}
private createRpcBackedTool({
actionsClient,
name,
description,
inputSchema,
}: {
actionsClient: RpcClient;
name: string;
description?: string;
inputSchema: ToolInputSchema;
}): BaseTool {
const executeConfig = {
kind: 'rpc',
method: 'POST',
url: `${this.baseUrl}/actions/rpc`,
payloadKeys: {
action: 'action',
body: 'body',
headers: 'headers',
path: 'path',
query: 'query',
},
} as const satisfies RpcExecuteConfig; // Mirrors StackOne RPC payload layout so metadata/debug stays in sync.
const toolParameters = {
...inputSchema,
// properties are not well typed in MCP spec
properties: inputSchema?.properties as JsonSchemaProperties,
} satisfies ToolParameters;
const tool = new BaseTool(
name,
description ?? '',
toolParameters,
executeConfig,
this.headers,
).setExposeExecutionMetadata(false);
tool.execute = async (
inputParams?: JsonDict | string,
options?: ExecuteOptions,
): Promise<JsonDict> => {
try {
if (
inputParams !== undefined &&
typeof inputParams !== 'object' &&
typeof inputParams !== 'string'
) {
throw new StackOneError(
`Invalid parameters type. Expected object or string, got ${typeof inputParams}. Parameters: ${JSON.stringify(inputParams)}`,
);
}
const parsedParams =
typeof inputParams === 'string' ? JSON.parse(inputParams) : (inputParams ?? {});
const currentHeaders = tool.getHeaders();
const baseHeaders = this.buildActionHeaders(currentHeaders);
const pathParams = this.extractRecord(parsedParams, 'path');
const queryParams = this.extractRecord(parsedParams, 'query');
const additionalHeaders = this.extractRecord(parsedParams, 'headers');
const extraHeaders = normaliseHeaders(additionalHeaders);
// defu merges extraHeaders into baseHeaders, both are already branded types
const actionHeaders = defu(extraHeaders, baseHeaders) as StackOneHeaders;
const bodyPayload = this.extractRecord(parsedParams, 'body');
const rpcBody: JsonDict = bodyPayload ? { ...bodyPayload } : {};
for (const [key, value] of Object.entries(parsedParams)) {
if (key === 'body' || key === 'headers' || key === 'path' || key === 'query') {
continue;
}
rpcBody[key] = value as unknown;
}
if (options?.dryRun) {
const requestPayload = {
action: name,
body: rpcBody,
headers: actionHeaders,
path: pathParams ?? undefined,
query: queryParams ?? undefined,
};
return {
url: executeConfig.url,
method: executeConfig.method,
headers: actionHeaders,
body: JSON.stringify(requestPayload),
mappedParams: parsedParams,
} satisfies JsonDict;
}
const response = await actionsClient.actions.rpcAction({
action: name,
body: rpcBody,
headers: actionHeaders,
path: pathParams ?? undefined,
query: queryParams ?? undefined,
});
return rpcResponseToJsonDict(response);
} catch (error) {
if (error instanceof StackOneError) {
throw error;
}
throw new StackOneError(`Error executing RPC action ${name}`, { cause: error });
}
};
return tool;
}
private buildActionHeaders(headers: Record<string, string>): StackOneHeaders {
const sanitizedEntries = Object.entries(headers).filter(
([key]) => key.toLowerCase() !== 'authorization',
);
return stackOneHeadersSchema.parse(
Object.fromEntries(sanitizedEntries.map(([key, value]) => [key, String(value)])),
);
}
private extractRecord(
params: JsonDict,
key: 'body' | 'headers' | 'path' | 'query',
): JsonDict | undefined {
const value = params[key];
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
return value as JsonDict;
}
return undefined;
}
/**
* Plan a workflow
* @param config Configuration object containing workflow details
* @returns Workflow object
*/
plan(_: WorkflowConfig): Promise<StackOneTool> {
throw new Error('Not implemented yet');
}
}
|