All files / src toolsets.ts

83.33% Statements 220/264
71.63% Branches 149/208
93.33% Functions 42/45
83% Lines 210/253

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 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 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 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006                                                                    3x 3x 3x   3x                       3x 3x                 3x 3x                                                                                                                                                                                                                                                                                                                                                     3x 3x                       2x                                             56x               56x 2x         54x   56x 1x         53x           53x               56x   56x           56x 56x 56x 56x 56x 56x     56x     56x   53x   53x 52x   52x 52x 52x 52x 52x   52x                               53x                           6x 6x             7x 7x 7x         7x             7x   7x           7x 7x         7x                                     3x           3x       3x                                                                 7x           7x 7x 7x 7x   7x 7x   7x         7x 2x     5x     5x                 5x           5x 5x             5x     5x 18x 18x         10x   8x 8x 8x           5x 5x 18x       5x 2x       19x   3x   7x 1x       9x 12x     9x 2x 1x         2x   2x 2x 1x       1x                                                                     2x           2x 2x       2x 2x               2x 2x 2x   2x                                                             2x         1x       1x 1x         1x   1x 1x                           3x 3x       3x 3x   11x 18x 3x       3x 11x 11x 11x   3x                   39x       39x 12x 16x 16x     16x 16x 16x   16x 16x 16x     16x       12x 12x 12x     27x       39x     39x 39x   39x             43x       43x         43x 43x 43x   43x 117x               43x                   39x     39x 4x 3x 11x         39x 7x 31x       39x                     31x     31x     31x       43x 9x     34x   43x           43x 43x   43x           34x               34x                           117x                         117x             117x               117x       9x 9x         1x           8x   9x 9x   9x 9x 9x 9x   9x   9x 9x 9x 12x 8x   4x     7x 4x               4x                 3x               3x   2x 1x   1x       117x       7x 14x     7x 7x               28x 28x 8x   20x      
import { defu } from 'defu';
import type { MergeExclusive, SimplifyDeep } from 'type-fest';
import { DEFAULT_BASE_URL } from './consts';
import { createFeedbackTool } from './feedback';
import { type StackOneHeaders, normalizeHeaders, stackOneHeadersSchema } from './headers';
import { ToolIndex } from './local-search';
import { createMCPClient } from './mcp-client';
import { type RpcActionResponse, RpcClient } from './rpc-client';
import {
	SemanticSearchClient,
	SemanticSearchError,
	type SemanticSearchResult,
} from './semantic-search';
import { BaseTool, Tools } from './tool';
import type {
	ExecuteOptions,
	JsonObject,
	JsonSchemaProperties,
	RpcExecuteConfig,
	SearchConfig,
	ToolParameters,
} from './types';
import { StackOneError } from './utils/error-stackone';
import { normalizeActionName } from './utils/normalize';
 
/**
 * Converts RpcActionResponse to JsonObject in a type-safe manner.
 * RpcActionResponse uses z.passthrough() which preserves additional fields,
 * making it structurally compatible with Record<string, JsonValue>.
 */
function rpcResponseToJsonObject(response: RpcActionResponse): JsonObject {
	// RpcActionResponse with passthrough() has the shape:
	// { next?: string | null, data?: ..., [key: string]: unknown }
	// We extract all properties into a plain object
	const result: JsonObject = {};
	for (const [key, value] of Object.entries(response)) {
		result[key] = value as JsonObject[string];
	}
	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 with a single account ID
 */
interface SingleAccountConfig {
	/**
	 * Single account ID for StackOne API operations
	 * Use this when working with a single account
	 */
	accountId: string;
}
 
/**
 * Configuration with multiple account IDs
 */
interface MultipleAccountsConfig {
	/**
	 * Array of account IDs for filtering tools across multiple accounts
	 * When provided, tools will be fetched for all specified accounts
	 * @example ['account-1', 'account-2']
	 */
	accountIds: string[];
}
 
/**
 * Account configuration options - either single accountId or multiple accountIds, but not both
 */
type AccountConfig = SimplifyDeep<MergeExclusive<SingleAccountConfig, MultipleAccountsConfig>>;
 
/**
 * Base configuration for StackOne toolset (without account options)
 */
interface StackOneToolSetBaseConfig extends BaseToolSetConfig {
	apiKey?: string;
	strict?: boolean;
	/**
	 * Search configuration. Controls default search behavior for `searchTools()`,
	 * `getSearchTool()`, and `searchActionNames()`.
	 *
	 * - Omit or pass `undefined` → search enabled with defaults (`method: 'auto'`)
	 * - Pass `null` → search disabled
	 * - Pass `{ method, topK, minSimilarity }` → search enabled with custom defaults
	 *
	 * Per-call options always override these defaults.
	 */
	search?: SearchConfig | null;
}
 
/**
 * Configuration for StackOne toolset
 * Accepts either accountId (single) or accountIds (multiple), but not both
 */
export type StackOneToolSetConfig = StackOneToolSetBaseConfig & Partial<AccountConfig>;
 
/**
 * 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[];
}
 
/**
 * Search mode for tool discovery.
 *
 * - `"auto"` (default): try semantic search first, fall back to local BM25+TF-IDF if the API is unavailable
 * - `"semantic"`: use only the semantic search API; throws SemanticSearchError on failure
 * - `"local"`: use only local BM25+TF-IDF search (no API call to the semantic search endpoint)
 */
export type SearchMode = 'auto' | 'semantic' | 'local';
 
/**
 * Options for searchTools() and SearchTool
 */
export interface SearchToolsOptions {
	/** Optional provider/connector filter (e.g., "bamboohr", "slack") */
	connector?: string;
	/** Maximum number of tools to return */
	topK?: number;
	/** Minimum similarity score threshold 0-1 */
	minSimilarity?: number;
	/** Optional account IDs (uses setAccounts() if not provided) */
	accountIds?: string[];
	/** Search backend to use */
	search?: SearchMode;
}
 
/**
 * Options for searchActionNames()
 */
export interface SearchActionNamesOptions {
	/** Optional provider/connector filter */
	connector?: string;
	/** Optional account IDs to scope results */
	accountIds?: string[];
	/** Maximum number of results */
	topK?: number;
	/** Minimum similarity score threshold 0-1 */
	minSimilarity?: number;
}
 
/**
 * Callable search tool that wraps StackOneToolSet.searchTools().
 *
 * Designed for agent loops — call `search()` with a query to get Tools back.
 *
 * @example
 * ```typescript
 * const toolset = new StackOneToolSet({ apiKey: 'sk-xxx' });
 * const searchTool = toolset.getSearchTool();
 * const tools = await searchTool.search('manage employee records', { accountIds: ['acc-123'] });
 * ```
 */
export class SearchTool {
	private readonly toolset: StackOneToolSet;
	private readonly defaultConfig: SearchConfig;
 
	constructor(toolset: StackOneToolSet, config: SearchConfig = {}) {
		this.toolset = toolset;
		this.defaultConfig = config;
	}
 
	/**
	 * Search for tools using natural language.
	 *
	 * @param query - Natural language description of needed functionality
	 * @param options - Search options (connector, topK, minSimilarity, accountIds, search).
	 *   Per-call options override the defaults from the constructor config.
	 * @returns Tools collection with matched tools
	 */
	async search(query: string, options?: SearchToolsOptions): Promise<Tools> {
		return this.toolset.searchTools(query, {
			...options,
			search: options?.search ?? this.defaultConfig.method,
			topK: options?.topK ?? this.defaultConfig.topK,
			minSimilarity: options?.minSimilarity ?? this.defaultConfig.minSimilarity,
		});
	}
}
 
/**
 * Class for loading StackOne tools via MCP
 */
export class StackOneToolSet {
	private baseUrl?: string;
	private authentication?: AuthenticationConfig;
	private headers: Record<string, string>;
	private rpcClient?: RpcClient;
	private readonly searchConfig: SearchConfig | null;
 
	/**
	 * Account ID for StackOne API
	 */
	private accountId?: string;
	private accountIds: string[] = [];
 
	/**
	 * Initialize StackOne toolset with API key and optional account ID(s)
	 * @param config Configuration object containing API key and optional account ID(s)
	 */
	constructor(config?: StackOneToolSetConfig) {
		// Validate mutually exclusive account options
		if (config?.accountId != null && config?.accountIds != null) {
			throw new ToolSetConfigError(
				'Cannot provide both accountId and accountIds. Use accountId for a single account or accountIds for multiple accounts.',
			);
		}
 
		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 } : {}),
		};
 
		// Initialize 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;
		this.accountIds = config?.accountIds ?? [];
 
		// Resolve search config: undefined → defaults, null → disabled, object → custom
		this.searchConfig = config?.search === null ? null : { method: 'auto', ...config?.search };
 
		// 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 };
			}
		}
	}
 
	private semanticSearchClient?: SemanticSearchClient;
 
	/**
	 * 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;
	}
 
	/**
	 * Get or lazily create the semantic search client.
	 */
	private getSemanticClient(): SemanticSearchClient {
		Eif (!this.semanticSearchClient) {
			const apiKey = this.getApiKey();
			this.semanticSearchClient = new SemanticSearchClient({
				apiKey,
				baseUrl: this.baseUrl,
			});
		}
		return this.semanticSearchClient;
	}
 
	/**
	 * Extract the API key from authentication config.
	 */
	private getApiKey(): string {
		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;
		Iif (!apiKey) {
			throw new ToolSetConfigError(
				'API key is required for semantic search. Provide apiKey in config or set STACKONE_API_KEY environment variable.',
			);
		}
		return apiKey;
	}
 
	/**
	 * Get a callable search tool that returns Tools collections.
	 *
	 * Returns a SearchTool instance that wraps `searchTools()` for use in agent loops.
	 *
	 * @param options - Options including the default search mode
	 * @returns SearchTool instance
	 *
	 * @example
	 * ```typescript
	 * const toolset = new StackOneToolSet({ apiKey: 'sk-xxx' });
	 * const searchTool = toolset.getSearchTool();
	 * const tools = await searchTool.search('manage employee records', { accountIds: ['acc-123'] });
	 * ```
	 */
	getSearchTool(options?: { search?: SearchMode }): SearchTool {
		Iif (this.searchConfig === null) {
			throw new ToolSetConfigError(
				'Search is disabled. Initialize StackOneToolSet with a search config to enable.',
			);
		}
 
		const config: SearchConfig = options?.search
			? { ...this.searchConfig, method: options.search }
			: this.searchConfig;
 
		return new SearchTool(this, config);
	}
 
	/**
	 * Search for and fetch tools using semantic or local search.
	 *
	 * This method discovers relevant tools based on natural language queries.
	 *
	 * @param query - Natural language description of needed functionality
	 *   (e.g., "create employee", "send a message")
	 * @param options - Search options
	 * @returns Tools collection with matched tools from linked accounts
	 * @throws SemanticSearchError if the API call fails and search is "semantic"
	 *
	 * @example
	 * ```typescript
	 * // Semantic search (default with local fallback)
	 * const tools = await toolset.searchTools('manage employee records', { topK: 5 });
	 *
	 * // Explicit semantic search
	 * const tools = await toolset.searchTools('manage employees', { search: 'semantic' });
	 *
	 * // Local BM25+TF-IDF search
	 * const tools = await toolset.searchTools('manage employees', { search: 'local' });
	 *
	 * // Filter by connector
	 * const tools = await toolset.searchTools('create time off request', {
	 *   connector: 'bamboohr',
	 *   search: 'semantic',
	 * });
	 * ```
	 */
	async searchTools(query: string, options?: SearchToolsOptions): Promise<Tools> {
		Iif (this.searchConfig === null) {
			throw new ToolSetConfigError(
				'Search is disabled. Initialize StackOneToolSet with a search config to enable.',
			);
		}
 
		const search = options?.search ?? this.searchConfig.method ?? 'auto';
		const topK = options?.topK ?? this.searchConfig.topK;
		const minSimilarity = options?.minSimilarity ?? this.searchConfig.minSimilarity;
		const mergedOptions = { ...options, search, topK, minSimilarity };
 
		const allTools = await this.fetchTools({ accountIds: mergedOptions.accountIds });
		const availableConnectors = allTools.getConnectors();
 
		Iif (availableConnectors.size === 0) {
			return new Tools([]);
		}
 
		// Local-only search — skip semantic API entirely
		if (search === 'local') {
			return this.localSearch(query, allTools, mergedOptions);
		}
 
		try {
			// Determine which connectors to search
			let connectorsToSearch: Set<string>;
			Iif (mergedOptions.connector) {
				const connectorLower = mergedOptions.connector.toLowerCase();
				connectorsToSearch = availableConnectors.has(connectorLower)
					? new Set([connectorLower])
					: new Set();
				if (connectorsToSearch.size === 0) {
					return new Tools([]);
				}
			} else {
				connectorsToSearch = availableConnectors;
			}
 
			// Search each connector in parallel — in auto mode, treat missing
			// API key as "semantic unavailable" and fall back to local search.
			let client: SemanticSearchClient;
			try {
				client = this.getSemanticClient();
			} catch (error) {
				if (search === 'auto' && error instanceof ToolSetConfigError) {
					return this.localSearch(query, allTools, mergedOptions);
				}
				throw error;
			}
			const allResults: SemanticSearchResult[] = [];
			let lastError: SemanticSearchError | undefined;
 
			const searchPromises = [...connectorsToSearch].map(async (connector) => {
				try {
					const response = await client.search(query, {
						connector,
						topK: mergedOptions.topK,
						minSimilarity: mergedOptions.minSimilarity,
					});
					return response.results;
				} catch (error) {
					Eif (error instanceof SemanticSearchError) {
						lastError = error;
						return [];
					}
					throw error;
				}
			});
 
			const resultArrays = await Promise.all(searchPromises);
			for (const results of resultArrays) {
				allResults.push(...results);
			}
 
			// If ALL connector searches failed, re-raise to trigger fallback
			if (allResults.length === 0 && lastError) {
				throw lastError;
			}
 
			// Sort by score, apply topK
			allResults.sort((a, b) => b.similarityScore - a.similarityScore);
			const topResults =
				mergedOptions.topK != null ? allResults.slice(0, mergedOptions.topK) : allResults;
 
			if (topResults.length === 0) {
				return new Tools([]);
			}
 
			// Match back to fetched tool definitions
			const actionNames = new Set(topResults.map((r) => normalizeActionName(r.actionName)));
			const matchedTools = allTools.toArray().filter((t) => actionNames.has(t.name));
 
			// Sort matched tools by semantic search score order
			const actionOrder = new Map(topResults.map((r, i) => [normalizeActionName(r.actionName), i]));
			matchedTools.sort(
				(a, b) =>
					(actionOrder.get(a.name) ?? Number.POSITIVE_INFINITY) -
					(actionOrder.get(b.name) ?? Number.POSITIVE_INFINITY),
			);
 
			return new Tools(matchedTools);
		} catch (error) {
			Eif (error instanceof SemanticSearchError) {
				if (search === 'semantic') {
					throw error;
				}
 
				// Auto mode: silently fall back to local search
				return this.localSearch(query, allTools, mergedOptions);
			}
			throw error;
		}
	}
 
	/**
	 * Search for action names without fetching tools.
	 *
	 * Useful when you need to inspect search results before fetching,
	 * or when building custom filtering logic.
	 *
	 * @param query - Natural language description of needed functionality
	 * @param options - Search options
	 * @returns List of SemanticSearchResult with action names, scores, and metadata
	 *
	 * @example
	 * ```typescript
	 * // Lightweight: inspect results before fetching
	 * const results = await toolset.searchActionNames('manage employees');
	 * for (const r of results) {
	 *   console.log(`${r.actionName}: ${r.similarityScore.toFixed(2)}`);
	 * }
	 *
	 * // Then fetch specific high-scoring actions
	 * const selected = results
	 *   .filter(r => r.similarityScore > 0.7)
	 *   .map(r => r.actionName);
	 * const tools = await toolset.fetchTools({ actions: selected });
	 * ```
	 */
	async searchActionNames(
		query: string,
		options?: SearchActionNamesOptions,
	): Promise<SemanticSearchResult[]> {
		Iif (this.searchConfig === null) {
			throw new ToolSetConfigError(
				'Search is disabled. Initialize StackOneToolSet with a search config to enable.',
			);
		}
 
		const effectiveTopK = options?.topK ?? this.searchConfig.topK;
		const effectiveMinSimilarity = options?.minSimilarity ?? this.searchConfig.minSimilarity;
 
		// Resolve available connectors from account IDs
		let availableConnectors: Set<string> | undefined;
		const effectiveAccountIds = options?.accountIds || this.accountIds;
		Iif (effectiveAccountIds.length > 0) {
			const allTools = await this.fetchTools({ accountIds: effectiveAccountIds });
			availableConnectors = allTools.getConnectors();
			if (availableConnectors.size === 0) {
				return [];
			}
		}
 
		try {
			const client = this.getSemanticClient();
			let allResults: SemanticSearchResult[] = [];
 
			Iif (availableConnectors) {
				// Parallel per-connector search (only user's connectors)
				let connectorsToSearch: Set<string>;
				if (options?.connector) {
					const connectorLower = options.connector.toLowerCase();
					connectorsToSearch = availableConnectors.has(connectorLower)
						? new Set([connectorLower])
						: new Set();
				} else {
					connectorsToSearch = availableConnectors;
				}
 
				const searchPromises = [...connectorsToSearch].map(async (connector) => {
					try {
						const response = await client.search(query, {
							connector,
							topK: effectiveTopK,
							minSimilarity: effectiveMinSimilarity,
						});
						return response.results;
					} catch {
						return [];
					}
				});
 
				const resultArrays = await Promise.all(searchPromises);
				for (const results of resultArrays) {
					allResults.push(...results);
				}
			} else {
				// No account filtering — single global search
				const response = await client.search(query, {
					connector: options?.connector,
					topK: effectiveTopK,
					minSimilarity: effectiveMinSimilarity,
				});
				allResults = response.results;
			}
 
			// Sort by score, normalize action names
			allResults.sort((a, b) => b.similarityScore - a.similarityScore);
			const normalized = allResults.map((r) => ({
				...r,
				actionName: normalizeActionName(r.actionName),
			}));
 
			return effectiveTopK != null ? normalized.slice(0, effectiveTopK) : normalized;
		} catch (error) {
			Eif (error instanceof SemanticSearchError) {
				return [];
			}
			throw error;
		}
	}
 
	/**
	 * Run local BM25+TF-IDF search over already-fetched tools.
	 */
	private async localSearch(
		query: string,
		allTools: Tools,
		options?: Pick<SearchToolsOptions, 'connector' | 'topK' | 'minSimilarity'>,
	): Promise<Tools> {
		const availableConnectors = allTools.getConnectors();
		Iif (availableConnectors.size === 0) {
			return new Tools([]);
		}
 
		const index = new ToolIndex(allTools.toArray());
		const results = await index.search(query, options?.topK ?? 5, options?.minSimilarity ?? 0.0);
 
		const matchedNames = results.map((r) => r.name);
		const toolMap = new Map(allTools.toArray().map((t) => [t.name, t]));
		const filterConnectors = options?.connector
			? new Set([options.connector.toLowerCase()])
			: availableConnectors;
 
		const matchedTools = matchedNames
			.filter((name) => toolMap.has(name))
			.map((name) => toolMap.get(name)!)
			.filter((tool) => tool.connector && filterConnectors.has(tool.connector));
 
		return new Tools(options?.topK != null ? matchedTools.slice(0, options.topK) : matchedTools);
	}
 
	/**
	 * 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 }) => {
			return 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) => {
				return tool.connector && providerSet.has(tool.connector);
			});
		}
 
		// 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 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?: JsonObject | string,
			options?: ExecuteOptions,
		): Promise<JsonObject> => {
			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 = normalizeHeaders(additionalHeaders);
				// defu merges extraHeaders into baseHeaders, both are already branded types
				const actionHeaders = defu(extraHeaders, baseHeaders);
 
				const bodyPayload = this.extractRecord(parsedParams, 'body');
				const rpcBody: JsonObject = bodyPayload ? { ...bodyPayload } : {};
				for (const [key, value] of Object.entries(parsedParams)) {
					if (key === 'body' || key === 'headers' || key === 'path' || key === 'query') {
						continue;
					}
					rpcBody[key] = value as JsonObject[string];
				}
 
				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 JsonObject;
				}
 
				const response = await actionsClient.actions.rpcAction({
					action: name,
					body: rpcBody,
					headers: actionHeaders,
					path: pathParams ?? undefined,
					query: queryParams ?? undefined,
				});
 
				return rpcResponseToJsonObject(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: JsonObject,
		key: 'body' | 'headers' | 'path' | 'query',
	): JsonObject | undefined {
		const value = params[key];
		if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
			return value as JsonObject;
		}
		return undefined;
	}
}