Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,5 @@
*--------------------------------------------------------------------------------------------*/

export type { McpServerSource } from './vscode/mcpCustomizationMeta.js';
export { readMcpRoutingServers, withMcpRoutingServers } from './vscode/mcpCustomizationMeta.js';
export { copilotConnectorReconnectRequiredErrorType, readMcpRoutingServers, withMcpRoutingServers } from './vscode/mcpCustomizationMeta.js';
export { readMcpServerConnectorName, readMcpServerControllingSetting, readMcpServerDisplayName, readMcpServerSource, readMcpServerSourcePlugin, withMcpServerConnectorNameMeta, withMcpServerControllingSettingMeta, withMcpServerDisplayNameMeta, withMcpServerSourceMeta, withMcpServerSourcePluginMeta } from './vscode/mcpCustomizationMeta.js';
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ const controllingSettingKey = 'vscode.mcpServerControllingSetting';
const connectorNameKey = 'vscode.mcpServerConnectorName';
const routingServersKey = 'vscode.mcpRoutingServers';

/**
* `errorType` of a Copilot Connector server whose connection the Connector service reported as broken and
* not retryable. Only reconnecting the Connector, which refreshes its authorization, recovers it.
*/
export const copilotConnectorReconnectRequiredErrorType = 'copilot-connector-reconnect-required';

/** Reads the servers with registered routing tools on this chat. */
export function readMcpRoutingServers(session: { readonly _meta?: Record<string, unknown> } | undefined, chat: string): readonly string[] {
const entries = session?._meta?.[routingServersKey];
Expand Down
103 changes: 91 additions & 12 deletions src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ import type { IAgentHostScopedCredential } from '../../common/agentHostCredentia
import type { ErrorInfo, ProtectedResourceMetadata } from '../../common/state/protocol/common/state.js';
import { CopilotSlashCommandProvider } from './copilotSlashCommandProvider.js';
import { CopilotMcpToolRoutingCache, getMcpRoutingCacheKey, getMcpRoutingProxyName, type ICopilotMcpRoutingServer, type ICopilotMcpRoutingTool } from './copilotMcpToolRoutingCache.js';
import { readMcpRoutingServers, readMcpServerSource, withMcpRoutingServers } from '../../common/meta/mcpCustomizationMeta.js';
import { copilotConnectorReconnectRequiredErrorType, readMcpRoutingServers, readMcpServerSource, withMcpRoutingServers } from '../../common/meta/mcpCustomizationMeta.js';
import { readRuntimePluginEnablement } from '../../common/meta/pluginEnablementMeta.js';
import { AgentHostStateManager, IAgentHostStateManager } from '../agentHostStateManager.js';
import { type CopilotPluginReloadReason, getCopilotCustomizationCommandHandler, installCopilotPlugin, type ICopilotMcpCommandServer, type ICopilotPluginCommandApi, removeCopilotPluginMarketplace } from './copilotCustomizationCommandDisplay.js';
Expand Down Expand Up @@ -1057,6 +1057,26 @@ function getEffectiveMcpServerEnablement(enabled: boolean | undefined, status: S
return status !== undefined ? status !== 'disabled' && status !== 'not_configured' : enabled ?? true;
}

function isRecord(value: unknown): value is Record<string, unknown> {
return isObject(value);
}

function isBrokenCopilotConnectorError(error: string): boolean {
const start = error.indexOf('{');
const end = error.lastIndexOf('}');
if (start === -1 || end < start || !error.includes('"com.github/copilot-connector-errors"')) {
return false;
}
try {
const parsed: unknown = JSON.parse(error.slice(start, end + 1));
const details = isRecord(parsed) ? parsed['com.github/copilot-connector-errors'] : undefined;
return isRecord(details)
&& details.reason === 'connection_broken' && details.action === 'reconnect' && details.retryable === false;
} catch {
return false;
}
}

class DirectUsageAccumulator {
private readonly _tokenTotalsByModel = new Map<string, Mutable<ITurnTokenTotal>>();
private _copilotNanoAiu: number | undefined;
Expand Down Expand Up @@ -2323,6 +2343,8 @@ export class CopilotAgentSession extends Disposable {
private readonly _lastMcpAuthRequirements = new Map<string, ILastMcpAuthRequirement>();
/** Latest SDK status per server, used to notice a server leaving `connected`. */
private readonly _mcpSdkStatus = new Map<string, SdkMcpServerStatus>();
/** Structured failures observed before or after Connector ownership is published. */
private readonly _mcpConnectorReconnectErrors = new Map<string, string>();
/** Servers whose current connection has loaded tools, from lifecycle events or inventory `toolsLoaded`. */
private readonly _mcpToolsLoaded = new Set<string>();
/** Invalidates inventory snapshots when lifecycle events or authentication challenges arrive. */
Expand Down Expand Up @@ -5095,7 +5117,10 @@ export class CopilotAgentSession extends Disposable {
}
const serverName = proxy.server.serverName;
const enabled = this._mcpConfiguredEnablement.get(serverName) ?? this._mcpCustomizations.enabledForServer(serverName);
return enabled !== false
const status = this._mcpSdkStatus.get(serverName);
const reconnecting = this._isCopilotConnectorServer(serverName) && this._mcpConnectorReconnectErrors.has(serverName)
&& (status === 'failed' || status === 'not_configured' || status === 'pending');
return (enabled !== false || reconnecting)
&& this._getDesiredMcpServerEnablementByName([serverName]).get(serverName) !== false
&& !availableTools?.some(tool => tool.mcpServerName === serverName);
}
Expand Down Expand Up @@ -6805,11 +6830,25 @@ export class CopilotAgentSession extends Disposable {
this._copilotConnectorAuthorizationRequired = connectorServers.authorizationRequired;
// Republish servers that stopped being Connector-owned too, so their Connector metadata is removed.
for (const serverName of new Set([...previous, ...connectorServers.servers.keys()])) {
const state = this._mcpCustomizations.stateForServer(serverName);
let state = this._mcpCustomizations.stateForServer(serverName);
const status = this._mcpSdkStatus.get(serverName);
const error = this._mcpConnectorReconnectErrors.get(serverName);
if (error && (status === 'failed' || status === 'not_configured')
&& (!state || state.kind === McpServerStatus.Error || state.kind === McpServerStatus.Stopped)
&& (state || this._isCopilotConnectorServer(serverName))) {
state = this._translateSdkMcpStatus(serverName, status, error, this._hasPendingMcpAuthentication(serverName));
} else if (error && status === 'pending' && !state && this._isCopilotConnectorServer(serverName)) {
state = this._translateSdkMcpStatus(serverName, status, undefined, this._hasPendingMcpAuthentication(serverName));
}
if (state) {
this._mcpCustomizations.applyOne({ name: serverName, displayName: this._copilotConnectorServers.get(serverName)?.displayName, state });
}
}
for (const serverName of previous) {
if (!this._copilotConnectorServers.has(serverName)) {
this._mcpConnectorReconnectErrors.delete(serverName);
}
}
if (this._mcpToolRoutingEnabled && this._clientToolConfiguration?.toolSearchActive) {
await this._replaceClientTools(undefined, this._lifetimeCts.token, true);
}
Expand Down Expand Up @@ -9025,6 +9064,10 @@ export class CopilotAgentSession extends Disposable {
throw new CancellationError();
}
const state = this._mcpCustomizations.stateForServer(serverName);
const reconnectMessage = this._copilotConnectorReconnectMessage(serverName);
if (reconnectMessage && (!state || state.kind === McpServerStatus.Error || state.kind === McpServerStatus.Stopped)) {
throw new Error(reconnectMessage);
}
if (state?.kind === McpServerStatus.AuthRequired) {
this._mcpLifecycleVersion++;
this._mcpCustomizations.applyOne({ name: serverName, state }, true);
Expand Down Expand Up @@ -9296,6 +9339,7 @@ export class CopilotAgentSession extends Disposable {
try {
this._recordRuntimeMutation('mcpDisable');
await this._wrapper.session.rpc.mcp.disable(await this._mcpServerIdentity(serverName));
this._mcpConnectorReconnectErrors.delete(serverName);
this._hostMcpServerEnablement.set(serverName, false);
} catch (error) {
if (this._expectedMcpEnablementChanges.get(serverName) === false) {
Expand All @@ -9316,6 +9360,7 @@ export class CopilotAgentSession extends Disposable {
this._cancelPendingMcpAuthRequestsForServer(serverName);
this._recordRuntimeMutation('userRequested');
await this._wrapper.session.rpc.mcp.stopServer(await this._mcpServerIdentity(serverName));
this._mcpConnectorReconnectErrors.delete(serverName);
this._mcpLifecycleVersion++;
this._mcpCustomizations.applyOne({ name: serverName, state: { kind: McpServerStatus.Stopped } });
}));
Expand Down Expand Up @@ -13692,7 +13737,7 @@ export class CopilotAgentSession extends Disposable {
this._mcpAwaitingOAuthReconnect.delete(e.data.serverName);
}
this._observeMcpRestart(e.data.serverName, e.data.status);
this._noteMcpSdkStatus(e.data.serverName, e.data.status);
this._noteMcpSdkStatus(e.data.serverName, e.data.status, e.data.error, true);
const requirement = this._lastMcpAuthRequirements.get(e.data.serverName);
if (requirement && e.data.status !== 'pending') {
this._lastMcpAuthRequirements.set(e.data.serverName, { ...requirement, acceptsTokenCompletion: false });
Expand Down Expand Up @@ -13797,7 +13842,7 @@ export class CopilotAgentSession extends Disposable {
})), 'inventory');
for (const server of result.servers) {
const status = server.live?.status ?? 'stopped';
this._noteMcpSdkStatus(server.name, status);
this._noteMcpSdkStatus(server.name, status, server.live?.error);
// The bundled SDK types predate inventory `toolsLoaded`; older runtimes use connected as ready.
const toolsLoaded = (server.live as { readonly toolsLoaded?: boolean } | undefined)?.toolsLoaded;
if (toolsLoaded === true || (toolsLoaded === undefined && status === 'connected')) {
Expand Down Expand Up @@ -13988,11 +14033,20 @@ export class CopilotAgentSession extends Disposable {
return { ...server, source, enabled, configuration, configurationError, sourceUri, tools };
}

private _noteMcpSdkStatus(serverName: string, status: SdkMcpServerStatus): void {
private _noteMcpSdkStatus(serverName: string, status: SdkMcpServerStatus, error?: string, statusEvent = false): void {
if (this._mcpSdkStatus.get(serverName) === 'connected' && status !== 'connected') {
this._mcpToolsLoaded.delete(serverName);
this._mcpRoutingConnectionCalls.delete(serverName);
}
if (status === 'failed' && (error !== undefined || statusEvent || this._mcpSdkStatus.get(serverName) !== 'failed')) {
if (error !== undefined && isBrokenCopilotConnectorError(error)) {
this._mcpConnectorReconnectErrors.set(serverName, error);
} else {
this._mcpConnectorReconnectErrors.delete(serverName);
}
} else if (status === 'connected' || status === 'disabled') {
this._mcpConnectorReconnectErrors.delete(serverName);
}
this._mcpSdkStatus.set(serverName, status);
}

Expand Down Expand Up @@ -14030,6 +14084,16 @@ export class CopilotAgentSession extends Disposable {
}
this._mcpInventoryProvenance = new Map(servers.map(server => [server.name, { source: server.source, sourcePlugin: server.sourcePlugin, url: server.url }]));
const sdkServers = servers.map(server => this._toSdkMcpServer(server));
for (const [serverName, connector] of this._copilotConnectorServers) {
const status = this._mcpSdkStatus.get(serverName);
if (!serverNames.has(serverName) && this._mcpConnectorReconnectErrors.has(serverName) && (status === 'failed' || status === 'not_configured' || status === 'pending')) {
sdkServers.push({
name: serverName,
displayName: connector.displayName,
state: this._translateSdkMcpStatus(serverName, status, undefined, this._hasPendingMcpAuthentication(serverName)),
});
}
}
this._mcpCustomizations.applyAll(sdkServers);
for (const server of servers) {
if (server.enabled === undefined) {
Expand Down Expand Up @@ -14216,14 +14280,15 @@ export class CopilotAgentSession extends Disposable {
const previous = this._mcpCustomizations.stateForServer(name);
return { kind: McpServerStatus.Starting, blocking: previous?.kind === McpServerStatus.Starting ? previous.blocking ?? true : true };
}
case 'failed':
case 'failed': {
const reconnectMessage = this._copilotConnectorReconnectMessage(name);
return {
kind: McpServerStatus.Error,
error: {
errorType: 'mcp-server-failed',
message: error ?? 'MCP server failed to start',
},
error: reconnectMessage
? { errorType: copilotConnectorReconnectRequiredErrorType, message: reconnectMessage }
: { errorType: 'mcp-server-failed', message: error ?? 'MCP server failed to start' },
};
}
case 'pending': {
const previous = this._mcpCustomizations.stateForServer(name);
if (hasPendingAuthentication && previous?.kind === McpServerStatus.AuthRequired) {
Expand All @@ -14239,15 +14304,29 @@ export class CopilotAgentSession extends Disposable {
const auth = this._lastMcpAuthRequirements.get(name)?.auth ?? this._copilotConnectorAuthRequirement(name);
return auth ? { kind: McpServerStatus.AuthRequired, ...auth } : { kind: McpServerStatus.Starting };
}
case 'not_configured': {
this._lastMcpAuthRequirements.delete(name);
const message = this._copilotConnectorReconnectMessage(name);
return message
? { kind: McpServerStatus.Error, error: { errorType: copilotConnectorReconnectRequiredErrorType, message } }
: { kind: McpServerStatus.Stopped };
}
case 'disabled':
case 'not_configured':
this._lastMcpAuthRequirements.delete(name);
return { kind: McpServerStatus.Stopped };
default:
return { kind: McpServerStatus.Stopped };
}
}

private _copilotConnectorReconnectMessage(serverName: string): string | undefined {
const connector = this._copilotConnectorServers.get(serverName);
const status = this._mcpSdkStatus.get(serverName);
return connector && this._mcpConnectorReconnectErrors.has(serverName) && (status === 'failed' || status === 'not_configured')
? localize('copilot.connectorReconnect', "Disconnect and reconnect {0} using the Copilot account for this session to reauthorize it. In VS Code, manage connected connectors under Chat: Open Customizations > MCP Servers or browse Copilot Connectors.", connector.displayName)
: undefined;
}

/**
* A runtime that classifies a Connector scope failure reports it on the Connector status instead of asking for
* an MCP token, so describe the requirement for a Connector-owned server that needs authentication.
Expand Down
Loading