import CloudBase from '@cloudbase/manager-node';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { RegisteredTool } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { ToolAnnotations as ToolAnnotations_2 } from '@modelcontextprotocol/sdk/types.js';

export declare const ALL_SUPPORTED_RUNTIMES: ("Nodejs20.19" | "Nodejs18.15" | "Nodejs16.13" | "Nodejs14.18" | "Nodejs12.16" | "Nodejs10.15" | "Nodejs8.9" | "Python3.10" | "Python3.9" | "Python3.7" | "Python3.6" | "Python2.7" | "Php8.0" | "Php7.4" | "Php7.2" | "Java8" | "Java11" | "Golang1")[];

export declare type AuthFlowMode = "web" | "device";

export declare interface AuthOptions {
    authMode?: AuthFlowMode;
    clientId?: string;
    oauthEndpoint?: string;
    oauthCustom?: boolean;
}

/**
 * 自定义 API 请求函数，由外部注入，替代 TC3 签名发请求。
 * 入参对齐 CAPI 模式：service + action + version + region + payload。
 * 返回腾讯云 API 响应中 Response 字段的内容（已解包）。
 */
export declare type CloudApiRequestFn = (params: {
    service: string;
    action: string;
    version: string;
    region: string;
    payload: Record<string, any>;
}) => Promise<any>;

declare type CloudBaseConfigBase = NonNullable<ConstructorParameters<typeof CloudBase>[0]>;

export declare type CloudBaseOptions = CloudBaseConfigBase & {
    requestFn?: CloudApiRequestFn;
};

/**
 * registerTool config with CloudBase `annotations.category` retained after
 * MCP SDK >=1.26 closed ToolAnnotations to strip unknown keys at the type level.
 */
export declare type CloudBaseRegisterToolConfig = {
    title?: string;
    description?: string;
    inputSchema?: any;
    outputSchema?: any;
    annotations?: ToolAnnotations;
    _meta?: Record<string, unknown>;
};

/**
 * Create a manager with the provided CloudBase options, without using cache
 * @param cloudBaseOptions Provided CloudBase options
 * @returns CloudBase manager instance
 */
export declare function createCloudBaseManagerWithOptions(cloudBaseOptions: CloudBaseOptions): CloudBase;

/**
 * Create and configure a CloudBase MCP Server instance
 * @param options Server configuration options
 * @returns Configured McpServer instance
 *
 * @example
 * import { createCloudBaseMcpServer } from "@cloudbase/mcp-server";
 * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
 *
 * const server = createCloudBaseMcpServer({ cloudBaseOptions: {
 *  envId,    // 环境ID
 *  secretId,  // 腾讯云密钥ID
 *  secretKey, // 腾讯云密钥
 *  region, // 地域，默认是 ap-shanghai
 *  token // 临时密钥，有有效期限制，生成密钥时可控制
 * } });
 *
 * const transport = new StdioServerTransport();
 * await server.connect(transport);
 */
export declare function createCloudBaseMcpServer(options?: {
    name?: string;
    version?: string;
    enableTelemetry?: boolean;
    cloudBaseOptions?: CloudBaseOptions;
    authOptions?: AuthOptions;
    cloudMode?: boolean;
    ide?: string;
    logger?: Logger;
    pluginsEnabled?: string[];
    pluginsDisabled?: string[];
    pluginOptions?: PluginOptions;
}): Promise<ExtendedMcpServer>;

export declare interface DataModel {
    id?: string;
    name: string;
    title: string;
    schema: DataModelSchema;
    envId?: string;
    status?: 'draft' | 'published';
    createdAt?: string;
    updatedAt?: string;
}

export declare interface DataModelField {
    name: string;
    type: 'string' | 'number' | 'boolean' | 'date' | 'array' | 'object' | 'objectId' | 'file' | 'image';
    required?: boolean;
    default?: any;
    description?: string;
    validation?: {
        min?: number;
        max?: number;
        pattern?: string;
        enum?: any[];
    };
}

export declare interface DataModelSchema {
    type: 'object';
    properties: Record<string, {
        type: string;
        description?: string;
        required?: boolean;
        default?: any;
        validation?: any;
    }>;
    required?: string[];
}

export declare const DEFAULT_NODEJS_RUNTIME = "Nodejs18.15";

export declare const DEFAULT_RUNTIME = "Nodejs18.15";

export declare interface DeleteFileParams {
    cloudPath: string;
}

export declare interface DeviceFlowAuthInfo {
    user_code: string;
    verification_uri?: string;
    verification_uri_complete?: string;
    device_code: string;
    expires_in: number;
}

/**
 * Enable cloud mode by setting environment variable
 */
export declare function enableCloudMode(): void;

export declare interface EnsureLoginOptions extends AuthOptions {
    fromCloudBaseLoginPage?: boolean;
    ignoreEnvVars?: boolean;
    region?: string;
    serverAuthOptions?: AuthOptions;
    onDeviceCode?: (info: DeviceFlowAuthInfo) => void;
}

declare class EnvironmentManager {
    private cachedEnvId;
    private envIdPromise;
    reset(): void;
    getEnvId(): Promise<string>;
    private _fetchEnvId;
    private _setCachedEnvId;
    setEnvId(envId: string): Promise<void>;
    getCachedEnvId(): string | null;
}

export declare const envManager: EnvironmentManager;

export declare const error: (message: string, data?: object | Error) => void;

export declare interface ExtendedMcpServer extends McpServer {
    cloudBaseOptions?: CloudBaseOptions;
    authOptions?: AuthOptions;
    ide?: string;
    logger?: Logger;
    enabledPlugins?: string[];
    pluginOptions?: PluginOptions;
    /** Registered tools for external hosts (e.g. WeChat IDE) to re-register. */
    toolDefs: Array<{
        name: string;
        description: string;
        inputSchema: any;
        handler: (input: any) => Promise<any>;
    }>;
    setLogger(logger: Logger): void;
    /**
     * Same as MCP SDK registerTool, but annotations may include CloudBase `category`.
     * Handler typing stays intentionally loose to match existing tool call sites.
     */
    registerTool(name: string, config: CloudBaseRegisterToolConfig, cb: (...args: any[]) => any): RegisteredTool;
}

export declare function formatRuntimeList(): string;

/**
 * manageFunctions 工具中部分 action 的 override 钩子
 * 参数使用 CloudBase 领域语言，与 MCP 内部 DTO 解耦
 * 实现方（如微信 IDE）负责在内部做参数适配
 *
 * - createFunction / updateFunctionCode：有默认实现，override 后可走外部专有接口
 * - incrementalDeployFunction：无默认实现，必须通过 pluginOptions 注入
 */
export declare interface FunctionDeployOverrides {
    createFunction?: (params: {
        functionName: string;
        functionRootPath: string;
        runtime?: string;
        force?: boolean;
        installDependency?: boolean;
    }) => Promise<any>;
    updateFunctionCode?: (params: {
        functionName: string;
        functionRootPath: string;
        force?: boolean;
        installDependency?: boolean;
    }) => Promise<any>;
    incrementalDeployFunction?: (params: {
        functionName: string;
        functionRootPath: string;
        incrementalFile: string;
    }) => Promise<any>;
}

/**
 * 每次都实时获取最新的 token/secretId/secretKey
 */
export declare function getCloudBaseManager(options?: GetManagerOptions): Promise<CloudBase>;

/**
 * Get cloud mode status for logging/debugging
 */
export declare function getCloudModeStatus(): {
    enabled: boolean;
    source: string | null;
};

/**
 * Get the default configured CloudBase MCP Server
 */
export declare function getDefaultServer(): Promise<ExtendedMcpServer>;

export declare function getEnvId(cloudBaseOptions?: CloudBaseOptions): Promise<string>;

export declare interface GetFileInfoParams {
    cloudPath: string;
}

/**
 * Get interactive server instance (CommonJS compatible)
 */
export declare function getInteractiveServerAsync(): Promise<InteractiveServer>;

export declare function getLoginState(options?: EnsureLoginOptions): Promise<LoginState | null>;

declare interface GetManagerOptions {
    requireEnvId?: boolean;
    cloudBaseOptions?: CloudBaseOptions;
    mcpServer?: any;
    authStrategy?: 'fail_fast' | 'ensure';
}

declare interface IdeFileDescriptor {
    path: string;
    isMcpConfig?: boolean;
}

export declare const info: (message: string, data?: object | Error) => void;

export declare interface InteractiveResult {
    type: "envId" | "clarification" | "confirmation";
    data: any;
    cancelled?: boolean;
    switch?: boolean;
    timeout?: boolean;
    timeoutDuration?: number;
}

declare class InteractiveServer {
    private app;
    private server;
    private wss;
    private port;
    private isRunning;
    private currentResolver;
    private sessionData;
    private _mcpServer;
    get mcpServer(): any;
    set mcpServer(server: any);
    private readonly DEFAULT_PORT;
    private readonly FALLBACK_PORTS;
    /** Idle timeout for HTTP/WS connections (e.g. long login). Avoids "connection disconnected" after ~1 min. */
    private static readonly SERVER_IDLE_MS;
    /** WebSocket ping interval to keep connection alive past proxies/firewalls. */
    private static readonly WS_PING_INTERVAL_MS;
    constructor(mcpServer?: any);
    private cleanup;
    /** Apply timeouts so long-lived login does not cause "connection disconnected". */
    private applyServerTimeouts;
    private setupExpress;
    private setupWebSocket;
    start(): Promise<number>;
    stop(): Promise<void>;
    collectEnvId(availableEnvs: any[], accountInfo?: {
        uin?: string;
    }, errorContext?: any, // EnvSetupContext
    manager?: any, // CloudBase manager instance for refreshing env list
    mcpServer?: any): Promise<InteractiveResult>;
    clarifyRequest(message: string, options?: string[]): Promise<InteractiveResult>;
    private escapeHtml;
    private getEnvSetupHTML;
    private getEnvSetupHTML_OLD;
    private getClarificationHTML;
    private getConfirmationHTML;
    get running(): boolean;
    get currentPort(): number;
}

/**
 * Check if MCP is running in cloud mode
 * Cloud mode is enabled by:
 * 1. Command line argument --cloud-mode
 * 2. Environment variable CLOUDBASE_MCP_CLOUD_MODE=true
 * 3. Environment variable MCP_CLOUD_MODE=true
 *
 * Intentionally does not import logger: logger.ts calls isCloudMode() during
 * module init, so importing logger here creates a circular dependency that
 * crashes `node dist/cli.cjs --cloud-mode` with `debug is not a function`.
 */
export declare function isCloudMode(): boolean;

export declare interface ListFilesParams {
    prefix: string;
    marker?: string;
}

declare type Logger = (data: {
    type: string;
    requestId?: string;
    result?: any;
    toolName?: string;
    args?: any;
    message?: string;
    duration?: number;
    [key: string]: any;
}) => void;

declare interface LoginState {
    secretId: string;
    secretKey: string;
    token?: string;
    envId?: string;
}

export declare function logout(): Promise<void>;

/** MCP initialize clientInfo fields available after handshake via Server.getClientVersion(). */
declare type McpClientInfo = {
    name?: string;
    version?: string;
    title?: string;
};

export { McpServer }

/** 各插件的可选配置 */
export declare interface PluginOptions {
    functions?: FunctionDeployOverrides;
    storage?: StorageOverrides;
}

export declare const RAW_IDE_FILE_MAPPINGS: Record<string, IdeFileDescriptor[]>;

export declare const RECOMMENDED_RUNTIMES: {
    readonly nodejs: "Nodejs18.15";
    readonly python: "Python3.9";
    readonly php: "Php7.4";
    readonly java: "Java11";
    readonly golang: "Golang1";
};

export declare const reportToolCall: (params: {
    toolName: string;
    success: boolean;
    requestId?: string;
    duration?: number;
    error?: string;
    inputParams?: any;
    cloudBaseOptions?: CloudBaseOptions;
    ide?: string;
    mcpClientInfo?: McpClientInfo;
}) => Promise<void>;

export declare const reportToolkitLifecycle: (params: {
    event: "start" | "exit";
    duration?: number;
    exitCode?: number;
    error?: string;
    cloudBaseOptions?: CloudBaseOptions;
    ide?: string;
    mcpClientInfo?: McpClientInfo;
}) => Promise<void>;

export declare function resetCloudBaseManagerCache(): void;

/**
 * Check if a tool should be registered in cloud mode
 * @param toolName - The name of the tool
 * @returns true if the tool should be registered in current mode
 */
export declare function shouldRegisterTool(toolName: string): boolean;

/**
 * Simplify environment list data by keeping only essential fields for AI assistant
 * This reduces token consumption when returning environment lists via MCP tools
 * @param envList - Full environment list from API
 * @returns Simplified environment list with only essential fields
 */
export declare function simplifyEnvList(envList: any[]): any[];

export { StdioServerTransport }

/**
 * 存储工具中需要 COS SDK 操作的 override 钩子
 * 实现方（如微信 IDE）负责在内部通过 /route/getcosauth 获取临时签名并操作 COS
 *
 * - listFiles / getFileInfo / downloadFile：queryStorage 只读操作
 * - uploadFile / deleteFiles / deleteDirectory：manageStorage 写操作
 * - getFileUrl：获取文件临时下载链接（可选，未提供时使用 CAPI 默认实现）
 */
declare interface StorageOverrides {
    /** 列出目录下的文件，替代 storageService.listDirectoryFiles() */
    listFiles?: (params: {
        cloudPath: string;
    }) => Promise<Array<Record<string, any>>>;
    /** 获取文件元信息，替代 storageService.getFileInfo() */
    getFileInfo?: (params: {
        cloudPath: string;
    }) => Promise<Record<string, any>>;
    /** 下载文件到本地，替代 storageService.downloadFile() */
    downloadFile?: (params: {
        cloudPath: string;
        localPath: string;
    }) => Promise<void>;
    /** 下载目录到本地，替代 storageService.downloadDirectory() */
    downloadDirectory?: (params: {
        cloudPath: string;
        localPath: string;
    }) => Promise<void>;
    /** 上传单个文件，替代 storageService.uploadFile() */
    uploadFile?: (params: {
        localPath: string;
        cloudPath: string;
    }) => Promise<void>;
    /** 上传目录，替代 storageService.uploadDirectory() */
    uploadDirectory?: (params: {
        localPath: string;
        cloudPath: string;
    }) => Promise<void>;
    /**
     * 获取文件临时下载链接，替代 storageService.getTemporaryUrl()
     * 可通过 COS getObjectUrl 实现；未提供时走 manager-node 默认路径
     */
    getFileUrl?: (params: {
        cloudPath: string;
        maxAge?: number;
    }) => Promise<{
        url: string;
        fileId?: string;
    }>;
    /** 删除文件（支持批量），替代 storageService.deleteFile() */
    deleteFiles?: (params: {
        cloudPaths: string[];
    }) => Promise<void>;
    /** 删除目录，替代 storageService.deleteDirectory() */
    deleteDirectory?: (params: {
        cloudPath: string;
    }) => Promise<void>;
}

export declare const SUPPORTED_NODEJS_RUNTIMES: readonly ["Nodejs20.19", "Nodejs18.15", "Nodejs16.13", "Nodejs14.18", "Nodejs12.16", "Nodejs10.15", "Nodejs8.9"];

export declare const SUPPORTED_RUNTIMES: {
    readonly nodejs: readonly ["Nodejs20.19", "Nodejs18.15", "Nodejs16.13", "Nodejs14.18", "Nodejs12.16", "Nodejs10.15", "Nodejs8.9"];
    readonly python: readonly ["Python3.10", "Python3.9", "Python3.7", "Python3.6", "Python2.7"];
    readonly php: readonly ["Php8.0", "Php7.4", "Php7.2"];
    readonly java: readonly ["Java8", "Java11"];
    readonly golang: readonly ["Golang1"];
};

/**
 * 数据上报类
 * 用于收集 MCP 工具使用情况和错误信息，帮助改进产品
 *
 * 隐私保护：
 * - 可通过环境变量 CLOUDBASE_MCP_TELEMETRY_DISABLED=true 完全关闭
 * - 不收集敏感信息（代码内容、具体文件路径等）
 * - 使用设备指纹而非真实用户信息
 * - 所有数据仅用于产品改进，不用于其他用途
 */
declare class TelemetryReporter {
    private deviceId;
    private userAgent;
    private additionalParams;
    private enabled;
    constructor();
    /**
     * 获取用户运行环境信息
     * 包含操作系统、Node版本和MCP版本等信息
     */
    getUserAgent(): {
        userAgent: string;
        deviceId: string;
        osType: string;
        osRelease: string;
        nodeVersion: string;
        arch: string;
        mcpVersion: string;
    };
    /**
     * 获取设备唯一标识
     * 基于主机名、CPU信息和MAC地址生成匿名设备指纹
     */
    private getDeviceId;
    /**
     * 发送HTTP请求
     */
    private postFetch;
    /**
     * 上报事件
     * @param eventCode 事件代码
     * @param eventData 事件数据
     */
    report(eventCode: string, eventData?: {
        [key: string]: any;
    }): Promise<void>;
    /**
     * 设置公共参数
     */
    addAdditionalParams(params: {
        [key: string]: any;
    }): void;
    /**
     * 检查是否启用
     */
    isEnabled(): boolean;
}

export declare const telemetryReporter: TelemetryReporter;

export { Tool }

/**
 * CloudBase extends MCP ToolAnnotations with a stable `category` hint used by
 * IDE UIs for grouping. SDK >=1.26 types annotations as a closed/strip object,
 * so we keep category via an intersection while still passing it through at
 * runtime (listTools returns registered annotations without schema stripping).
 */
export declare type ToolAnnotations = ToolAnnotations_2 & {
    category?: string;
};

export declare interface ToolResponse {
    success: boolean;
    [key: string]: any;
}

export declare interface UploadFileParams {
    cloudPath: string;
    fileContent: string;
}

export declare function validateTimerCron(config: string): string;

export declare const warn: (message: string, data?: object | Error) => void;

export { }
