All files / global/MCP/helpers mapMcpToolToGigaChatFunctionSchema.ts

100% Statements 105/105
100% Branches 104/104
100% Functions 17/17
100% Lines 101/101

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                                                            6x           6x                           61x 41x   20x 18x 36x   18x 18x 16x   2x   2x               86x 167x 167x 156x   11x 11x 11x 20x           16x   4x 4x     11x 7x 7x 7x           86x 82x   4x 4x 4x 2x 2x 1x                 86x 70x   16x 20x 16x 19x   18x 16x 7x 7x   9x 4x 6x   4x 4x   5x 1x 1x   4x                 86x 86x 86x             91x 4x   87x 2x     86x       86x 61x 61x 59x                   86x         86x           4x     86x 28x           15x       86x         28x 28x 28x 13x   28x     86x 8x 7x         1x       86x         1x         86x   86x             16x 3x   13x 13x 2x   11x 11x                     10x           10x 6x           10x 2x     10x                         3x 4x          
/*
  Copyright (C) 2026 Sber
 
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
 
          http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
 
import type { Tool } from '@modelcontextprotocol/sdk/types';
import { GigaChatFunctionSchema } from '@global/gigachat/types/gigachat.types';
 
/**
 * JSON Schema для аргументов / ответа функции в формате GigaChat (поля `parameters`, `return_parameters`).
 * Подмножество JSON Schema: type, properties, items, required, description, enum, default, числовые и строковые ограничения.
 */
export type GigaChatJsonSchemaFragment = Record<string, unknown>;
 
export interface MapMcpToolToGigaChatOptions {
  /** MCP не передаёт примеры; можно задать вручную по имени инструмента. */
  few_shot_examples?: GigaChatFunctionSchema['few_shot_examples'];
}
 
const EMPTY_OBJECT_SCHEMA: GigaChatJsonSchemaFragment = {
  type: 'object',
  properties: {}
};
 
/** Типы `type`, которые GigaChat принимает как одну строку (не массив union). */
const GIGACHAT_JSON_TYPE = new Set([
  'string',
  'number',
  'integer',
  'boolean',
  'array',
  'object'
]);
 
/**
 * API GigaChat не принимает JSON Schema с `type: string[]` (например `["string","null"]` из Zod).
 * Схлопываем в одну строку: первый известный тип, иначе `string`.
 */
function normalizeJsonSchemaTypeField(type: unknown): string | undefined {
  if (typeof type === 'string' && GIGACHAT_JSON_TYPE.has(type)) {
    return type;
  }
  if (Array.isArray(type)) {
    const nonNull = type.filter(
      (t): t is string => typeof t === 'string' && t !== 'null'
    );
    const known = nonNull.find((t) => GIGACHAT_JSON_TYPE.has(t));
    if (known) {
      return known;
    }
    return nonNull.length > 0 ? 'string' : 'string';
  }
  return undefined;
}
 
/**
 * Zod / json-schema часто дают `oneOf`/`anyOf` из веток `{ "const": "x" }`.
 * GigaChat ожидает `type` + `enum` для таких полей (см. truncateMode и т.п.).
 */
function tryFlattenOneOfAnyOfToEnum(obj: Record<string, unknown>): void {
  for (const key of ['oneOf', 'anyOf'] as const) {
    const arr = obj[key];
    if (!Array.isArray(arr) || arr.length === 0) {
      continue;
    }
    const values: unknown[] = [];
    let ok = true;
    for (const branch of arr) {
      if (
        branch &&
        typeof branch === 'object' &&
        !Array.isArray(branch) &&
        'const' in (branch as Record<string, unknown>)
      ) {
        values.push((branch as Record<string, unknown>).const);
      } else {
        ok = false;
        break;
      }
    }
    if (ok && values.length === arr.length) {
      delete obj[key];
      obj.enum = values;
      break;
    }
  }
}
 
function mergeConstIntoEnum(obj: Record<string, unknown>): void {
  if (!('const' in obj)) {
    return;
  }
  const c = obj.const;
  delete obj.const;
  if (!Array.isArray(obj.enum)) {
    obj.enum = [c];
  } else if (!(obj.enum as unknown[]).includes(c)) {
    (obj.enum as unknown[]).push(c);
  }
}
 
/**
 * Для поля с `enum` API GigaChat ожидает согласованный скалярный `type` (часто `string`).
 * Исправляет рассинхрон вроде `type: "integer"` при строковых литералах в enum.
 */
function alignTypeWithEnumValues(obj: Record<string, unknown>): void {
  if (!Array.isArray(obj.enum) || obj.enum.length === 0) {
    return;
  }
  const values = obj.enum as unknown[];
  const allString = values.every((v) => typeof v === 'string');
  const allNumber = values.every(
    (v) => typeof v === 'number' && !Number.isNaN(v as number)
  );
  const allBool = values.every((v) => typeof v === 'boolean');
  if (allString) {
    obj.type = 'string';
    return;
  }
  if (allNumber) {
    const allInt = values.every(
      (v) => typeof v === 'number' && Number.isInteger(v as number)
    );
    obj.type = allInt ? 'integer' : 'number';
    return;
  }
  if (allBool) {
    obj.type = 'boolean';
    return;
  }
  obj.type = 'string';
}
 
/**
 * Листья схемы: привести const / oneOf / enum к виду, который принимает GigaChat.
 */
function finalizePrimitiveSchemaForGigaChat(
  obj: Record<string, unknown>
): void {
  tryFlattenOneOfAnyOfToEnum(obj);
  mergeConstIntoEnum(obj);
  alignTypeWithEnumValues(obj);
}
 
/**
 * Рекурсивно приводит фрагмент JSON Schema к ограничениям GigaChat.
 */
export function normalizeJsonSchemaForGigaChat(node: unknown): unknown {
  if (node === null || typeof node !== 'object') {
    return node;
  }
  if (Array.isArray(node)) {
    return node.map((item) => normalizeJsonSchemaForGigaChat(item));
  }
 
  const obj: Record<string, unknown> = {
    ...(node as Record<string, unknown>)
  };
 
  if ('type' in obj) {
    const single = normalizeJsonSchemaTypeField(obj.type);
    if (single !== undefined) {
      obj.type = single;
    }
  }
 
  /**
   * GigaChat требует у каждого `type: "object"` явный ключ `properties` в схеме
   * (см. валидацию вроде `...environment.properties is missing`).
   * Zod/MCP часто дают только `additionalProperties` или пустой объект без `properties`.
   */
  const propertiesLookLikeObject =
    obj.properties !== undefined &&
    typeof obj.properties === 'object' &&
    obj.properties !== null &&
    !Array.isArray(obj.properties);
 
  if (
    obj.type === undefined &&
    (propertiesLookLikeObject ||
      obj.additionalProperties !== undefined ||
      obj.patternProperties !== undefined)
  ) {
    obj.type = 'object';
  }
 
  if (obj.type === 'object') {
    if (
      obj.properties === undefined ||
      obj.properties === null ||
      typeof obj.properties !== 'object' ||
      Array.isArray(obj.properties)
    ) {
      obj.properties = {};
    }
  }
 
  if (
    typeof obj.properties === 'object' &&
    obj.properties !== null &&
    !Array.isArray(obj.properties)
  ) {
    const props = obj.properties as Record<string, unknown>;
    const next: Record<string, unknown> = {};
    for (const [key, val] of Object.entries(props)) {
      next[key] = normalizeJsonSchemaForGigaChat(val);
    }
    obj.properties = next;
  }
 
  if (obj.items !== undefined) {
    if (Array.isArray(obj.items)) {
      obj.items =
        obj.items.length > 0
          ? normalizeJsonSchemaForGigaChat(obj.items[0])
          : { type: 'string' };
    } else {
      obj.items = normalizeJsonSchemaForGigaChat(obj.items);
    }
  }
 
  if (
    typeof obj.additionalProperties === 'object' &&
    obj.additionalProperties !== null &&
    !Array.isArray(obj.additionalProperties)
  ) {
    obj.additionalProperties = normalizeJsonSchemaForGigaChat(
      obj.additionalProperties
    );
  }
 
  finalizePrimitiveSchemaForGigaChat(obj);
 
  return obj;
}
 
function normalizeObjectSchema(
  schema: Tool['inputSchema'] | NonNullable<Tool['outputSchema']> | undefined,
  fallback: GigaChatJsonSchemaFragment
): GigaChatJsonSchemaFragment {
  if (!schema || typeof schema !== 'object') {
    return { ...fallback };
  }
  const o = schema as Record<string, unknown>;
  if (o.type !== 'object') {
    return { ...fallback };
  }
  const clone = JSON.parse(JSON.stringify(o)) as GigaChatJsonSchemaFragment;
  return normalizeJsonSchemaForGigaChat(clone) as GigaChatJsonSchemaFragment;
}
 
/**
 * Приводит инструмент MCP (`tools/list`) к схеме функции GigaChat:
 * `inputSchema` → `parameters`, `outputSchema` → `return_parameters` (если есть).
 */
export function mapMcpToolToGigaChatFunctionSchema(
  tool: Tool,
  options?: MapMcpToolToGigaChatOptions
): GigaChatFunctionSchema {
  const out: GigaChatFunctionSchema = {
    name: tool.name,
    description: tool.description ?? '',
    parameters: normalizeObjectSchema(tool.inputSchema, EMPTY_OBJECT_SCHEMA)
  };
 
  if (tool.outputSchema) {
    out.return_parameters = normalizeObjectSchema(
      tool.outputSchema,
      EMPTY_OBJECT_SCHEMA
    );
  }
 
  if (options?.few_shot_examples !== undefined) {
    out.few_shot_examples = options.few_shot_examples;
  }
 
  return out;
}
 
/**
 * Маппинг списка инструментов из ответа `mcpClient.listTools()`.
 */
export function mapMcpToolsToGigaChatFunctionSchemas(
  tools: Tool[],
  fewShotByToolName?: Record<
    string,
    NonNullable<GigaChatFunctionSchema['few_shot_examples']>
  >
): GigaChatFunctionSchema[] {
  return tools.map((tool) =>
    mapMcpToolToGigaChatFunctionSchema(tool, {
      few_shot_examples: fewShotByToolName?.[tool.name]
    })
  );
}