
import { __decorate, __param } from '../../../../../../../external/tslib/tslib.es6.js';
import { equals } from '../../../../base/common/arrays.js';
import { assertNever } from '../../../../base/common/assert.js';
import { encodeHex, VSBuffer, decodeHex } from '../../../../base/common/buffer.js';
import { Codicon } from '../../../../base/common/codicons.js';
import { Disposable } from '../../../../base/common/lifecycle.js';
import { equals as equals$1 } from '../../../../base/common/objects.js';
import { URI } from '../../../../base/common/uri.js';
import { localize } from '../../../../nls.js';
import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js';
import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js';
import { registerIcon } from '../../../../platform/theme/common/iconRegistry.js';
import { IMcpWorkbenchService } from './mcpTypes.service.js';
import { MCP } from './modelContextProtocol.js';

const extensionMcpCollectionPrefix = 'ext.';
function extensionPrefixedIdentifier(identifier, id) {
    return ExtensionIdentifier.toKey(identifier) + '/' + id;
}
var McpCollectionSortOrder;
(function (McpCollectionSortOrder) {
    McpCollectionSortOrder[McpCollectionSortOrder["WorkspaceFolder"] = 0] = "WorkspaceFolder";
    McpCollectionSortOrder[McpCollectionSortOrder["Workspace"] = 100] = "Workspace";
    McpCollectionSortOrder[McpCollectionSortOrder["User"] = 200] = "User";
    McpCollectionSortOrder[McpCollectionSortOrder["Extension"] = 300] = "Extension";
    McpCollectionSortOrder[McpCollectionSortOrder["Filesystem"] = 400] = "Filesystem";
    McpCollectionSortOrder[McpCollectionSortOrder["RemoteBoost"] = -50] = "RemoteBoost";
})(McpCollectionSortOrder || (McpCollectionSortOrder = {}));
var McpCollectionDefinition;
(function (McpCollectionDefinition) {
    function equals(a, b) {
        return a.id === b.id
            && a.remoteAuthority === b.remoteAuthority
            && a.label === b.label
            && a.isTrustedByDefault === b.isTrustedByDefault;
    }
    McpCollectionDefinition.equals = equals;
})(McpCollectionDefinition || (McpCollectionDefinition = {}));
var McpServerDefinition;
(function (McpServerDefinition) {
    function toSerialized(def) {
        return def;
    }
    McpServerDefinition.toSerialized = toSerialized;
    function fromSerialized(def) {
        return {
            id: def.id,
            label: def.label,
            cacheNonce: def.cacheNonce,
            launch: McpServerLaunch.fromSerialized(def.launch),
            variableReplacement: def.variableReplacement ? McpServerDefinitionVariableReplacement.fromSerialized(def.variableReplacement) : undefined,
        };
    }
    McpServerDefinition.fromSerialized = fromSerialized;
    function equals$2(a, b) {
        return a.id === b.id
            && a.label === b.label
            && equals(a.roots, b.roots, (a, b) => ( a.toString()) === ( b.toString()))
            && equals$1(a.launch, b.launch)
            && equals$1(a.presentation, b.presentation)
            && equals$1(a.variableReplacement, b.variableReplacement)
            && equals$1(a.devMode, b.devMode);
    }
    McpServerDefinition.equals = equals$2;
})(McpServerDefinition || (McpServerDefinition = {}));
var McpServerDefinitionVariableReplacement;
(function (McpServerDefinitionVariableReplacement) {
    function toSerialized(def) {
        return def;
    }
    McpServerDefinitionVariableReplacement.toSerialized = toSerialized;
    function fromSerialized(def) {
        return {
            section: def.section,
            folder: def.folder ? { ...def.folder, uri: URI.revive(def.folder.uri) } : undefined,
            target: def.target,
        };
    }
    McpServerDefinitionVariableReplacement.fromSerialized = fromSerialized;
})(McpServerDefinitionVariableReplacement || (McpServerDefinitionVariableReplacement = {}));
var LazyCollectionState;
(function (LazyCollectionState) {
    LazyCollectionState[LazyCollectionState["HasUnknown"] = 0] = "HasUnknown";
    LazyCollectionState[LazyCollectionState["LoadingUnknown"] = 1] = "LoadingUnknown";
    LazyCollectionState[LazyCollectionState["AllKnown"] = 2] = "AllKnown";
})(LazyCollectionState || (LazyCollectionState = {}));
const isMcpResourceTemplate = (obj) => {
    return obj.template !== undefined;
};
var McpServerCacheState;
(function (McpServerCacheState) {
    McpServerCacheState[McpServerCacheState["Unknown"] = 0] = "Unknown";
    McpServerCacheState[McpServerCacheState["Cached"] = 1] = "Cached";
    McpServerCacheState[McpServerCacheState["Outdated"] = 2] = "Outdated";
    McpServerCacheState[McpServerCacheState["RefreshingFromUnknown"] = 3] = "RefreshingFromUnknown";
    McpServerCacheState[McpServerCacheState["RefreshingFromCached"] = 4] = "RefreshingFromCached";
    McpServerCacheState[McpServerCacheState["Live"] = 5] = "Live";
})(McpServerCacheState || (McpServerCacheState = {}));
const mcpPromptReplaceSpecialChars = (s) => s.replace(/[^a-z0-9_.-]/gi, '_');
const mcpPromptPrefix = (definition) => `/mcp.` + mcpPromptReplaceSpecialChars(definition.label);
var McpServerTransportType;
(function (McpServerTransportType) {
    McpServerTransportType[McpServerTransportType["Stdio"] = 1] = "Stdio";
    McpServerTransportType[McpServerTransportType["HTTP"] = 2] = "HTTP";
})(McpServerTransportType || (McpServerTransportType = {}));
var McpServerLaunch;
(function (McpServerLaunch) {
    function toSerialized(launch) {
        return launch;
    }
    McpServerLaunch.toSerialized = toSerialized;
    function fromSerialized(launch) {
        switch (launch.type) {
            case McpServerTransportType.HTTP:
                return { type: launch.type, uri: URI.revive(launch.uri), headers: launch.headers };
            case McpServerTransportType.Stdio:
                return {
                    type: launch.type,
                    cwd: launch.cwd,
                    command: launch.command,
                    args: launch.args,
                    env: launch.env,
                    envFile: launch.envFile,
                };
        }
    }
    McpServerLaunch.fromSerialized = fromSerialized;
})(McpServerLaunch || (McpServerLaunch = {}));
var McpConnectionState;
(function (McpConnectionState) {
    let Kind;
    (function (Kind) {
        Kind[Kind["Stopped"] = 0] = "Stopped";
        Kind[Kind["Starting"] = 1] = "Starting";
        Kind[Kind["Running"] = 2] = "Running";
        Kind[Kind["Error"] = 3] = "Error";
    })(Kind = McpConnectionState.Kind || (McpConnectionState.Kind = {}));
    McpConnectionState.toString = (s) => {
        switch (s.state) {
            case Kind.Stopped:
                return localize(7986, 'Stopped');
            case Kind.Starting:
                return localize(7987, 'Starting');
            case Kind.Running:
                return localize(7988, 'Running');
            case Kind.Error:
                return localize(7989, 'Error {0}', s.message);
            default:
                assertNever();
        }
    };
    McpConnectionState.toKindString = (s) => {
        switch (s) {
            case Kind.Stopped:
                return 'stopped';
            case Kind.Starting:
                return 'starting';
            case Kind.Running:
                return 'running';
            case Kind.Error:
                return 'error';
            default:
                assertNever();
        }
    };
    McpConnectionState.canBeStarted = (s) => s === Kind.Error || s === Kind.Stopped;
    McpConnectionState.isRunning = (s) => !McpConnectionState.canBeStarted(s.state);
})(McpConnectionState || (McpConnectionState = {}));
class MpcResponseError extends Error {
    constructor(message, code, data) {
        super(`MPC ${code}: ${message}`);
        this.code = code;
        this.data = data;
    }
}
class McpConnectionFailedError extends Error {
}
let McpServerContainers = class McpServerContainers extends Disposable {
    constructor(containers, mcpWorkbenchService) {
        super();
        this.containers = containers;
        this._register(mcpWorkbenchService.onChange(this.update, this));
    }
    set mcpServer(extension) {
        this.containers.forEach(c => c.mcpServer = extension);
    }
    update(server) {
        for (const container of this.containers) {
            if (server && container.mcpServer) {
                if (server.name === container.mcpServer.name) {
                    container.mcpServer = server;
                }
            }
            else {
                container.update();
            }
        }
    }
};
McpServerContainers = ( __decorate([
    ( __param(1, IMcpWorkbenchService))
], McpServerContainers));
const McpServersGalleryEnabledContext = ( new RawContextKey('mcpServersGalleryEnabled', false));
const HasInstalledMcpServersContext = ( new RawContextKey('hasInstalledMcpServers', false));
const InstalledMcpServersViewId = 'workbench.views.mcp.installed';
const mcpServerIcon = registerIcon('mcp-server', Codicon.mcp, ( localize(7990, 'Icon used for the MCP server.')));
var McpResourceURI;
(function (McpResourceURI) {
    McpResourceURI.scheme = 'mcp-resource';
    function fromServer(def, resourceURI) {
        if (typeof resourceURI === 'string') {
            resourceURI = ( URI.parse(resourceURI));
        }
        return resourceURI.with({
            scheme: McpResourceURI.scheme,
            authority: encodeHex(VSBuffer.fromString(def.id)),
            path: ['', resourceURI.scheme, resourceURI.authority].join('/') + resourceURI.path,
        });
    }
    McpResourceURI.fromServer = fromServer;
    function toServer(uri) {
        if (typeof uri === 'string') {
            uri = ( URI.parse(uri));
        }
        if (uri.scheme !== McpResourceURI.scheme) {
            throw ( new Error(`Invalid MCP resource URI: ${( uri.toString())}`));
        }
        const parts = uri.path.split('/');
        if (parts.length < 3) {
            throw ( new Error(`Invalid MCP resource URI: ${( uri.toString())}`));
        }
        const [, serverScheme, authority, ...path] = parts;
        return {
            definitionId: ( decodeHex(uri.authority).toString()),
            resourceURI: uri.with({
                scheme: serverScheme,
                authority,
                path: '/' + path.join('/'),
            }),
        };
    }
    McpResourceURI.toServer = toServer;
})(McpResourceURI || (McpResourceURI = {}));
var McpCapability;
(function (McpCapability) {
    McpCapability[McpCapability["Logging"] = 1] = "Logging";
    McpCapability[McpCapability["Completions"] = 2] = "Completions";
    McpCapability[McpCapability["Prompts"] = 4] = "Prompts";
    McpCapability[McpCapability["PromptsListChanged"] = 8] = "PromptsListChanged";
    McpCapability[McpCapability["Resources"] = 16] = "Resources";
    McpCapability[McpCapability["ResourcesSubscribe"] = 32] = "ResourcesSubscribe";
    McpCapability[McpCapability["ResourcesListChanged"] = 64] = "ResourcesListChanged";
    McpCapability[McpCapability["Tools"] = 128] = "Tools";
    McpCapability[McpCapability["ToolsListChanged"] = 256] = "ToolsListChanged";
})(McpCapability || (McpCapability = {}));
class McpError extends Error {
    static methodNotFound(method) {
        return ( new McpError(MCP.METHOD_NOT_FOUND, `Method not found: ${method}`));
    }
    static notAllowed() {
        return ( new McpError(-32e3, 'The user has denied permission to call this method.'));
    }
    static unknown(e) {
        const mcpError = ( new McpError(MCP.INTERNAL_ERROR, `Unknown error: ${e.stack}`));
        mcpError.cause = e;
        return mcpError;
    }
    constructor(code, message, data) {
        super(message);
        this.code = code;
        this.data = data;
    }
}
var McpToolName;
(function (McpToolName) {
    McpToolName["Prefix"] = "mcp_";
    McpToolName[McpToolName["MaxPrefixLen"] = 18] = "MaxPrefixLen";
    McpToolName[McpToolName["MaxLength"] = 64] = "MaxLength";
})(McpToolName || (McpToolName = {}));

export { HasInstalledMcpServersContext, InstalledMcpServersViewId, LazyCollectionState, McpCapability, McpCollectionDefinition, McpCollectionSortOrder, McpConnectionFailedError, McpConnectionState, McpError, McpResourceURI, McpServerCacheState, McpServerContainers, McpServerDefinition, McpServerDefinitionVariableReplacement, McpServerLaunch, McpServerTransportType, McpServersGalleryEnabledContext, McpToolName, MpcResponseError, extensionMcpCollectionPrefix, extensionPrefixedIdentifier, isMcpResourceTemplate, mcpPromptPrefix, mcpPromptReplaceSpecialChars, mcpServerIcon };
