{"version":3,"file":"tools.cjs","names":["getDebugLog","ZodErrorV4","ZodErrorV3","z","callToolResultContentTypes","_resolveDetailedOutputHandling","ToolMessage","Command","DynamicStructuredTool"],"sources":["../src/tools.ts"],"sourcesContent":["import { z, ZodError as ZodErrorV4 } from \"zod/v4\";\nimport { ZodError as ZodErrorV3 } from \"zod/v3\";\nimport {\n  type CallToolResult,\n  type ContentBlock as MCPContentBlock,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { Client as MCPClient } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport type {\n  EmbeddedResource,\n  ReadResourceResult,\n  Tool as MCPTool,\n  ListToolsResult,\n} from \"@modelcontextprotocol/sdk/types.js\";\nimport type { RequestOptions } from \"@modelcontextprotocol/sdk/shared/protocol.js\";\nimport { DynamicStructuredTool } from \"@langchain/core/tools\";\nimport type { ContentBlock } from \"@langchain/core/messages\";\nimport { RunnableConfig } from \"@langchain/core/runnables\";\nimport type { CallbackManagerForToolRun } from \"@langchain/core/callbacks/manager\";\nimport { ToolMessage } from \"@langchain/core/messages\";\nimport { Command, getCurrentTaskInput } from \"@langchain/langgraph\";\n\nimport type { Notifications } from \"./types.js\";\n\nimport {\n  _resolveDetailedOutputHandling,\n  callToolResultContentTypes,\n  type CallToolResultContentType,\n  type LoadMcpToolsOptions,\n  type OutputHandling,\n} from \"./types.js\";\nimport type { ToolHooks, State } from \"./hooks.js\";\nimport type { Client } from \"./connection.js\";\nimport { getDebugLog } from \"./logging.js\";\n\nconst debugLog = getDebugLog(\"tools\");\n\n/**\n * JSON Schema type definitions for dereferencing $defs.\n */\ntype JsonSchemaObject = {\n  type?: string;\n  properties?: Record<string, JsonSchemaObject>;\n  items?: JsonSchemaObject | JsonSchemaObject[];\n  additionalProperties?: boolean | JsonSchemaObject;\n  $ref?: string;\n  $defs?: Record<string, JsonSchemaObject>;\n  definitions?: Record<string, JsonSchemaObject>;\n  allOf?: JsonSchemaObject[];\n  anyOf?: JsonSchemaObject[];\n  oneOf?: JsonSchemaObject[];\n  not?: JsonSchemaObject;\n  if?: JsonSchemaObject;\n  then?: JsonSchemaObject;\n  else?: JsonSchemaObject;\n  required?: string[];\n  description?: string;\n  default?: unknown;\n  enum?: unknown[];\n  const?: unknown;\n  [key: string]: unknown;\n};\n\n/**\n * Dereferences $ref pointers in a JSON Schema by inlining the definitions from $defs.\n * This is necessary because some JSON Schema validators (like @cfworker/json-schema)\n * don't automatically resolve $ref references to $defs.\n *\n * @param schema - The JSON Schema to dereference\n * @returns A new schema with all $ref pointers resolved\n */\nfunction dereferenceJsonSchema(schema: JsonSchemaObject): JsonSchemaObject {\n  const definitions = schema.$defs ?? schema.definitions ?? {};\n\n  /**\n   * Recursively resolve $ref pointers in the schema.\n   * Tracks visited refs to prevent infinite recursion with circular references.\n   */\n  function resolveRefs(\n    obj: JsonSchemaObject,\n    visitedRefs: Set<string> = new Set()\n  ): JsonSchemaObject {\n    if (typeof obj !== \"object\" || obj === null) {\n      return obj;\n    }\n\n    // Handle $ref\n    if (obj.$ref && typeof obj.$ref === \"string\") {\n      const refPath = obj.$ref;\n\n      // Only handle local references to $defs or definitions\n      const defsMatch = refPath.match(/^#\\/\\$defs\\/(.+)$/);\n      const definitionsMatch = refPath.match(/^#\\/definitions\\/(.+)$/);\n      const match = defsMatch || definitionsMatch;\n\n      if (match) {\n        const defName = match[1];\n        const definition = definitions[defName];\n\n        if (definition) {\n          // Check for circular reference\n          if (visitedRefs.has(refPath)) {\n            // Return a placeholder for circular refs to avoid infinite loop\n            debugLog(\n              `WARNING: Circular reference detected for ${refPath}, using empty object`\n            );\n            return { type: \"object\" };\n          }\n\n          // Track this ref as visited\n          const newVisitedRefs = new Set(visitedRefs);\n          newVisitedRefs.add(refPath);\n\n          // Merge the resolved definition with any other properties from the original object\n          // (excluding $ref itself)\n          const { $ref: _, ...restOfObj } = obj;\n          const resolvedDef = resolveRefs(definition, newVisitedRefs);\n          return { ...resolvedDef, ...restOfObj };\n        } else {\n          debugLog(`WARNING: Could not resolve $ref: ${refPath}`);\n        }\n      }\n      // For non-local refs, return as-is\n      return obj;\n    }\n\n    // Recursively process all properties\n    const result: JsonSchemaObject = {};\n\n    for (const [key, value] of Object.entries(obj)) {\n      // Skip $defs and definitions as they're no longer needed after dereferencing\n      if (key === \"$defs\" || key === \"definitions\") {\n        continue;\n      }\n\n      if (Array.isArray(value)) {\n        result[key] = value.map((item) =>\n          typeof item === \"object\" && item !== null\n            ? resolveRefs(item as JsonSchemaObject, visitedRefs)\n            : item\n        );\n      } else if (typeof value === \"object\" && value !== null) {\n        result[key] = resolveRefs(value as JsonSchemaObject, visitedRefs);\n      } else {\n        result[key] = value;\n      }\n    }\n\n    return result;\n  }\n\n  return resolveRefs(schema);\n}\n\n/**\n * Deep merges two JSON Schema objects.\n * Arrays are concatenated (with special handling for enum), objects are recursively merged,\n * primitives are overwritten.\n *\n * @param target - The target schema to merge into\n * @param source - The source schema to merge from\n * @returns A new merged schema\n */\nfunction deepMergeSchemas(\n  target: JsonSchemaObject,\n  source: JsonSchemaObject\n): JsonSchemaObject {\n  const result: JsonSchemaObject = { ...target };\n\n  for (const [key, sourceValue] of Object.entries(source)) {\n    const targetValue = result[key];\n\n    if (key === \"required\" && Array.isArray(targetValue)) {\n      // Concatenate and deduplicate required arrays\n      result[key] = [\n        ...new Set([...targetValue, ...(sourceValue as string[])]),\n      ];\n    } else if (key === \"const\") {\n      // When merging const values, convert to enum to allow multiple values\n      const existingConst = result.const;\n      const existingEnum = result.enum as unknown[] | undefined;\n      const values = new Set<unknown>();\n\n      if (existingEnum) {\n        for (const v of existingEnum) values.add(v);\n      }\n      if (existingConst !== undefined) {\n        values.add(existingConst);\n      }\n      values.add(sourceValue);\n\n      // Remove const and use enum instead\n      delete result.const;\n      result.enum = [...values];\n    } else if (key === \"enum\" && Array.isArray(sourceValue)) {\n      // Merge enum values (union of all possible values)\n      const values = new Set<unknown>();\n      if (Array.isArray(targetValue)) {\n        for (const v of targetValue) values.add(v);\n      }\n      // Also include any existing const value\n      if (result.const !== undefined) {\n        values.add(result.const);\n        delete result.const;\n      }\n      for (const v of sourceValue) values.add(v);\n      result[key] = [...values];\n    } else if (\n      key === \"properties\" &&\n      typeof targetValue === \"object\" &&\n      targetValue !== null\n    ) {\n      // Recursively merge properties - merge each property individually\n      const mergedProps: Record<string, JsonSchemaObject> = {\n        ...(targetValue as Record<string, JsonSchemaObject>),\n      };\n      for (const [propKey, propValue] of Object.entries(\n        sourceValue as Record<string, JsonSchemaObject>\n      )) {\n        if (\n          mergedProps[propKey] &&\n          typeof mergedProps[propKey] === \"object\" &&\n          typeof propValue === \"object\"\n        ) {\n          mergedProps[propKey] = deepMergeSchemas(\n            mergedProps[propKey],\n            propValue\n          );\n        } else {\n          mergedProps[propKey] = propValue;\n        }\n      }\n      result[key] = mergedProps;\n    } else if (Array.isArray(sourceValue) && Array.isArray(targetValue)) {\n      // Concatenate arrays\n      result[key] = [...targetValue, ...sourceValue];\n    } else if (\n      typeof sourceValue === \"object\" &&\n      sourceValue !== null &&\n      !Array.isArray(sourceValue) &&\n      typeof targetValue === \"object\" &&\n      targetValue !== null &&\n      !Array.isArray(targetValue)\n    ) {\n      // Recursively merge objects\n      result[key] = deepMergeSchemas(\n        targetValue as JsonSchemaObject,\n        sourceValue as JsonSchemaObject\n      );\n    } else {\n      // Overwrite primitives or when types don't match\n      result[key] = sourceValue;\n    }\n  }\n\n  return result;\n}\n\n/**\n * Extracts and merges properties from if/then/else conditional schemas.\n * This is used when processing allOf items that contain conditionals.\n *\n * @param schema - A schema that may contain if/then/else\n * @returns Properties extracted from both then and else branches\n */\nfunction extractPropertiesFromConditional(\n  schema: JsonSchemaObject\n): JsonSchemaObject {\n  let result: JsonSchemaObject = {};\n\n  // Extract properties from 'then' branch\n  if (schema.then && typeof schema.then === \"object\") {\n    const thenSchema = schema.then as JsonSchemaObject;\n    if (thenSchema.properties) {\n      result = deepMergeSchemas(result, { properties: thenSchema.properties });\n    }\n    if (thenSchema.required) {\n      result.required = [\n        ...new Set([...(result.required || []), ...thenSchema.required]),\n      ];\n    }\n  }\n\n  // Extract properties from 'else' branch\n  if (schema.else && typeof schema.else === \"object\") {\n    const elseSchema = schema.else as JsonSchemaObject;\n    if (elseSchema.properties) {\n      result = deepMergeSchemas(result, { properties: elseSchema.properties });\n    }\n    if (elseSchema.required) {\n      result.required = [\n        ...new Set([...(result.required || []), ...elseSchema.required]),\n      ];\n    }\n  }\n\n  return result;\n}\n\n/**\n * Simplifies a JSON Schema for LLM compatibility by removing patterns that\n * OpenAI and other LLM providers don't support at the top level:\n * - allOf: merged into the main schema\n * - anyOf/oneOf: flattened to the first object variant or merged if all are objects\n * - if/then/else: conditional schemas are removed, but properties are extracted\n * - not: negation constraints are removed\n * - $schema: meta schema reference is removed\n * - unevaluatedProperties: not supported by OpenAI\n *\n * This transformation is applied recursively to nested schemas as well.\n *\n * @param schema - The JSON Schema to simplify\n * @returns A new simplified schema compatible with LLM tool calling APIs\n */\nfunction simplifyJsonSchemaForLLM(schema: JsonSchemaObject): JsonSchemaObject {\n  if (typeof schema !== \"object\" || schema === null) {\n    return schema;\n  }\n\n  // Start with a copy of the schema, excluding unsupported keywords\n  const {\n    allOf,\n    anyOf,\n    oneOf,\n    not: _not,\n    if: schemaIf,\n    then: schemaThen,\n    else: schemaElse,\n    $schema: _$schema,\n    unevaluatedProperties: _unevaluatedProperties,\n    ...baseSchema\n  } = schema;\n\n  let result: JsonSchemaObject = { ...baseSchema };\n\n  // Handle if/then/else at the current level by extracting properties\n  if (schemaIf || schemaThen || schemaElse) {\n    const conditionalProps = extractPropertiesFromConditional({\n      if: schemaIf,\n      then: schemaThen,\n      else: schemaElse,\n    } as JsonSchemaObject);\n    result = deepMergeSchemas(result, conditionalProps);\n    debugLog(`INFO: Extracted properties from if/then/else conditional`);\n  }\n\n  // Handle allOf by merging all schemas into the base\n  if (Array.isArray(allOf)) {\n    for (const subSchema of allOf) {\n      // First extract properties from any if/then/else in this subschema\n      if (subSchema.if || subSchema.then || subSchema.else) {\n        const conditionalProps = extractPropertiesFromConditional(subSchema);\n        result = deepMergeSchemas(result, conditionalProps);\n      }\n      // Then recursively simplify the subschema and merge\n      const simplified = simplifyJsonSchemaForLLM(subSchema);\n      result = deepMergeSchemas(result, simplified);\n    }\n    debugLog(\n      `INFO: Flattened allOf with ${allOf.length} schemas into base schema`\n    );\n  }\n\n  // Handle anyOf/oneOf by attempting to merge object schemas or picking first viable option\n  // Note: When merging anyOf/oneOf, we only merge properties but NOT required arrays,\n  // because the union semantics mean any ONE of the schemas should match, not all.\n  const unionSchemas = anyOf || oneOf;\n  if (Array.isArray(unionSchemas) && unionSchemas.length > 0) {\n    // Check if all schemas in the union are object-like (have type: object or have properties)\n    const allAreObjects = unionSchemas.every(\n      (s) =>\n        typeof s === \"object\" &&\n        s !== null &&\n        (s.type === \"object\" || s.properties)\n    );\n\n    // Collect all properties from all schemas, but only keep required fields\n    // that are common to ALL schemas (intersection)\n    const mergedProperties: Record<string, JsonSchemaObject> = {};\n    const requiredSets: Set<string>[] = [];\n\n    const schemasToMerge = allAreObjects\n      ? unionSchemas\n      : unionSchemas.filter(\n          (s) =>\n            typeof s === \"object\" &&\n            s !== null &&\n            (s.type === \"object\" || s.properties)\n        );\n\n    for (const subSchema of schemasToMerge) {\n      const simplified = simplifyJsonSchemaForLLM(subSchema);\n      // Merge properties\n      if (simplified.properties) {\n        Object.assign(mergedProperties, simplified.properties);\n      }\n      // Collect required sets for intersection\n      if (simplified.required && Array.isArray(simplified.required)) {\n        requiredSets.push(new Set(simplified.required));\n      }\n      // Merge type if present\n      if (simplified.type && !result.type) {\n        result.type = simplified.type;\n      }\n    }\n\n    // Merge the collected properties\n    if (Object.keys(mergedProperties).length > 0) {\n      result.properties = {\n        ...(result.properties as Record<string, JsonSchemaObject>),\n        ...mergedProperties,\n      };\n    }\n\n    // Only add required fields that are common to ALL schemas (intersection)\n    if (requiredSets.length > 0) {\n      const commonRequired = requiredSets.reduce((acc, set) => {\n        return new Set([...acc].filter((x) => set.has(x)));\n      });\n      if (commonRequired.size > 0) {\n        result.required = [\n          ...new Set([...(result.required || []), ...commonRequired]),\n        ];\n      }\n    }\n\n    debugLog(\n      `INFO: Merged ${schemasToMerge.length} object schemas from ${anyOf ? \"anyOf\" : \"oneOf\"}`\n    );\n  }\n\n  // Ensure we have type: \"object\" if there are properties\n  if (result.properties && !result.type) {\n    result.type = \"object\";\n  }\n\n  // Recursively simplify nested schemas in properties\n  if (result.properties) {\n    const simplifiedProperties: Record<string, JsonSchemaObject> = {};\n    for (const [propName, propSchema] of Object.entries(result.properties)) {\n      if (typeof propSchema === \"object\" && propSchema !== null) {\n        simplifiedProperties[propName] = simplifyJsonSchemaForLLM(\n          propSchema as JsonSchemaObject\n        );\n      } else {\n        simplifiedProperties[propName] = propSchema as JsonSchemaObject;\n      }\n    }\n    result.properties = simplifiedProperties;\n  }\n\n  // Simplify items schema for arrays\n  if (result.items) {\n    if (Array.isArray(result.items)) {\n      result.items = result.items.map((item) =>\n        typeof item === \"object\" && item !== null\n          ? simplifyJsonSchemaForLLM(item as JsonSchemaObject)\n          : item\n      );\n    } else if (typeof result.items === \"object\") {\n      result.items = simplifyJsonSchemaForLLM(result.items as JsonSchemaObject);\n    }\n  }\n\n  // Simplify additionalProperties if it's a schema\n  if (\n    typeof result.additionalProperties === \"object\" &&\n    result.additionalProperties !== null\n  ) {\n    result.additionalProperties = simplifyJsonSchemaForLLM(\n      result.additionalProperties as JsonSchemaObject\n    );\n  }\n\n  return result;\n}\n\n/**\n * MCP instance is either a Client or a MCPClient.\n *\n * `MCPClient`: is the base instance from the `@modelcontextprotocol/sdk` package.\n * `Client`: is an extension of the `MCPClient` that adds the `fork` method to easier create a new client with different headers.\n *\n * This distinction is necessary to keep the interface of the `getTools` method simple.\n */\ntype MCPInstance = Client | MCPClient;\n\n/**\n * Custom error class for tool exceptions\n */\nexport class ToolException extends Error {\n  constructor(message: string, cause?: Error) {\n    super(message);\n    this.name = \"ToolException\";\n\n    /**\n     * don't display the large ZodError stack trace\n     */\n    if (\n      cause &&\n      // oxlint-disable-next-line no-instanceof/no-instanceof\n      (cause instanceof ZodErrorV4 || cause instanceof ZodErrorV3)\n    ) {\n      const minifiedZodError = new Error(z.prettifyError(cause));\n      const stackByLine = cause.stack?.split(\"\\n\") || [];\n      minifiedZodError.stack = cause.stack\n        ?.split(\"\\n\")\n        .slice(stackByLine.findIndex((l) => l.includes(\"    at\")))\n        .join(\"\\n\");\n      this.cause = minifiedZodError;\n    } else if (cause) {\n      this.cause = cause;\n    }\n  }\n}\n\nexport function isToolException(error: unknown): error is ToolException {\n  return (\n    typeof error === \"object\" &&\n    error !== null &&\n    \"name\" in error &&\n    error.name === \"ToolException\"\n  );\n}\n\nfunction isResourceReference(\n  resource:\n    | EmbeddedResource[\"resource\"]\n    | ReadResourceResult[\"contents\"][number]\n): boolean {\n  return (\n    typeof resource === \"object\" &&\n    resource !== null &&\n    \"uri\" in resource &&\n    typeof (resource as { uri?: unknown }).uri === \"string\" &&\n    (!(\"blob\" in resource) || resource.blob == null) &&\n    (!(\"text\" in resource) || resource.text == null)\n  );\n}\n\nasync function* _embeddedResourceToStandardFileBlocks(\n  resource:\n    | EmbeddedResource[\"resource\"]\n    | ReadResourceResult[\"contents\"][number],\n  client: MCPInstance\n): AsyncGenerator<\n  | (ContentBlock.Data.StandardFileBlock & ContentBlock.Data.Base64ContentBlock)\n  | (ContentBlock.Data.StandardFileBlock &\n      ContentBlock.Data.PlainTextContentBlock)\n> {\n  if (isResourceReference(resource)) {\n    const response: ReadResourceResult = await client.readResource({\n      uri: resource.uri,\n    });\n    for (const content of response.contents) {\n      yield* _embeddedResourceToStandardFileBlocks(content, client);\n    }\n    return;\n  }\n\n  if (\"blob\" in resource && resource.blob != null) {\n    yield {\n      type: \"file\",\n      source_type: \"base64\",\n      data: resource.blob,\n      mime_type: resource.mimeType,\n      ...(resource.uri != null ? { metadata: { uri: resource.uri } } : {}),\n    } as ContentBlock.Data.StandardFileBlock &\n      ContentBlock.Data.Base64ContentBlock;\n  }\n  if (\"text\" in resource && resource.text != null) {\n    yield {\n      type: \"file\",\n      source_type: \"text\",\n      mime_type: resource.mimeType,\n      text: resource.text,\n      ...(resource.uri != null ? { metadata: { uri: resource.uri } } : {}),\n    } as ContentBlock.Data.StandardFileBlock &\n      ContentBlock.Data.PlainTextContentBlock;\n  }\n}\n\nasync function _toolOutputToContentBlocks(\n  content: MCPContentBlock,\n  useStandardContentBlocks: true,\n  client: MCPInstance,\n  toolName: string,\n  serverName: string\n): Promise<ContentBlock.Multimodal.Standard[]>;\nasync function _toolOutputToContentBlocks(\n  content: MCPContentBlock,\n  useStandardContentBlocks: false | undefined,\n  client: MCPInstance,\n  toolName: string,\n  serverName: string\n): Promise<ContentBlock[]>;\nasync function _toolOutputToContentBlocks(\n  content: MCPContentBlock,\n  useStandardContentBlocks: boolean | undefined,\n  client: MCPInstance,\n  toolName: string,\n  serverName: string\n): Promise<(ContentBlock | ContentBlock.Multimodal.Standard)[]>;\nasync function _toolOutputToContentBlocks(\n  content: MCPContentBlock,\n  useStandardContentBlocks: boolean | undefined,\n  client: MCPInstance,\n  toolName: string,\n  serverName: string\n): Promise<(ContentBlock | ContentBlock.Multimodal.Standard)[]> {\n  const blocks: ContentBlock.Data.StandardFileBlock[] = [];\n  switch (content.type) {\n    case \"text\":\n      return [\n        {\n          type: \"text\",\n          ...(useStandardContentBlocks\n            ? {\n                source_type: \"text\",\n              }\n            : {}),\n          text: content.text,\n        } as ContentBlock.Text,\n      ];\n    case \"image\":\n      if (useStandardContentBlocks) {\n        return [\n          {\n            type: \"image\",\n            source_type: \"base64\",\n            data: content.data,\n            mime_type: content.mimeType,\n          } as ContentBlock.Data.StandardImageBlock,\n        ];\n      }\n      return [\n        {\n          type: \"image_url\",\n          image_url: {\n            url: `data:${content.mimeType};base64,${content.data}`,\n          },\n        } as ContentBlock,\n      ];\n    case \"audio\":\n      // We don't check `useStandardContentBlocks` here because we only support audio via\n      // standard content blocks\n      return [\n        {\n          type: \"audio\",\n          source_type: \"base64\",\n          data: content.data,\n          mime_type: content.mimeType,\n        } as ContentBlock.Data.StandardAudioBlock,\n      ];\n    case \"resource\":\n      for await (const block of _embeddedResourceToStandardFileBlocks(\n        content.resource,\n        client\n      )) {\n        blocks.push(block);\n      }\n      return blocks;\n    case \"resource_link\": {\n      return [\n        {\n          type: \"file\",\n          source_type: \"url\",\n          url: content.uri,\n          mime_type: content.mimeType,\n        } as ContentBlock.Data.StandardFileBlock &\n          ContentBlock.Data.URLContentBlock,\n      ];\n    }\n    default:\n      throw new ToolException(\n        `MCP tool '${toolName}' on server '${serverName}' returned a content block with unexpected type \"${\n          (content as { type: string }).type\n        }.\" Expected one of ${callToolResultContentTypes.map((t: string) => `\"${t}\"`).join(\", \")}.`\n      );\n  }\n}\n\nasync function _embeddedResourceToArtifact(\n  resource: EmbeddedResource,\n  useStandardContentBlocks: boolean | undefined,\n  client: MCPInstance,\n  toolName: string,\n  serverName: string\n): Promise<(EmbeddedResource | ContentBlock.Multimodal.Standard)[]> {\n  if (useStandardContentBlocks) {\n    return _toolOutputToContentBlocks(\n      resource,\n      useStandardContentBlocks,\n      client,\n      toolName,\n      serverName\n    );\n  }\n\n  if (\n    (!(\"blob\" in resource) || resource.blob == null) &&\n    (!(\"text\" in resource) || resource.text == null) &&\n    \"uri\" in resource &&\n    typeof resource.uri === \"string\"\n  ) {\n    const response: ReadResourceResult = await client.readResource({\n      uri: resource.uri,\n    });\n\n    return response.contents.map(\n      (content: ReadResourceResult[\"contents\"][number]) => ({\n        type: \"resource\",\n        resource: {\n          ...content,\n        },\n      })\n    );\n  }\n  return [resource];\n}\n\n/**\n * Special artifact type for structured content from MCP tool results\n * @internal\n */\ntype MCPStructuredContentArtifact = {\n  type: \"mcp_structured_content\";\n  data: NonNullable<CallToolResult[\"structuredContent\"]>;\n};\n\n/**\n * Special artifact type for meta information from MCP tool results\n * @internal\n */\ntype MCPMetaArtifact = {\n  type: \"mcp_meta\";\n  data: NonNullable<CallToolResult[\"_meta\"]>;\n};\n\n/**\n * Extended artifact type that includes MCP-specific artifacts\n * @internal\n */\ntype ExtendedArtifact =\n  | EmbeddedResource\n  | ContentBlock.Multimodal.Standard\n  | MCPStructuredContentArtifact\n  | MCPMetaArtifact;\n\n/**\n * Content type that may include structuredContent and meta\n * @internal\n */\ntype ExtendedContent =\n  | (ContentBlock | ContentBlock.Multimodal.Standard)[]\n  | (ContentBlock.Text & {\n      structuredContent?: NonNullable<CallToolResult[\"structuredContent\"]>;\n      meta?: NonNullable<CallToolResult[\"_meta\"]>;\n    })\n  | string;\n\n/**\n * @internal\n */\ntype ConvertCallToolResultArgs = {\n  /**\n   * The name of the server to call the tool on (used for error messages and logging)\n   */\n  serverName: string;\n  /**\n   * The name of the tool that was called\n   */\n  toolName: string;\n  /**\n   * The result from the MCP tool call\n   */\n  result: CallToolResult;\n  /**\n   * The MCP client that was used to call the tool\n   */\n  client: Client | MCPClient;\n  /**\n   * If true, the tool will use LangChain's standard multimodal content blocks for tools that output\n   * image or audio content. This option has no effect on handling of embedded resource tool output.\n   */\n  useStandardContentBlocks?: boolean;\n  /**\n   * Defines where to place each tool output type in the LangChain ToolMessage.\n   */\n  outputHandling?: OutputHandling;\n};\n\nfunction _getOutputTypeForContentType(\n  contentType: CallToolResultContentType,\n  outputHandling?: OutputHandling\n): \"content\" | \"artifact\" {\n  if (outputHandling === \"content\" || outputHandling === \"artifact\") {\n    return outputHandling;\n  }\n\n  const resolved = _resolveDetailedOutputHandling(outputHandling);\n\n  return (\n    resolved[contentType] ??\n    (contentType === \"resource\" ? \"artifact\" : \"content\")\n  );\n}\n\n/**\n * Process the result from calling an MCP tool.\n * Extracts text content and non-text content for better agent compatibility.\n *\n * @internal\n *\n * @param args - The arguments to pass to the tool\n * @returns A tuple of [textContent, nonTextContent]\n */\nasync function _convertCallToolResult({\n  serverName,\n  toolName,\n  result,\n  client,\n  useStandardContentBlocks,\n  outputHandling,\n}: ConvertCallToolResultArgs): Promise<[ExtendedContent, ExtendedArtifact[]]> {\n  if (!result) {\n    throw new ToolException(\n      `MCP tool '${toolName}' on server '${serverName}' returned an invalid result - tool call response was undefined`\n    );\n  }\n\n  if (!Array.isArray(result.content)) {\n    throw new ToolException(\n      `MCP tool '${toolName}' on server '${serverName}' returned an invalid result - expected an array of content, but was ${typeof result.content}`\n    );\n  }\n\n  if (result.isError) {\n    throw new ToolException(\n      `MCP tool '${toolName}' on server '${serverName}' returned an error: ${result.content\n        .map((content: MCPContentBlock) =>\n          content.type === \"text\" ? content.text : \"\"\n        )\n        .join(\"\\n\")}`\n    );\n  }\n\n  const convertedContent: (ContentBlock | ContentBlock.Multimodal.Standard)[] =\n    (\n      await Promise.all(\n        result.content\n          .filter(\n            (content: MCPContentBlock) =>\n              _getOutputTypeForContentType(content.type, outputHandling) ===\n              \"content\"\n          )\n          .map((content: MCPContentBlock) =>\n            _toolOutputToContentBlocks(\n              content,\n              useStandardContentBlocks,\n              client,\n              toolName,\n              serverName\n            )\n          )\n      )\n    ).flat();\n\n  // Create the text content output\n  const artifacts = (\n    await Promise.all(\n      (\n        result.content.filter(\n          (content: MCPContentBlock) =>\n            _getOutputTypeForContentType(content.type, outputHandling) ===\n            \"artifact\"\n        ) as EmbeddedResource[]\n      ).map((content: EmbeddedResource) => {\n        return _embeddedResourceToArtifact(\n          content,\n          useStandardContentBlocks,\n          client,\n          toolName,\n          serverName\n        );\n      })\n    )\n  ).flat();\n\n  // Extract structuredContent and _meta from result\n  // These are optional fields that are part of the CallToolResult type\n  const structuredContent = result.structuredContent;\n  const meta = result._meta;\n\n  // Add structuredContent and meta as special artifacts\n  const enhancedArtifacts: ExtendedArtifact[] = [...artifacts];\n  if (structuredContent) {\n    enhancedArtifacts.push({\n      type: \"mcp_structured_content\",\n      data: structuredContent,\n    });\n  }\n  if (meta) {\n    enhancedArtifacts.push({\n      type: \"mcp_meta\",\n      data: meta,\n    });\n  }\n\n  // If we have structuredContent or meta, create an enhanced content that includes all info\n  if (convertedContent.length === 1 && convertedContent[0].type === \"text\") {\n    const textBlock = convertedContent[0] as ContentBlock.Text;\n    const textContent = textBlock.text;\n\n    // If we have structuredContent or meta, wrap the content with additional info\n    if (structuredContent || meta) {\n      return [\n        {\n          ...textBlock,\n          ...(structuredContent ? { structuredContent } : {}),\n          ...(meta ? { meta } : {}),\n        } as ExtendedContent,\n        enhancedArtifacts,\n      ];\n    }\n\n    return [textContent as ExtendedContent, enhancedArtifacts];\n  }\n\n  return [convertedContent as ExtendedContent, enhancedArtifacts];\n}\n\n/**\n * @internal\n */\ntype CallToolArgs = {\n  /**\n   * The name of the server to call the tool on (used for error messages and logging)\n   */\n  serverName: string;\n  /**\n   * The name of the tool to call\n   */\n  toolName: string;\n  /**\n   * The MCP client to call the tool on\n   */\n  client: Client | MCPClient;\n  /**\n   * The arguments to pass to the tool - must conform to the tool's input schema\n   */\n  args: Record<string, unknown>;\n  /**\n   * Optional RunnableConfig with timeout settings\n   */\n  config?: RunnableConfig;\n  /**\n   * If true, the tool will use LangChain's standard multimodal content blocks for tools that output\n   * image or audio content. This option has no effect on handling of embedded resource tool output.\n   */\n  useStandardContentBlocks?: boolean;\n  /**\n   * Defines where to place each tool output type in the LangChain ToolMessage.\n   */\n  outputHandling?: OutputHandling;\n\n  /**\n   * `onProgress` callbacks used for tool calls.\n   */\n  onProgress?: Notifications[\"onProgress\"];\n\n  /**\n   * `beforeToolCall` callbacks used for tool calls.\n   */\n  beforeToolCall?: ToolHooks[\"beforeToolCall\"];\n\n  /**\n   * `afterToolCall` callbacks used for tool calls.\n   */\n  afterToolCall?: ToolHooks[\"afterToolCall\"];\n};\n\ntype ContentBlocksWithArtifacts =\n  | [ExtendedContent, ExtendedArtifact[]]\n  | Command;\n\n/**\n * Call an MCP tool.\n *\n * Use this with `.bind` to capture the fist three arguments, then pass to the constructor of DynamicStructuredTool.\n *\n * @internal\n * @param args - The arguments to pass to the tool\n * @returns A tuple of [textContent, nonTextContent]\n */\nasync function _callTool({\n  serverName,\n  toolName,\n  client,\n  args,\n  config,\n  useStandardContentBlocks,\n  outputHandling,\n  onProgress,\n  beforeToolCall,\n  afterToolCall,\n}: CallToolArgs): Promise<ContentBlocksWithArtifacts> {\n  try {\n    debugLog(`INFO: Calling tool ${toolName}(${JSON.stringify(args)})`);\n\n    // Extract timeout from RunnableConfig and pass to MCP SDK\n    // Note: ensureConfig() converts timeout into an AbortSignal and deletes the timeout field.\n    // To preserve the numeric timeout for SDKs that accept an explicit timeout value, we read\n    // it from metadata.timeoutMs if present, falling back to any direct timeout.\n    const numericTimeout =\n      (config?.metadata?.timeoutMs as number | undefined) ?? config?.timeout;\n    const requestOptions: RequestOptions = {\n      ...(numericTimeout ? { timeout: numericTimeout } : {}),\n      ...(config?.signal ? { signal: config.signal } : {}),\n      ...(onProgress\n        ? {\n            onprogress: (progress) => {\n              // oxlint-disable-next-line @typescript-eslint/no-floating-promises\n              onProgress?.(progress, {\n                type: \"tool\",\n                name: toolName,\n                args,\n                server: serverName,\n              });\n            },\n          }\n        : {}),\n    };\n\n    let state: State = {};\n    try {\n      state = getCurrentTaskInput(config) as State;\n    } catch (error) {\n      debugLog(\n        `State can't be derrived as LangGraph is not used: ${String(error)}`\n      );\n    }\n\n    const beforeToolCallInterception = await beforeToolCall?.(\n      {\n        name: toolName,\n        args,\n        serverName,\n      },\n      state,\n      config ?? {}\n    );\n\n    const finalArgs = Object.assign(\n      args,\n      beforeToolCallInterception?.args || {}\n    );\n\n    const headers = beforeToolCallInterception?.headers || {};\n    const hasHeaderChanges = Object.entries(headers).length > 0;\n    if (hasHeaderChanges && typeof (client as Client).fork !== \"function\") {\n      throw new ToolException(\n        `MCP client for server \"${serverName}\" does not support header changes`\n      );\n    }\n\n    const finalClient =\n      hasHeaderChanges && typeof (client as Client).fork === \"function\"\n        ? await (client as Client).fork(headers)\n        : client;\n\n    const callToolArgs: Parameters<typeof finalClient.callTool> = [\n      {\n        name: toolName,\n        arguments: finalArgs,\n      },\n    ];\n\n    if (Object.keys(requestOptions).length > 0) {\n      callToolArgs.push(undefined); // optional output schema arg\n      callToolArgs.push(requestOptions);\n    }\n\n    const result = (await finalClient.callTool(\n      ...callToolArgs\n    )) as CallToolResult;\n    const [content, artifacts] = await _convertCallToolResult({\n      serverName,\n      toolName,\n      result,\n      client: finalClient,\n      useStandardContentBlocks,\n      outputHandling,\n    });\n\n    // Convert ExtendedContent to the format expected by afterToolCall\n    // afterToolCall expects: string | (ContentBlock | ContentBlock.Data.DataContentBlock)[]\n    // ExtendedContent can be: string | ContentBlock[] | (ContentBlock.Text & {...})\n    const normalizedContent:\n      | string\n      | (ContentBlock | ContentBlock.Data.DataContentBlock)[] =\n      typeof content === \"string\"\n        ? content\n        : Array.isArray(content)\n          ? (content as (ContentBlock | ContentBlock.Data.DataContentBlock)[])\n          : ([content] as (\n              | ContentBlock\n              | ContentBlock.Data.DataContentBlock\n            )[]);\n\n    // Filter artifacts to only include types expected by afterToolCall\n    // afterToolCall expects: (EmbeddedResource | ContentBlock.Multimodal.Standard)[]\n    // ExtendedArtifact includes additional types (MCPStructuredContentArtifact, MCPMetaArtifact)\n    // which need to be filtered out\n    const normalizedArtifacts: (\n      | EmbeddedResource\n      | ContentBlock.Multimodal.Standard\n    )[] = artifacts.filter(\n      (\n        artifact\n      ): artifact is EmbeddedResource | ContentBlock.Multimodal.Standard =>\n        artifact.type === \"resource\" ||\n        (artifact.type !== \"mcp_structured_content\" &&\n          artifact.type !== \"mcp_meta\" &&\n          typeof artifact === \"object\" &&\n          artifact !== null &&\n          \"source_type\" in artifact)\n    ) as (EmbeddedResource | ContentBlock.Multimodal.Standard)[];\n\n    const interceptedResult = await afterToolCall?.(\n      {\n        name: toolName,\n        args: finalArgs,\n        result: [normalizedContent, normalizedArtifacts],\n        serverName,\n      },\n      state,\n      config ?? {}\n    );\n\n    if (!interceptedResult) {\n      return [content, artifacts];\n    }\n\n    if (typeof interceptedResult.result === \"string\") {\n      return [interceptedResult.result, []];\n    }\n\n    if (Array.isArray(interceptedResult.result)) {\n      return interceptedResult.result as ContentBlocksWithArtifacts;\n    }\n\n    if (ToolMessage.isInstance(interceptedResult.result)) {\n      return [interceptedResult.result.contentBlocks, []];\n    }\n\n    // oxlint-disable-next-line no-instanceof/no-instanceof\n    if (interceptedResult?.result instanceof Command) {\n      return interceptedResult.result;\n    }\n\n    throw new Error(\n      `Unexpected result value type from afterToolCall: expected either a Command, a ToolMessage or a tuple of ContentBlock and Artifact, but got ${interceptedResult.result}`\n    );\n  } catch (error) {\n    // oxlint-disable-next-line no-instanceof/no-instanceof\n    if (error instanceof ZodErrorV4 || error instanceof ZodErrorV3) {\n      throw new ToolException(z.prettifyError(error), error);\n    }\n\n    debugLog(`Error calling tool ${toolName}: ${String(error)}`);\n    if (isToolException(error)) {\n      throw error;\n    }\n    throw new ToolException(`Error calling tool ${toolName}: ${String(error)}`);\n  }\n}\n\nconst defaultLoadMcpToolsOptions: LoadMcpToolsOptions = {\n  throwOnLoadError: true,\n  prefixToolNameWithServerName: false,\n  additionalToolNamePrefix: \"\",\n  useStandardContentBlocks: false,\n};\n\n/**\n * Load all tools from an MCP client.\n *\n * @param serverName - The name of the server to load tools from\n * @param client - The MCP client\n * @returns A list of LangChain tools\n */\nexport async function loadMcpTools(\n  serverName: string,\n  client: MCPInstance,\n  options?: LoadMcpToolsOptions\n): Promise<DynamicStructuredTool[]> {\n  const {\n    throwOnLoadError,\n    prefixToolNameWithServerName,\n    additionalToolNamePrefix,\n    useStandardContentBlocks,\n    outputHandling,\n    defaultToolTimeout,\n  } = {\n    ...defaultLoadMcpToolsOptions,\n    ...(options ?? {}),\n  };\n\n  const mcpTools: MCPTool[] = [];\n\n  // Get tools in a single operation\n  let toolsResponse: ListToolsResult | undefined;\n  do {\n    toolsResponse = await client.listTools({\n      ...(toolsResponse?.nextCursor\n        ? { cursor: toolsResponse.nextCursor }\n        : {}),\n    });\n    mcpTools.push(...(toolsResponse.tools || []));\n  } while (toolsResponse.nextCursor);\n\n  debugLog(`INFO: Found ${mcpTools.length} MCP tools`);\n\n  const initialPrefix = additionalToolNamePrefix\n    ? `${additionalToolNamePrefix}__`\n    : \"\";\n  const serverPrefix = prefixToolNameWithServerName ? `${serverName}__` : \"\";\n  const toolNamePrefix = `${initialPrefix}${serverPrefix}`;\n\n  // Filter out tools without names and convert in a single map operation\n  return (\n    await Promise.all(\n      mcpTools\n        .filter((tool: MCPTool) => !!tool.name)\n        .map(async (tool: MCPTool) => {\n          try {\n            if (!tool.inputSchema.properties) {\n              // Workaround for MCP SDK not consistently providing properties\n              tool.inputSchema.properties = {};\n            }\n\n            // Dereference $defs/$ref in the schema to support Pydantic v2 schemas\n            // and other JSON schemas that use $defs for nested type definitions\n            const dereferencedSchema = dereferenceJsonSchema(\n              tool.inputSchema as JsonSchemaObject\n            );\n\n            // Simplify schema for LLM compatibility by removing allOf, anyOf, oneOf,\n            // if/then/else, not, and other patterns that OpenAI doesn't support\n            const simplifiedSchema =\n              simplifyJsonSchemaForLLM(dereferencedSchema);\n\n            const dst = new DynamicStructuredTool({\n              name: `${toolNamePrefix}${tool.name}`,\n              description: tool.description || \"\",\n              schema: simplifiedSchema,\n              responseFormat: \"content_and_artifact\",\n              metadata: { annotations: tool.annotations },\n              defaultConfig: defaultToolTimeout\n                ? { timeout: defaultToolTimeout }\n                : undefined,\n              func: async (\n                args: Record<string, unknown>,\n                _runManager?: CallbackManagerForToolRun,\n                config?: RunnableConfig\n              ) => {\n                return _callTool({\n                  serverName,\n                  toolName: tool.name,\n                  client,\n                  args,\n                  config,\n                  useStandardContentBlocks,\n                  outputHandling,\n                  onProgress: options?.onProgress,\n                  beforeToolCall: options?.beforeToolCall,\n                  afterToolCall: options?.afterToolCall,\n                });\n              },\n            });\n            debugLog(`INFO: Successfully loaded tool: ${dst.name}`);\n            return dst;\n          } catch (error) {\n            debugLog(`ERROR: Failed to load tool \"${tool.name}\":`, error);\n            if (throwOnLoadError) {\n              throw error;\n            }\n            return null;\n          }\n        })\n    )\n  ).filter(Boolean) as DynamicStructuredT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