All files / backend/controllers mcp.ts

80.64% Statements 25/31
50% Branches 3/6
50% Functions 5/10
89.28% Lines 25/28

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                                                1x   1x   1x     3x 6x                                               3x         3x     3x   3x 1x     1x   1x     1x         3x 3x       3x   3x               3x     1x 1x   1x   1x 1x                         4x 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 { Express, Response } from 'express';
import { RequestWithBenefits } from './gigachat';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { getLoggerWithTag } from '@global/logger/v2/logger.mjs';
import { jsonata } from '@back/MCPServer/schemas/jsonata';
import { search } from '@back/MCPServer/schemas/search';
 
const logger = getLoggerWithTag('controller-mcp');
 
export const MCP_ENDPOINT = '/seaf-core/api/mcp';
 
const SCHEMAS = [jsonata, search];
 
function registerMcpTools(server: McpServer, req: RequestWithBenefits) {
  SCHEMAS.forEach((tool) => {
    server.registerTool(
      tool.name,
      {
        title: tool.schema.title,
        description: tool.schema.description,
        inputSchema: tool.schema.inputSchema
      },
      tool.createHandler(req)
    );
  });
}
 
/*
  Stateless Streamable HTTP (sessionIdGenerator: undefined): на каждый HTTP-запрос
  создаём новый McpServer + transport и закрываем их после ответа.
  SDK запрещает переиспользовать stateless transport между запросами
  («Stateless transport cannot be reused across requests»).
  Официальные примеры тоже делают server/transport per request.
  См.:
  - https://github.com/modelcontextprotocol/typescript-sdk/tree/main/examples
  Дополнительно: handlers тулов замыкаются на req (storage/userProfile) —
  per-request server изолирует контекст вызывающего.
*/
async function handleMcpRequest(req: RequestWithBenefits, res: Response) {
  const server = new McpServer({
    name: 'seaf-archtool',
    version: '1.0.0'
  });
 
  registerMcpTools(server, req);
 
  let transport: StreamableHTTPServerTransport;
  let cleanedUp = false;
 
  const cleanup = () => {
    Iif (cleanedUp) {
      return;
    }
    cleanedUp = true;
 
    transport?.close().catch((error: Error) => {
      logger.error(() => `MCP transport close error: ${error.message}`);
    });
    server.close().catch((error: Error) => {
      logger.error(() => `MCP server close error: ${error.message}`);
    });
  };
 
  try {
    transport = new StreamableHTTPServerTransport({
      sessionIdGenerator: undefined
    });
 
    await server.connect(transport);
 
    res.on('close', cleanup);
 
    /*
      Отдельная валидация аргументов не производится:
      McpServer при tools/call сам прогоняет arguments через Zod inputSchema
      (validateToolInput → safeParse). Ошибка схемы уходит клиенту как
      CallToolResult с isError: true, а не как HTTP 500 из catch ниже.
    */
    await transport.handleRequest(req, res, req.body);
  } catch (error) {
    const message =
      error instanceof Error ? error.message : JSON.stringify(error);
    logger.error(() => `MCP request error: ${message}`, error);
 
    cleanup();
 
    Eif (!res.headersSent) {
      res.status(500).json({
        jsonrpc: '2.0',
        error: {
          code: -32603,
          message: 'Internal server error'
        },
        id: null
      });
    }
  }
}
 
export default function controllerMcp(app: Express) {
  app.get(MCP_ENDPOINT, handleMcpRequest);
  app.post(MCP_ENDPOINT, handleMcpRequest);
}