import * as _backstage_backend_plugin_api from '@backstage/backend-plugin-api'; import { LoggerService, RootConfigService, DatabaseService, HttpAuthService } from '@backstage/backend-plugin-api'; import { GenerateContentResponse } from '@google/genai'; import { Config } from '@backstage/config'; import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import express from 'express'; /** * mcpChatPlugin backend plugin * * @public */ declare const mcpChatPlugin: _backstage_backend_plugin_api.BackendFeature; /** * Valid roles for chat messages. * Use these values when constructing ChatMessage objects. * * @public */ declare const VALID_ROLES: readonly ["user", "assistant", "system", "tool"]; /** * MCP server connection types. * * - `STDIO`: Local process communication via stdin/stdout * - `STREAMABLE_HTTP`: Streamable HTTP transport * * @public */ declare enum MCPServerType { STDIO = "stdio", STREAMABLE_HTTP = "streamable-http" } /** * Supported LLM provider types. * Use this type for type-safe provider selection. * * @public */ type LLMProviderType = 'openai' | 'openai-responses' | 'azure-openai' | 'claude' | 'gemini' | 'ollama' | 'litellm'; /** * Configuration for an MCP server. * Supports multiple connection types: STDIO and Streamable HTTP. * * @example * ```typescript * // STDIO server using npx * const stdioServer: MCPServerConfig = { * id: 'filesystem', * name: 'File System', * type: MCPServerType.STDIO, * npxCommand: '@modelcontextprotocol/server-filesystem', * args: ['/path/to/directory'] * }; * * // HTTP server * const httpServer: MCPServerConfig = { * id: 'remote-api', * name: 'Remote API', * type: MCPServerType.STREAMABLE_HTTP, * url: 'https://api.example.com/mcp' * }; * ``` * * @public */ interface MCPServerConfig { /** Unique identifier for the server */ id: string; /** Human-readable name for display */ name: string; /** Connection type: stdio or streamable-http */ type: MCPServerType; /** Path to a local script (for STDIO servers) */ scriptPath?: string; /** NPX package command to run (for STDIO servers) */ npxCommand?: string; /** Command-line arguments to pass to the server */ args?: string[]; /** URL endpoint (for HTTP servers) */ url?: string; /** List of tools to be excluded for the MCP Server */ disabledTools?: string[]; } /** * Sensitive configuration for an MCP server. * Contains environment variables and HTTP headers that may include secrets. * * @example * ```typescript * const secrets: MCPServerSecrets = { * env: { * API_KEY: 'your-secret-key', * DATABASE_URL: 'postgres://...' * }, * headers: { * 'Authorization': 'Bearer token123' * } * }; * ``` * * @public */ interface MCPServerSecrets { /** Environment variables to pass to the server process */ env?: Record; /** HTTP headers to include in requests (for HTTP-based servers) */ headers?: Record; } /** * Complete MCP server configuration combining base config and secrets. * * @public */ type MCPServerFullConfig = MCPServerConfig & MCPServerSecrets; /** * MCP server with runtime status information. * Used to display server health in the UI. * * @public */ type MCPServer = MCPServerConfig & { /** Current connection and validation status */ status: { /** Whether the server configuration is valid */ valid: boolean; /** Whether the server is currently connected */ connected: boolean; /** Error message if connection failed */ error?: string; }; }; /** * Aggregated status data for all MCP servers. * * @public */ interface MCPServerStatusData { /** Total number of configured servers */ total: number; /** Number of servers with valid configuration */ valid: number; /** Number of currently connected servers */ active: number; /** List of all servers with their status */ servers: MCPServer[]; /** ISO timestamp of when this status was generated */ timestamp: string; } /** * Configuration for an LLM provider. * * @example * ```typescript * const openaiConfig: ProviderConfig = { * type: 'openai', * apiKey: 'sk-...', * baseUrl: 'https://api.openai.com/v1', * model: 'gpt-4' * }; * * const ollamaConfig: ProviderConfig = { * type: 'ollama', * baseUrl: 'http://localhost:11434', * model: 'llama2' * }; * ``` * * @public */ interface ProviderConfig { /** Provider type identifier */ type: string; /** API key for authentication (optional for local providers like Ollama) */ apiKey?: string; /** Base URL for the provider's API */ baseUrl: string; /** Model identifier to use */ model: string; /** Azure OpenAI deployment name. Required when using the `azure-openai` provider type. */ deploymentName?: string; /** Logger for debugging */ logger?: LoggerService; /** Maximum number of tokens to generate (default: 1000 for OpenAI-compatible, 4096 for Claude, 8192 for Gemini) */ maxTokens?: number; /** Temperature for response randomness, between 0 and 1 (default: 0.7) */ temperature?: number; } /** * Runtime information about an active LLM provider. * Used for status display and monitoring. * * @public */ interface ProviderInfo { /** Provider type identifier (e.g., 'openai', 'claude') */ id: string; /** Currently configured model */ model: string; /** API base URL */ baseUrl: string; /** Current connection status */ connection: ProviderConnectionStatus; } /** * Connection test result for an LLM provider. * * @public */ interface ProviderConnectionStatus { /** Whether the provider is reachable and authenticated */ connected: boolean; /** List of available models (if supported by the provider) */ models?: string[]; /** Error message if connection failed */ error?: string; } /** * Aggregated status data for all LLM providers. * * @public */ interface ProviderStatusData { /** List of all configured providers with their status */ providers: ProviderInfo[]; /** Summary statistics */ summary: { /** Total number of configured providers */ totalProviders: number; /** Number of providers that passed connection test */ healthyProviders: number; /** Error message if status check failed */ error?: string; }; /** ISO timestamp of when this status was generated */ timestamp: string; } /** * A chat message in the conversation. * Compatible with OpenAI's Chat Completions API message format. * * @example * ```typescript * // User message * const userMsg: ChatMessage = { * role: 'user', * content: 'What files are in the current directory?' * }; * * // Assistant message with tool call * const assistantMsg: ChatMessage = { * role: 'assistant', * content: null, * tool_calls: [{ * id: 'call_123', * type: 'function', * function: { name: 'list_files', arguments: '{"path": "."}' } * }] * }; * * // Tool response * const toolMsg: ChatMessage = { * role: 'tool', * content: '["file1.txt", "file2.txt"]', * tool_call_id: 'call_123' * }; * ``` * * @public */ interface ChatMessage { /** The role of the message author */ role: 'system' | 'user' | 'assistant' | 'tool'; /** Message content. Can be null for assistant messages that only contain tool calls. */ content: string | null; /** Tool calls requested by the assistant. Only present when role is 'assistant'. */ tool_calls?: ToolCall[]; /** ID of the tool call this message responds to. Required when role is 'tool'. */ tool_call_id?: string; } /** * Response from an LLM provider. * Follows OpenAI's Chat Completions API response format. * * @public */ interface ChatResponse { /** Array of response choices (typically contains one choice) */ choices: [ { /** The generated message */ message: { /** Always 'assistant' for responses */ role: 'assistant'; /** Text content of the response. Null if only tool calls are present. */ content: string | null; /** Tool calls the model wants to make */ tool_calls?: ToolCall[]; }; } ]; /** Token usage statistics (if provided by the model) */ usage?: { /** Number of tokens in the input prompt */ prompt_tokens: number; /** Number of tokens in the generated response */ completion_tokens: number; /** Total tokens used */ total_tokens: number; }; } /** * Complete response from a chat query including tool execution results. * * @public */ interface QueryResponse { /** The final text reply from the assistant */ reply: string; /** Tool calls that were made during the conversation */ toolCalls: ToolCall[]; /** Results from executing the tool calls */ toolResponses: ToolExecutionResult[]; } /** * Tool definition in OpenAI function calling format. * Describes a tool that the LLM can invoke. * * @example * ```typescript * const tool: Tool = { * type: 'function', * function: { * name: 'get_weather', * description: 'Get the current weather for a location', * parameters: { * type: 'object', * properties: { * location: { type: 'string', description: 'City name' }, * unit: { type: 'string', enum: ['celsius', 'fahrenheit'] } * }, * required: ['location'] * } * } * }; * ``` * * @public */ interface Tool { /** Always 'function' for function-calling tools */ type: 'function'; /** Function definition */ function: { /** Unique name of the function */ name: string; /** Description of what the function does (shown to the LLM) */ description: string; /** JSON Schema describing the function parameters (flexible to support various LLM providers) */ parameters: Record; }; } /** * A tool call made by the LLM. * Represents the model's request to invoke a specific tool. * * @example * ```typescript * const toolCall: ToolCall = { * id: 'call_abc123', * type: 'function', * function: { * name: 'get_weather', * arguments: '{"location": "San Francisco", "unit": "celsius"}' * } * }; * * // Parse the arguments * const args = JSON.parse(toolCall.function.arguments); * ``` * * @public */ interface ToolCall { /** Unique identifier for this tool call */ id: string; /** Always 'function' for function calls */ type: 'function'; /** Function invocation details */ function: { /** Name of the function to call */ name: string; /** JSON-encoded string of the function arguments */ arguments: string; }; } /** * Tool associated with a specific MCP server. * Extends the base Tool with server identification for routing. * * @public */ interface ServerTool extends Tool { /** ID of the MCP server that provides this tool */ serverId: string; } /** * Result of executing a tool call. * * @public */ interface ToolExecutionResult { /** ID of the original tool call */ id: string; /** Name of the tool that was executed */ name: string; /** Parsed arguments that were passed to the tool */ arguments: Record; /** String result returned by the tool */ result: string; /** ID of the MCP server that executed the tool */ serverId: string; } /** * Result of validating chat messages. * * @example * ```typescript * const result = validateMessages(messages); * if (!result.isValid) { * console.error('Validation failed:', result.error); * } * ``` * * @public */ interface MessageValidationResult { /** Whether the messages passed validation */ isValid: boolean; /** Error message describing the validation failure */ error?: string; } /** * MCP tool configuration for OpenAI Responses API. * Used to configure native MCP support in the Responses API. * * @public */ interface ResponsesApiMcpTool { /** Tool type identifier */ type: 'mcp'; /** URL of the MCP server */ server_url: string; /** Human-readable label for the server */ server_label: string; /** When to require user approval for tool calls */ require_approval: 'never' | 'always' | 'auto'; /** List of allowed tool names (if not set, all tools are allowed) */ allowed_tools?: string[]; /** HTTP headers to send with requests */ headers?: Record; } /** * MCP list tools output event from OpenAI Responses API. * * @public */ interface ResponsesApiMcpListTools { /** Event ID */ id: string; /** Event type identifier */ type: 'mcp_list_tools'; /** Label of the server that provided the tools */ server_label: string; /** List of available tools */ tools: Array<{ /** Tool name */ name: string; /** Tool description */ description: string; /** JSON Schema for tool input */ input_schema: Record; }>; } /** * MCP tool call output event from OpenAI Responses API. * * @public */ interface ResponsesApiMcpCall { /** Event ID */ id: string; /** Event type identifier */ type: 'mcp_call'; /** Name of the tool that was called */ name: string; /** JSON-encoded arguments passed to the tool */ arguments: string; /** Label of the server that handled the call */ server_label: string; /** Error message if the call failed */ error: string | null; /** Output from the tool call */ output: string; } /** * Message output event from OpenAI Responses API. * * @public */ interface ResponsesApiMessage { /** Event ID */ id: string; /** Event type identifier */ type: 'message'; /** Message role */ role: 'assistant'; /** Completion status */ status: 'completed' | 'failed'; /** Message content blocks */ content: Array<{ /** Content type */ type: 'output_text'; /** Text content */ text: string; /** Optional annotations */ annotations?: unknown[]; }>; } /** * Union type for all possible output events from OpenAI Responses API. * * @public */ type ResponsesApiOutputEvent = ResponsesApiMcpListTools | ResponsesApiMcpCall | ResponsesApiMessage; /** * Complete response from OpenAI Responses API. * * @public */ interface ResponsesApiResponse { /** Response ID */ id: string; /** Object type */ object: 'response'; /** Unix timestamp of creation */ created_at: number; /** Model used for generation */ model: string; /** Response status */ status: 'completed' | 'failed' | 'cancelled'; /** Output events from the response */ output: ResponsesApiOutputEvent[]; /** Token usage statistics */ usage?: { /** Input tokens used */ input_tokens: number; /** Output tokens generated */ output_tokens: number; /** Total tokens */ total_tokens: number; /** Detailed input token breakdown */ input_tokens_details?: { /** Tokens served from cache */ cached_tokens: number; }; /** Detailed output token breakdown */ output_tokens_details?: unknown; }; /** Error message if failed */ error?: string | null; /** System instructions */ instructions?: string | null; /** Configured tools */ tools?: ResponsesApiMcpTool[]; /** Whether parallel tool calls are enabled */ parallel_tool_calls?: boolean; /** ID of the previous response in a conversation */ previous_response_id?: string | null; /** Temperature setting used */ temperature?: number | null; /** Top-p setting used */ top_p?: number | null; /** Text format configuration */ text?: { format: { type: string; }; }; /** Truncation settings */ truncation?: unknown; } /** * A stored conversation record. * Used for API responses and internal representation. * * @public */ interface ConversationRecord { /** Unique identifier for the conversation */ id: string; /** User entity ref who owns this conversation */ userId: string; /** Array of chat messages in the conversation */ messages: ChatMessage[]; /** Optional array of tool names used in the conversation */ toolsUsed?: string[]; /** AI-generated or user-edited conversation title */ title?: string; /** Whether the conversation is starred/favorited */ isStarred: boolean; /** Timestamp when the conversation was created */ createdAt: Date; /** Timestamp when the conversation was last updated */ updatedAt: Date; } /** * Abstract base class for all LLM providers. * Extend this class to create custom LLM provider implementations. * * @public */ declare abstract class LLMProvider { protected apiKey?: string; protected baseUrl: string; protected model: string; protected type: string; protected logger?: LoggerService; protected maxTokens?: number; protected temperature?: number; constructor(config: ProviderConfig); abstract sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; abstract testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected abstract getHeaders(): Record; protected abstract formatRequest(messages: ChatMessage[], tools?: Tool[]): any; protected abstract parseResponse(response: any): ChatResponse; protected truncateForLogging(data: string, maxLength?: number): string; protected makeRequest(endpoint: string, body: any): Promise; } /** * Factory class for creating LLM provider instances. * Supports OpenAI, Azure OpenAI, Claude, Gemini, Ollama, LiteLLM, and OpenAI Responses API. * * @public */ declare class ProviderFactory { /** * Creates an LLM provider instance based on the configuration. * * @param config - The provider configuration * @param logger - Optional logger service for debug logging * @returns An LLM provider instance */ static createProvider(config: ProviderConfig, logger?: LoggerService): LLMProvider; } /** * Parses and returns the LLM provider configuration from Backstage config. * Reads from mcpChat.providers configuration section. * * @param config - The Backstage root config service * @returns The provider configuration * @public */ declare function getProviderConfig(config: RootConfigService): ProviderConfig; /** * Returns provider information for status display purposes. * * @param config - The Backstage root config service * @returns Provider info including type, model, and base URL * @public */ declare function getProviderInfo(config: RootConfigService): { deploymentName?: string | undefined; provider: string; model: string; baseURL: string; }; /** * OpenAI Chat Completions API provider. * * @public */ declare class OpenAIProvider extends LLMProvider { protected get providerName(): string; sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(messages: ChatMessage[], tools?: Tool[]): any; protected parseResponse(response: any): ChatResponse; } /** * Azure OpenAI Chat Completions API provider. * * @public */ declare class AzureOpenAIProvider extends OpenAIProvider { private readonly deploymentName; protected get providerName(): string; constructor(config: ProviderConfig); testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected formatRequest(messages: ChatMessage[], tools?: Tool[]): any; } /** * OpenAI Responses API provider with native MCP support. * Delegates MCP tool discovery and execution to the API itself. * * @public */ declare class OpenAIResponsesProvider extends LLMProvider { private mcpServerConfigs; private allowedToolsByServer; /** * Sets the MCP server configurations for native tool support. * These servers will be passed to the OpenAI Responses API. * * @param configs - Array of MCP server configurations * @param allowedToolsByServer - Map of server ID to allowed tool names */ setMcpServerConfigs(configs: MCPServerFullConfig[], allowedToolsByServer?: Map): void; sendMessage(messages: ChatMessage[], _tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(messages: ChatMessage[], _tools?: Tool[]): any; protected parseResponse(response: ResponsesApiResponse): ChatResponse; /** * Get the raw Responses API output for detailed tool execution information * This is used by MCPClientServiceImpl to construct toolResponses */ getLastResponseOutput(): ResponsesApiResponse['output'] | null; private lastResponseOutput; protected makeRequest(endpoint: string, body: any): Promise; } /** * Anthropic Claude API provider. * * @public */ declare class ClaudeProvider extends LLMProvider { sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(messages: ChatMessage[], tools?: Tool[]): any; protected parseResponse(response: any): ChatResponse; private convertToAnthropicFormat; private convertToAnthropicTools; } /** * Google Gemini API provider. * * @public */ declare class GeminiProvider extends LLMProvider { private genAI; private readonly baseModelConfig; constructor(config: ProviderConfig); sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(_messages: ChatMessage[], _tools?: Tool[]): any; protected parseResponse(result: GenerateContentResponse): ChatResponse; private convertToGeminiFormat; private convertToGeminiTools; private cleanJsonSchemaForGemini; } /** * Ollama local LLM provider. * * @public */ declare class OllamaProvider extends LLMProvider { private ollama; constructor(config: any); sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(messages: ChatMessage[], tools?: Tool[]): any; protected parseResponse(response: any): ChatResponse; } /** * LiteLLM Provider * * LiteLLM is a unified interface to 100+ LLM APIs including: * - OpenAI, Azure OpenAI * - Anthropic (Claude) * - Google (Gemini, VertexAI) * - AWS Bedrock * - Cohere, Replicate, Huggingface * - And many more... * * It uses the OpenAI-compatible format, making it easy to integrate. * * Configuration example in app-config.yaml: * ```yaml * mcpChat: * providers: * - id: litellm * token: ${LITELLM_API_KEY} # Optional, depends on your LiteLLM setup * baseUrl: 'http://localhost:4000' # Your LiteLLM proxy URL * model: gpt-4 # Any model supported by your LiteLLM instance * ``` */ /** * LiteLLM proxy provider. * Provides unified access to 100+ LLM APIs through LiteLLM. * * @public */ declare class LiteLLMProvider extends LLMProvider { sendMessage(messages: ChatMessage[], tools?: Tool[]): Promise; testConnection(): Promise<{ connected: boolean; models?: string[]; error?: string; }>; protected getHeaders(): Record; protected formatRequest(messages: ChatMessage[], tools?: Tool[]): any; protected parseResponse(response: any): ChatResponse; } /** * Service interface for MCP (Model Context Protocol) client operations. * Provides methods for interacting with LLM providers and MCP tool servers. * * Use this interface when you need to: * - Send queries to an LLM with optional tool support * - Manage MCP server connections * - Check provider and server health status * * @example * ```typescript * // Get the service from Backstage backend * const mcpService = await coreServices.service(mcpClientServiceRef); * * // Send a query * const response = await mcpService.processQuery( * [{ role: 'user', content: 'List files in /tmp' }], * ['filesystem__list_files'] * ); * console.log(response.reply); * ``` * * @public */ interface MCPClientService { /** * Initializes connections to all configured MCP servers. * This is typically called during plugin startup. * * @returns Promise resolving to array of MCP servers with their connection status */ initializeMCPServers(): Promise; /** * Processes a chat query through the LLM provider. * Automatically handles tool calls if the LLM requests them. * * @param messagesInput - Array of chat messages representing the conversation * @param enabledTools - Optional array of server IDs to enable. If undefined, all tools are enabled. * If empty array, no tools are enabled. * @returns Promise resolving to the query response with reply and tool execution details * * @example * ```typescript * // Enable all tools * const response = await service.processQuery(messages); * * // Enable specific servers only * const response = await service.processQuery(messages, ['kubernetes-server']); * * // Disable all tools * const response = await service.processQuery(messages, []); * ``` */ processQuery(messagesInput: ChatMessage[], enabledTools?: string[]): Promise; /** * Returns all tools available from connected MCP servers. * Each tool includes its server ID for routing purposes. * * @returns Array of server tools with their definitions */ getAvailableTools(): ServerTool[]; /** * Gets the current status of the configured LLM provider. * Useful for health checks and monitoring. * * @returns Promise resolving to provider status including connection health */ getProviderStatus(): Promise; /** * Gets the current status of all configured MCP servers. * Useful for health checks and monitoring. * * @returns Promise resolving to MCP server status including connection states */ getMCPServerStatus(): Promise; } /** * Options for creating an MCPClientServiceImpl instance. * * @public */ type Options = { logger: LoggerService; config: RootConfigService; }; /** * Implementation of the MCP Client Service. * Provides full MCP integration with LLM providers. * * @public */ declare class MCPClientServiceImpl implements MCPClientService { private readonly logger; private readonly config; private llmProvider; private readonly mcpClients; private tools; private connected; private mcpServers; private readonly systemPrompt; private serverConfigs; private allowedToolsByServer; private readonly toolCallTimeout; constructor(options: Options); private initializeLLMProvider; initializeMCPServers(): Promise; private mcpServerInit; /** * Filters discovered tools based on the server's disabledTools config. * Validates disabled tool names and logs warnings for invalid ones. * Returns the filtered ServerTool[] and, if any tools were disabled, * the list of allowed tool names (for use with the Responses API). */ private filterDiscoveredTools; processQuery(messagesInput: any[], enabledTools?: string[]): Promise; /** * Process query using OpenAI Responses API * The API handles tool discovery and execution internally */ private processQueryWithResponsesApi; getAvailableTools(): ServerTool[]; getProviderStatus(): Promise; getMCPServerStatus(): Promise; } /** * Options for creating a ChatConversationStore instance. * * @public */ interface ChatConversationStoreOptions { database: DatabaseService; logger: LoggerService; config: Config; } /** * Service for storing and retrieving chat conversations from the database. * Follows the Backstage pattern used by playlist-backend/DatabaseHandler. * * @public */ declare class ChatConversationStore { private readonly db; private readonly logger; private readonly config; /** * Creates a new ChatConversationStore instance. * Handles database migrations automatically. * * @param options - Configuration options * @returns A new ChatConversationStore instance */ static create(options: ChatConversationStoreOptions): Promise; private constructor(); /** * Save a conversation to the database. * Creates a new conversation or updates an existing one. * * @param userId - User entity ref who owns this conversation * @param messages - Array of chat messages * @param toolsUsed - Optional array of tool names used * @param conversationId - Optional existing conversation ID to update * @returns The saved conversation record */ saveConversation(userId: string, messages: ChatMessage[], toolsUsed?: string[], conversationId?: string): Promise; /** * Retrieve conversations for a specific user, ordered by last update (newest first). * Limit is controlled by config or parameter. * * @param userId - User entity ref * @param limit - Optional limit override (default from config) * @returns Array of conversation records */ getConversations(userId: string, limit?: number): Promise; /** * Retrieve a specific conversation by ID (with user verification). * * @param userId - User entity ref (for authorization) * @param id - Conversation ID * @returns The conversation record or null if not found */ getConversationById(userId: string, id: string): Promise; /** * Convert a database row to a ConversationRecord. * Includes safe JSON parsing with error handling. */ private rowToRecord; /** * Delete all conversations for a user. * Useful for account cleanup or testing. * * @param userId - User entity ref */ deleteUserConversations(userId: string): Promise; /** * Delete a specific conversation. * * @param userId - User entity ref (for authorization) * @param id - Conversation ID * @returns true if deleted, false if not found */ deleteConversation(userId: string, id: string): Promise; /** * Toggle the starred status of a conversation. * * @param userId - User entity ref (for authorization) * @param id - Conversation ID * @returns The new starred status, or false if not found */ toggleStarred(userId: string, id: string): Promise; /** * Update the title of a conversation. * * @param userId - User entity ref (for authorization) * @param id - Conversation ID * @param title - New title */ updateTitle(userId: string, id: string, title: string): Promise; } /** * Options for creating a SummarizationService instance. * * @public */ interface SummarizationServiceOptions { mcpClientService: MCPClientService; logger: LoggerService; config: Config; } /** * Service for generating AI-powered conversation titles. * Uses the configured LLM provider to summarize conversations into concise titles. * Falls back to first user message if summarization fails or times out. * * @public */ declare class SummarizationService { private readonly mcpClientService; private readonly logger; private readonly config; constructor(options: SummarizationServiceOptions); /** * Generate a title for a conversation using the LLM. * Falls back to first user message on failure or timeout. * * @param messages - The conversation messages to summarize * @returns A concise title for the conversation */ summarizeConversation(messages: ChatMessage[]): Promise; /** * Sanitize a title to remove potential XSS vectors and formatting issues. */ private sanitizeTitle; /** * Generate a fallback title from the first user message. * Used when LLM summarization fails or is disabled. */ private getFallbackTitle; } /** * Default timeout in milliseconds for MCP tool call requests. * @public */ declare const DEFAULT_MCP_TOOL_CALL_TIMEOUT_MS = 60000; /** * Loads MCP server configurations from Backstage config. * Reads from the `mcpChat.mcpServers` configuration section. * * @param config - The Backstage root config service * @returns Array of server configurations including secrets * @public */ declare function loadServerConfigs(config: RootConfigService): MCPServerFullConfig[]; /** * Helper function to find npx executable path. * Searches common installation locations and validates the executable works. * * @returns Promise resolving to the path to the npx executable * @throws Error if npx cannot be found or is not functional * @public */ declare function findNpxPath(): Promise; /** * Executes a tool call using the MCP client. * Finds the appropriate server based on the tool's serverId and executes the tool call. * * @param toolCall - The tool call from the LLM containing function name and arguments * @param tools - List of available tools with their server IDs * @param mcpClients - Map of server IDs to MCP client instances * @param toolCallTimeout - Timeout for the tool call to complete (default: 60000, unit: ms) * @returns Promise resolving to the tool execution result * @public */ declare function executeToolCall(toolCall: ToolCall, tools: ServerTool[], mcpClients: Map, toolCallTimeout?: number): Promise; /** * Validates the MCP server configuration. * Ensures that headers and env are objects with string key-value pairs. * Throws an error if any configuration is invalid. * * @param config - The root configuration service * @public */ declare const validateConfig: (config: RootConfigService) => void; /** * Validates the structure and content of chat messages. * Checks for required fields, valid roles, and proper message format. * * @param messages - Array of messages to validate * @returns Validation result with isValid flag and optional error message * * @example * ```typescript * const result = validateMessages([ * { role: 'user', content: 'Hello' } * ]); * if (!result.isValid) { * throw new Error(result.error); * } * ``` * * @public */ declare const validateMessages: (messages: unknown) => MessageValidationResult; /** * Options for creating the MCP Chat router. * * @public */ interface RouterOptions { logger: LoggerService; mcpClientService: MCPClientService; conversationStore: ChatConversationStore; httpAuth: HttpAuthService; summarizationService: SummarizationService; } /** * Creates an Express router with MCP chat endpoints. * * Routes are organized into domain-specific modules: * - Status routes: /provider/status, /mcp/status, /tools * - Chat routes: /chat * - Conversation routes: /conversations/* * * @param options - Router options including logger, services, and auth * @returns Express router * @public */ declare function createRouter(options: RouterOptions): Promise; export { AzureOpenAIProvider, ChatConversationStore, ClaudeProvider, DEFAULT_MCP_TOOL_CALL_TIMEOUT_MS, GeminiProvider, LLMProvider, LiteLLMProvider, MCPClientServiceImpl, MCPServerType, OllamaProvider, OpenAIProvider, OpenAIResponsesProvider, ProviderFactory, SummarizationService, VALID_ROLES, createRouter, mcpChatPlugin as default, executeToolCall, findNpxPath, getProviderConfig, getProviderInfo, loadServerConfigs, validateConfig, validateMessages }; export type { ChatConversationStoreOptions, ChatMessage, ChatResponse, ConversationRecord, LLMProviderType, MCPClientService, Options as MCPClientServiceOptions, MCPServer, MCPServerConfig, MCPServerFullConfig, MCPServerSecrets, MCPServerStatusData, MessageValidationResult, ProviderConfig, ProviderConnectionStatus, ProviderInfo, ProviderStatusData, QueryResponse, ResponsesApiMcpCall, ResponsesApiMcpListTools, ResponsesApiMcpTool, ResponsesApiMessage, ResponsesApiOutputEvent, ResponsesApiResponse, RouterOptions, ServerTool, SummarizationServiceOptions, Tool, ToolCall, ToolExecutionResult };