UNPKG

@juspay/neurolink

Version:

The pipe layer of an AI nervous system: one interface connecting provider neurons to your application, across three inference types — generate, stream and decide. `decide` returns typed, calibrated judgements from a non-generative model (~400ms, ~$0.00002

154 lines (153 loc) • 6.75 kB
import type { AIProviderName, ToolUtilities } from "../../types/index.js"; import type { NeuroLink } from "../../neurolink.js"; import type { Tool } from "../../types/index.js"; /** * Build an argument validator for an external MCP tool's JSON Schema, in the * shape the AI SDK's `jsonSchema()` wrapper expects. Returns undefined when * the schema can't be compiled (exotic dialect) — the tool then keeps the * previous declarative-only behaviour instead of failing registration. * * The error message is written for the MODEL (it is fed back verbatim as the * tool-error text): it names the offending fields and restates the contract * (required properties + types) so the retry can succeed on the first attempt. */ export declare function buildMCPSchemaValidator(toolName: string, schema: Record<string, unknown>): Promise<((value: unknown) => { success: true; value: unknown; } | { success: false; error: Error; }) | undefined>; export declare class ToolsManager { private readonly providerName; private directTools; private readonly neurolink?; private readonly utilities?; protected mcpTools?: Record<string, Tool>; protected customTools?: Map<string, unknown>; protected toolExecutor?: (toolName: string, params: unknown, options?: Record<string, unknown>) => Promise<unknown>; protected sessionId?: string; protected userId?: string; constructor(providerName: AIProviderName, directTools: Record<string, unknown>, neurolink?: NeuroLink | undefined, utilities?: ToolUtilities | undefined); /** * BZ-666: Wrap tool execute with output truncation to prevent * context overflow when large results flow into the AI SDK accumulator. * * Passes the AI-SDK second argument (execution options: abortSignal, * toolCallId, messages) through to the inner execute — the native loops * provide an abortSignal there, and dropping it at this wrapper made * every tool uncancellable (deadline overshoot / ghost executions). */ private wrapExecuteWithTruncation; /** * Byte budget for BZ-666 truncation. Reads the instance-level * `tools.outputTruncationMaxBytes` config (see `ToolConfig` / * `NeuroLink.getToolsConfig()`) so hosts can raise or lower the ceiling * without a new env var or constructor param; falls back to the original * hard-coded 51,200 bytes (== DEFAULT_MAX_PREVIEW_BYTES) so existing * consumers see no behavior change. */ private resolveTruncationMaxBytes; /** * The default omission notice names `retrieve_context` as the on-demand * read-back tool. That is only true when this NeuroLink instance actually * registered it (Redis or an artifact store must exist — see * `retrieveContextRegistered` in neurolink.ts). Otherwise hand * `generateToolOutputPreview` a notice that doesn't mention it. */ private resolveTruncationNotice; /** * Truncate an MCP `CallToolResult`-shaped envelope (`{content:[...], * isError?}`) — at the top level, or nested under `data` the way * NeuroLink's own `executeExternalMCPTool` / `{success, data}` wrapper * shapes it — WITHOUT collapsing it to the generic `_truncated` sentinel, * while still honouring `maxBytes` for the envelope AS A WHOLE. * * Only TEXT content items are rewritten (byte-accurate head/tail preview, * same mechanism as a plain string result). `isError` and any non-text * items (images, resources, embedded resources, …) pass through * untouched, and every other top-level field on the result is preserved. * * The budget is enforced on the serialized envelope, not per item: the * bytes the envelope occupies with every text item emptied (structure, * non-text items, other fields) come off the top, and what remains is * water-filled across the text items — items that already fit keep their * text and donate the rest of their share to the larger ones. JSON * escaping and the per-item notice add bytes the raw allocation cannot * see, so the result is re-measured and the text budget tightened until * the whole envelope fits. * * Returns `undefined` when `result` doesn't have this shape at all, AND * when the shape cannot be kept within `maxBytes` — no text items, the * non-text payload alone exceeds the budget, or tightening did not * converge — so the caller's generic sentinel path bounds it instead. * Preserving the shape never buys the right to exceed the ceiling. */ private truncateMcpContentEnvelope; /** * BZ-666: Apply generateToolOutputPreview to tool results to prevent * context overflow when large results flow into the AI SDK accumulator. */ private truncateToolResult; /** * Set session context for MCP tools */ setSessionContext(sessionId?: string, userId?: string): void; private emitToolEvent; /** * Set up tool executor for a provider to enable actual tool execution * @param sdk - The NeuroLinkSDK instance for tool execution * @param functionTag - Function name for logging */ setupToolExecutor(sdk: { customTools: Map<string, unknown>; executeTool: (toolName: string, params: unknown) => Promise<unknown>; }, functionTag: string): void; /** * Get all available tools - direct tools are ALWAYS available * MCP tools are added when available (without blocking) */ getAllTools(): Promise<Record<string, Tool>>; /** * Get direct tools (built-in agent tools) */ getDirectTools(): Record<string, unknown>; /** * Replace the direct tools for this provider instance — used to bind the * built-in file tools to one request's root policy. Providers are created * per request, so this never leaks a boundary into another request. */ setDirectTools(tools: Record<string, unknown>): void; /** * Get MCP tools */ getMCPTools(): Record<string, Tool> | undefined; /** * Get custom tools */ getCustomTools(): Map<string, unknown> | undefined; /** * Process direct tools with event emission wrapping */ private processDirectTools; /** * Process custom tools from setupToolExecutor */ private processCustomTools; /** * Process MCP tools integration */ private processMCPTools; /** * Process external MCP tools */ private processExternalMCPTools; /** * Create a custom tool from tool definition */ private createCustomToolFromDefinition; /** * Create an external MCP tool */ private createExternalMCPTool; }