diff --git a/extensions/json-language-features/client/src/jsonClient.ts b/extensions/json-language-features/client/src/jsonClient.ts index 95d0a131b7c..eb336e8f89b 100644 --- a/extensions/json-language-features/client/src/jsonClient.ts +++ b/extensions/json-language-features/client/src/jsonClient.ts @@ -650,8 +650,6 @@ async function startClientWithParticipants(_context: ExtensionContext, languageP async function getSchemaAssociations(forceRefresh: boolean): Promise { if (!schemaAssociationsCache || forceRefresh) { schemaAssociationsCache = computeSchemaAssociations(); - runtime.logOutputChannel.info(`Computed schema associations: ${(await schemaAssociationsCache).map(a => `${a.uri} -> [${a.fileMatch.join(', ')}]`).join('\n')}`); - } return schemaAssociationsCache; } diff --git a/package.json b/package.json index 5023a7daebb..4c450e79c73 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "code-oss-dev", "version": "1.109.0", - "distro": "84c8b9580d546487fee8ff25a29c5f3f49d33799", + "distro": "6c9f72a1ba8565301b303ec4314f5a24d585f012", "author": { "name": "Microsoft Corporation" }, @@ -240,4 +240,4 @@ "optionalDependencies": { "windows-foreground-love": "0.6.1" } -} +} \ No newline at end of file diff --git a/src/vs/base/browser/ui/contextview/contextview.ts b/src/vs/base/browser/ui/contextview/contextview.ts index b3bfc63cb79..44c3c080e24 100644 --- a/src/vs/base/browser/ui/contextview/contextview.ts +++ b/src/vs/base/browser/ui/contextview/contextview.ts @@ -7,13 +7,11 @@ import { BrowserFeatures } from '../../canIUse.js'; import * as DOM from '../../dom.js'; import { StandardMouseEvent } from '../../mouseEvent.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../common/lifecycle.js'; -import { AnchorAlignment, AnchorAxisAlignment, AnchorPosition, IRect, layout2d } from '../../../common/layout.js'; import * as platform from '../../../common/platform.js'; +import { Range } from '../../../common/range.js'; import { OmitOptional } from '../../../common/types.js'; import './contextview.css'; -export { AnchorAlignment, AnchorAxisAlignment, AnchorPosition } from '../../../common/layout.js'; - export const enum ContextViewDOMPosition { ABSOLUTE = 1, FIXED, @@ -33,6 +31,18 @@ export function isAnchor(obj: unknown): obj is IAnchor | OmitOptional { return !!anchor && typeof anchor.x === 'number' && typeof anchor.y === 'number'; } +export const enum AnchorAlignment { + LEFT, RIGHT +} + +export const enum AnchorPosition { + BELOW, ABOVE +} + +export const enum AnchorAxisAlignment { + VERTICAL, HORIZONTAL +} + export interface IDelegate { /** * The anchor where to position the context view. @@ -63,40 +73,66 @@ export interface IContextViewProvider { layout(): void; } -export function getAnchorRect(anchor: HTMLElement | StandardMouseEvent | IAnchor): IRect { - // Get the element's position and size (to anchor the view) - if (DOM.isHTMLElement(anchor)) { - const elementPosition = DOM.getDomNodePagePosition(anchor); +export interface IPosition { + top: number; + left: number; +} - // In areas where zoom is applied to the element or its ancestors, we need to adjust the size of the element - // e.g. The title bar has counter zoom behavior meaning it applies the inverse of zoom level. - // Window Zoom Level: 1.5, Title Bar Zoom: 1/1.5, Size Multiplier: 1.5 - const zoom = DOM.getDomNodeZoomLevel(anchor); +export interface ISize { + width: number; + height: number; +} - return { - top: elementPosition.top * zoom, - left: elementPosition.left * zoom, - width: elementPosition.width * zoom, - height: elementPosition.height * zoom - }; - } else if (isAnchor(anchor)) { - return { - top: anchor.y, - left: anchor.x, - width: anchor.width || 1, - height: anchor.height || 2 - }; +export interface IView extends IPosition, ISize { } + +export const enum LayoutAnchorPosition { + Before, + After +} + +export enum LayoutAnchorMode { + AVOID, + ALIGN +} + +export interface ILayoutAnchor { + offset: number; + size: number; + mode?: LayoutAnchorMode; // default: AVOID + position: LayoutAnchorPosition; +} + +/** + * Lays out a one dimensional view next to an anchor in a viewport. + * + * @returns The view offset within the viewport. + */ +export function layout(viewportSize: number, viewSize: number, anchor: ILayoutAnchor): number { + const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size; + const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset; + + if (anchor.position === LayoutAnchorPosition.Before) { + if (viewSize <= viewportSize - layoutAfterAnchorBoundary) { + return layoutAfterAnchorBoundary; // happy case, lay it out after the anchor + } + + if (viewSize <= layoutBeforeAnchorBoundary) { + return layoutBeforeAnchorBoundary - viewSize; // ok case, lay it out before the anchor + } + + return Math.max(viewportSize - viewSize, 0); // sad case, lay it over the anchor } else { - return { - top: anchor.posy, - left: anchor.posx, - // We are about to position the context view where the mouse - // cursor is. To prevent the view being exactly under the mouse - // when showing and thus potentially triggering an action within, - // we treat the mouse location like a small sized block element. - width: 2, - height: 2 - }; + if (viewSize <= layoutBeforeAnchorBoundary) { + return layoutBeforeAnchorBoundary - viewSize; // happy case, lay it out before the anchor + } + + + if (viewSize <= viewportSize - layoutAfterAnchorBoundary && layoutBeforeAnchorBoundary < viewSize / 2) { + return layoutAfterAnchorBoundary; // ok case, lay it out after the anchor + } + + + return 0; // sad case, lay it over the anchor } } @@ -234,14 +270,82 @@ export class ContextView extends Disposable { } // Get anchor - const anchor = getAnchorRect(this.delegate!.getAnchor()); + const anchor = this.delegate!.getAnchor(); + + // Compute around + let around: IView; + + // Get the element's position and size (to anchor the view) + if (DOM.isHTMLElement(anchor)) { + const elementPosition = DOM.getDomNodePagePosition(anchor); + + // In areas where zoom is applied to the element or its ancestors, we need to adjust the size of the element + // e.g. The title bar has counter zoom behavior meaning it applies the inverse of zoom level. + // Window Zoom Level: 1.5, Title Bar Zoom: 1/1.5, Size Multiplier: 1.5 + const zoom = DOM.getDomNodeZoomLevel(anchor); + + around = { + top: elementPosition.top * zoom, + left: elementPosition.left * zoom, + width: elementPosition.width * zoom, + height: elementPosition.height * zoom + }; + } else if (isAnchor(anchor)) { + around = { + top: anchor.y, + left: anchor.x, + width: anchor.width || 1, + height: anchor.height || 2 + }; + } else { + around = { + top: anchor.posy, + left: anchor.posx, + // We are about to position the context view where the mouse + // cursor is. To prevent the view being exactly under the mouse + // when showing and thus potentially triggering an action within, + // we treat the mouse location like a small sized block element. + width: 2, + height: 2 + }; + } + + const viewSizeWidth = DOM.getTotalWidth(this.view); + const viewSizeHeight = DOM.getTotalHeight(this.view); + + const anchorPosition = this.delegate!.anchorPosition ?? AnchorPosition.BELOW; + const anchorAlignment = this.delegate!.anchorAlignment ?? AnchorAlignment.LEFT; + const anchorAxisAlignment = this.delegate!.anchorAxisAlignment ?? AnchorAxisAlignment.VERTICAL; + + let top: number; + let left: number; + const activeWindow = DOM.getActiveWindow(); - const viewport = { top: activeWindow.pageYOffset, left: activeWindow.pageXOffset, width: activeWindow.innerWidth, height: activeWindow.innerHeight }; - const view = { width: DOM.getTotalWidth(this.view), height: DOM.getTotalHeight(this.view) }; - const anchorPosition = this.delegate!.anchorPosition; - const anchorAlignment = this.delegate!.anchorAlignment; - const anchorAxisAlignment = this.delegate!.anchorAxisAlignment; - const { top, left } = layout2d(viewport, view, anchor, { anchorAlignment, anchorPosition, anchorAxisAlignment }); + if (anchorAxisAlignment === AnchorAxisAlignment.VERTICAL) { + const verticalAnchor: ILayoutAnchor = { offset: around.top - activeWindow.pageYOffset, size: around.height, position: anchorPosition === AnchorPosition.BELOW ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After }; + const horizontalAnchor: ILayoutAnchor = { offset: around.left, size: around.width, position: anchorAlignment === AnchorAlignment.LEFT ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After, mode: LayoutAnchorMode.ALIGN }; + + top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset; + + // if view intersects vertically with anchor, we must avoid the anchor + if (Range.intersects({ start: top, end: top + viewSizeHeight }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) { + horizontalAnchor.mode = LayoutAnchorMode.AVOID; + } + + left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor); + } else { + const horizontalAnchor: ILayoutAnchor = { offset: around.left, size: around.width, position: anchorAlignment === AnchorAlignment.LEFT ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After }; + const verticalAnchor: ILayoutAnchor = { offset: around.top, size: around.height, position: anchorPosition === AnchorPosition.BELOW ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After, mode: LayoutAnchorMode.ALIGN }; + + left = layout(activeWindow.innerWidth, viewSizeWidth, horizontalAnchor); + + // if view intersects horizontally with anchor, we must avoid the anchor + if (Range.intersects({ start: left, end: left + viewSizeWidth }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) { + verticalAnchor.mode = LayoutAnchorMode.AVOID; + } + + top = layout(activeWindow.innerHeight, viewSizeHeight, verticalAnchor) + activeWindow.pageYOffset; + } this.view.classList.remove('top', 'bottom', 'left', 'right'); this.view.classList.add(anchorPosition === AnchorPosition.BELOW ? 'bottom' : 'top'); diff --git a/src/vs/base/browser/ui/menu/menu.ts b/src/vs/base/browser/ui/menu/menu.ts index c747ea1cd87..f48c4488073 100644 --- a/src/vs/base/browser/ui/menu/menu.ts +++ b/src/vs/base/browser/ui/menu/menu.ts @@ -11,6 +11,7 @@ import { StandardKeyboardEvent } from '../../keyboardEvent.js'; import { StandardMouseEvent } from '../../mouseEvent.js'; import { ActionBar, ActionsOrientation, IActionViewItemProvider } from '../actionbar/actionbar.js'; import { ActionViewItem, BaseActionViewItem, IActionViewItemOptions } from '../actionbar/actionViewItems.js'; +import { AnchorAlignment, layout, LayoutAnchorPosition } from '../contextview/contextview.js'; import { DomScrollableElement } from '../scrollbar/scrollableElement.js'; import { EmptySubmenuAction, IAction, IActionRunner, Separator, SubmenuAction } from '../../../common/actions.js'; import { RunOnceScheduler } from '../../../common/async.js'; @@ -25,7 +26,6 @@ import { DisposableStore } from '../../../common/lifecycle.js'; import { isLinux, isMacintosh } from '../../../common/platform.js'; import { ScrollbarVisibility, ScrollEvent } from '../../../common/scrollable.js'; import * as strings from '../../../common/strings.js'; -import { AnchorAlignment, layout, LayoutAnchorPosition } from '../../../common/layout.js'; export const MENU_MNEMONIC_REGEX = /\(&([^\s&])\)|(^|[^&])&([^\s&])/; export const MENU_ESCAPED_MNEMONIC_REGEX = /(&)?(&)([^\s&])/g; @@ -859,7 +859,7 @@ class SubmenuMenuActionViewItem extends BaseMenuActionViewItem { const ret = { top: 0, left: 0 }; // Start with horizontal - ret.left = layout(windowDimensions.width, submenu.width, { position: expandDirection.horizontal === HorizontalDirection.Right ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After, offset: entry.left, size: entry.width }).position; + ret.left = layout(windowDimensions.width, submenu.width, { position: expandDirection.horizontal === HorizontalDirection.Right ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After, offset: entry.left, size: entry.width }); // We don't have enough room to layout the menu fully, so we are overlapping the menu if (ret.left >= entry.left && ret.left < entry.left + entry.width) { @@ -872,7 +872,7 @@ class SubmenuMenuActionViewItem extends BaseMenuActionViewItem { } // Now that we have a horizontal position, try layout vertically - ret.top = layout(windowDimensions.height, submenu.height, { position: LayoutAnchorPosition.Before, offset: entry.top, size: 0 }).position; + ret.top = layout(windowDimensions.height, submenu.height, { position: LayoutAnchorPosition.Before, offset: entry.top, size: 0 }); // We didn't have enough room below, but we did above, so we shift down to align the menu if (ret.top + submenu.height === entry.top && ret.top + entry.height + submenu.height <= windowDimensions.height) { diff --git a/src/vs/base/common/defaultAccount.ts b/src/vs/base/common/defaultAccount.ts index 6b7f5d76d50..352fa5e4b34 100644 --- a/src/vs/base/common/defaultAccount.ts +++ b/src/vs/base/common/defaultAccount.ts @@ -59,5 +59,4 @@ export interface IDefaultAccount { readonly sessionId: string; readonly enterprise: boolean; readonly entitlementsData?: IEntitlementsData | null; - readonly policyData?: IPolicyData; } diff --git a/src/vs/base/common/layout.ts b/src/vs/base/common/layout.ts deleted file mode 100644 index fdfcba9695b..00000000000 --- a/src/vs/base/common/layout.ts +++ /dev/null @@ -1,166 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { Range } from './range.js'; - -export interface IAnchor { - x: number; - y: number; - width?: number; - height?: number; -} - -export const enum AnchorAlignment { - LEFT, RIGHT -} - -export const enum AnchorPosition { - BELOW, ABOVE -} - -export const enum AnchorAxisAlignment { - VERTICAL, HORIZONTAL -} - -interface IPosition { - readonly top: number; - readonly left: number; -} - -interface ISize { - readonly width: number; - readonly height: number; -} - -export interface IRect extends IPosition, ISize { } - -export const enum LayoutAnchorPosition { - Before, - After -} - -export enum LayoutAnchorMode { - AVOID, - ALIGN -} - -export interface ILayoutAnchor { - offset: number; - size: number; - mode?: LayoutAnchorMode; // default: AVOID - position: LayoutAnchorPosition; -} - -export interface ILayoutResult { - position: number; - result: 'ok' | 'flipped' | 'overlap'; -} - -/** - * Lays out a one dimensional view next to an anchor in a viewport. - * - * @returns The view offset within the viewport. - */ -export function layout(viewportSize: number, viewSize: number, anchor: ILayoutAnchor): ILayoutResult { - const layoutAfterAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset : anchor.offset + anchor.size; - const layoutBeforeAnchorBoundary = anchor.mode === LayoutAnchorMode.ALIGN ? anchor.offset + anchor.size : anchor.offset; - - if (anchor.position === LayoutAnchorPosition.Before) { - if (viewSize <= viewportSize - layoutAfterAnchorBoundary) { - return { position: layoutAfterAnchorBoundary, result: 'ok' }; // happy case, lay it out after the anchor - } - - if (viewSize <= layoutBeforeAnchorBoundary) { - return { position: layoutBeforeAnchorBoundary - viewSize, result: 'flipped' }; // ok case, lay it out before the anchor - } - - return { position: Math.max(viewportSize - viewSize, 0), result: 'overlap' }; // sad case, lay it over the anchor - } else { - if (viewSize <= layoutBeforeAnchorBoundary) { - return { position: layoutBeforeAnchorBoundary - viewSize, result: 'ok' }; // happy case, lay it out before the anchor - } - - if (viewSize <= viewportSize - layoutAfterAnchorBoundary && layoutBeforeAnchorBoundary < viewSize / 2) { - return { position: layoutAfterAnchorBoundary, result: 'flipped' }; // ok case, lay it out after the anchor - } - - return { position: 0, result: 'overlap' }; // sad case, lay it over the anchor - } -} - -interface ILayout2DOptions { - readonly anchorAlignment?: AnchorAlignment; // default: left - readonly anchorPosition?: AnchorPosition; // default: below - readonly anchorAxisAlignment?: AnchorAxisAlignment; // default: vertical -} - -export interface ILayout2DResult { - top: number; - left: number; - bottom: number; - right: number; - anchorAlignment: AnchorAlignment; - anchorPosition: AnchorPosition; -} - -export function layout2d(viewport: IRect, view: ISize, anchor: IRect, options?: ILayout2DOptions): ILayout2DResult { - let anchorAlignment = options?.anchorAlignment ?? AnchorAlignment.LEFT; - let anchorPosition = options?.anchorPosition ?? AnchorPosition.ABOVE; - const anchorAxisAlignment = options?.anchorAxisAlignment ?? AnchorAxisAlignment.VERTICAL; - - let top: number; - let left: number; - - if (anchorAxisAlignment === AnchorAxisAlignment.VERTICAL) { - const verticalAnchor: ILayoutAnchor = { offset: anchor.top - viewport.top, size: anchor.height, position: anchorPosition === AnchorPosition.BELOW ? LayoutAnchorPosition.After : LayoutAnchorPosition.Before }; - const horizontalAnchor: ILayoutAnchor = { offset: anchor.left, size: anchor.width, position: anchorAlignment === AnchorAlignment.LEFT ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After, mode: LayoutAnchorMode.ALIGN }; - - const verticalLayoutResult = layout(viewport.height, view.height, verticalAnchor); - top = verticalLayoutResult.position + viewport.top; - - if (verticalLayoutResult.result === 'flipped') { - anchorPosition = anchorPosition === AnchorPosition.BELOW ? AnchorPosition.ABOVE : AnchorPosition.BELOW; - } - - // if view intersects vertically with anchor, we must avoid the anchor - if (Range.intersects({ start: top, end: top + view.height }, { start: verticalAnchor.offset, end: verticalAnchor.offset + verticalAnchor.size })) { - horizontalAnchor.mode = LayoutAnchorMode.AVOID; - } - - const horizontalLayoutResult = layout(viewport.width, view.width, horizontalAnchor); - left = horizontalLayoutResult.position; - - if (horizontalLayoutResult.result === 'flipped') { - anchorAlignment = anchorAlignment === AnchorAlignment.LEFT ? AnchorAlignment.RIGHT : AnchorAlignment.LEFT; - } - } else { - const horizontalAnchor: ILayoutAnchor = { offset: anchor.left, size: anchor.width, position: anchorAlignment === AnchorAlignment.LEFT ? LayoutAnchorPosition.Before : LayoutAnchorPosition.After }; - const verticalAnchor: ILayoutAnchor = { offset: anchor.top, size: anchor.height, position: anchorPosition === AnchorPosition.BELOW ? LayoutAnchorPosition.After : LayoutAnchorPosition.Before, mode: LayoutAnchorMode.ALIGN }; - - const horizontalLayoutResult = layout(viewport.width, view.width, horizontalAnchor); - left = horizontalLayoutResult.position; - - if (horizontalLayoutResult.result === 'flipped') { - anchorAlignment = anchorAlignment === AnchorAlignment.LEFT ? AnchorAlignment.RIGHT : AnchorAlignment.LEFT; - } - - // if view intersects horizontally with anchor, we must avoid the anchor - if (Range.intersects({ start: left, end: left + view.width }, { start: horizontalAnchor.offset, end: horizontalAnchor.offset + horizontalAnchor.size })) { - verticalAnchor.mode = LayoutAnchorMode.AVOID; - } - - const verticalLayoutResult = layout(viewport.height, view.height, verticalAnchor); - top = verticalLayoutResult.position + viewport.top; - - if (verticalLayoutResult.result === 'flipped') { - anchorPosition = anchorPosition === AnchorPosition.BELOW ? AnchorPosition.ABOVE : AnchorPosition.BELOW; - } - } - - const right = viewport.width - (left + view.width); - const bottom = viewport.height - (top + view.height); - - return { top, left, bottom, right, anchorAlignment, anchorPosition }; -} diff --git a/src/vs/base/common/policy.ts b/src/vs/base/common/policy.ts index 8141b0f9b5d..c27030fe03a 100644 --- a/src/vs/base/common/policy.ts +++ b/src/vs/base/common/policy.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { localize } from '../../nls.js'; -import { IDefaultAccount } from './defaultAccount.js'; +import { IPolicyData } from './defaultAccount.js'; /** * System-wide policy file path for Linux systems. @@ -96,5 +96,5 @@ export interface IPolicy { * * If `undefined`, the feature's setting is not locked and can be overridden by other means. */ - readonly value?: (account: IDefaultAccount) => string | number | boolean | undefined; + readonly value?: (policyData: IPolicyData) => string | number | boolean | undefined; } diff --git a/src/vs/base/test/common/layout.test.ts b/src/vs/base/test/browser/ui/contextview/contextview.test.ts similarity index 60% rename from src/vs/base/test/common/layout.test.ts rename to src/vs/base/test/browser/ui/contextview/contextview.test.ts index a6be1ea8ed2..4058d33f4a9 100644 --- a/src/vs/base/test/common/layout.test.ts +++ b/src/vs/base/test/browser/ui/contextview/contextview.test.ts @@ -4,26 +4,27 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { layout, LayoutAnchorPosition } from '../../common/layout.js'; -import { ensureNoDisposablesAreLeakedInTestSuite } from './utils.js'; +import { layout, LayoutAnchorPosition } from '../../../../browser/ui/contextview/contextview.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../common/utils.js'; -suite('Layout', function () { +suite('Contextview', function () { test('layout', () => { - assert.strictEqual(layout(200, 20, { offset: 0, size: 0, position: LayoutAnchorPosition.Before }).position, 0); - assert.strictEqual(layout(200, 20, { offset: 50, size: 0, position: LayoutAnchorPosition.Before }).position, 50); - assert.strictEqual(layout(200, 20, { offset: 200, size: 0, position: LayoutAnchorPosition.Before }).position, 180); + assert.strictEqual(layout(200, 20, { offset: 0, size: 0, position: LayoutAnchorPosition.Before }), 0); + assert.strictEqual(layout(200, 20, { offset: 50, size: 0, position: LayoutAnchorPosition.Before }), 50); + assert.strictEqual(layout(200, 20, { offset: 200, size: 0, position: LayoutAnchorPosition.Before }), 180); - assert.strictEqual(layout(200, 20, { offset: 0, size: 0, position: LayoutAnchorPosition.After }).position, 0); - assert.strictEqual(layout(200, 20, { offset: 50, size: 0, position: LayoutAnchorPosition.After }).position, 30); - assert.strictEqual(layout(200, 20, { offset: 200, size: 0, position: LayoutAnchorPosition.After }).position, 180); - assert.strictEqual(layout(200, 20, { offset: 0, size: 50, position: LayoutAnchorPosition.Before }).position, 50); - assert.strictEqual(layout(200, 20, { offset: 50, size: 50, position: LayoutAnchorPosition.Before }).position, 100); - assert.strictEqual(layout(200, 20, { offset: 150, size: 50, position: LayoutAnchorPosition.Before }).position, 130); + assert.strictEqual(layout(200, 20, { offset: 0, size: 0, position: LayoutAnchorPosition.After }), 0); + assert.strictEqual(layout(200, 20, { offset: 50, size: 0, position: LayoutAnchorPosition.After }), 30); + assert.strictEqual(layout(200, 20, { offset: 200, size: 0, position: LayoutAnchorPosition.After }), 180); - assert.strictEqual(layout(200, 20, { offset: 0, size: 50, position: LayoutAnchorPosition.After }).position, 50); - assert.strictEqual(layout(200, 20, { offset: 50, size: 50, position: LayoutAnchorPosition.After }).position, 30); - assert.strictEqual(layout(200, 20, { offset: 150, size: 50, position: LayoutAnchorPosition.After }).position, 130); + assert.strictEqual(layout(200, 20, { offset: 0, size: 50, position: LayoutAnchorPosition.Before }), 50); + assert.strictEqual(layout(200, 20, { offset: 50, size: 50, position: LayoutAnchorPosition.Before }), 100); + assert.strictEqual(layout(200, 20, { offset: 150, size: 50, position: LayoutAnchorPosition.Before }), 130); + + assert.strictEqual(layout(200, 20, { offset: 0, size: 50, position: LayoutAnchorPosition.After }), 50); + assert.strictEqual(layout(200, 20, { offset: 50, size: 50, position: LayoutAnchorPosition.After }), 30); + assert.strictEqual(layout(200, 20, { offset: 150, size: 50, position: LayoutAnchorPosition.After }), 130); }); ensureNoDisposablesAreLeakedInTestSuite(); diff --git a/src/vs/editor/browser/services/editorWorkerService.ts b/src/vs/editor/browser/services/editorWorkerService.ts index c5d160cb899..d5c878af3b3 100644 --- a/src/vs/editor/browser/services/editorWorkerService.ts +++ b/src/vs/editor/browser/services/editorWorkerService.ts @@ -37,6 +37,7 @@ import { EditorWorkerHost } from '../../common/services/editorWorkerHost.js'; import { StringEdit } from '../../common/core/edits/stringEdit.js'; import { OffsetRange } from '../../common/core/ranges/offsetRange.js'; import { FileAccess } from '../../../base/common/network.js'; +import { isCompletionsEnabledWithTextResourceConfig } from '../../common/services/completionsEnablement.js'; /** * Stop the worker if it was not needed for 5 min. @@ -280,7 +281,9 @@ class WordBasedCompletionItemProvider implements languages.CompletionItemProvide return undefined; } - if (config.wordBasedSuggestions === 'offWithInlineSuggestions' && this.languageFeaturesService.inlineCompletionsProvider.has(model)) { + if (config.wordBasedSuggestions === 'offWithInlineSuggestions' + && this.languageFeaturesService.inlineCompletionsProvider.has(model) + && isCompletionsEnabledWithTextResourceConfig(this._configurationService, model.uri, model.getLanguageId())) { return undefined; } diff --git a/src/vs/editor/common/services/completionsEnablement.ts b/src/vs/editor/common/services/completionsEnablement.ts new file mode 100644 index 00000000000..b113f24da41 --- /dev/null +++ b/src/vs/editor/common/services/completionsEnablement.ts @@ -0,0 +1,78 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import product from '../../../platform/product/common/product.js'; +import { isObject } from '../../../base/common/types.js'; +import { IConfigurationService } from '../../../platform/configuration/common/configuration.js'; +import { ITextResourceConfigurationService } from './textResourceConfiguration.js'; +import { URI } from '../../../base/common/uri.js'; + +/** + * Get the completions enablement setting name from product configuration. + */ +function getCompletionsEnablementSettingName(): string | undefined { + return product.defaultChatAgent?.completionsEnablementSetting; +} + +/** + * Checks if completions (e.g., Copilot) are enabled for a given language ID + * using `IConfigurationService`. + * + * @param configurationService The configuration service to read settings from. + * @param modeId The language ID to check. Defaults to '*' which checks the global setting. + * @returns `true` if completions are enabled for the language, `false` otherwise. + */ +export function isCompletionsEnabled(configurationService: IConfigurationService, modeId: string = '*'): boolean { + const settingName = getCompletionsEnablementSettingName(); + if (!settingName) { + return false; + } + + return isCompletionsEnabledFromObject( + configurationService.getValue>(settingName), + modeId + ); +} + +/** + * Checks if completions (e.g., Copilot) are enabled for a given language ID + * using `ITextResourceConfigurationService`. + * + * @param configurationService The text resource configuration service to read settings from. + * @param modeId The language ID to check. Defaults to '*' which checks the global setting. + * @returns `true` if completions are enabled for the language, `false` otherwise. + */ +export function isCompletionsEnabledWithTextResourceConfig(configurationService: ITextResourceConfigurationService, resource: URI, modeId: string = '*'): boolean { + const settingName = getCompletionsEnablementSettingName(); + if (!settingName) { + return false; + } + + // Pass undefined as resource to get the global setting + return isCompletionsEnabledFromObject( + configurationService.getValue>(resource, settingName), + modeId + ); +} + +/** + * Checks if completions are enabled for a given language ID using a pre-fetched + * completions enablement object. + * + * @param completionsEnablementObject The object containing per-language enablement settings. + * @param modeId The language ID to check. Defaults to '*' which checks the global setting. + * @returns `true` if completions are enabled for the language, `false` otherwise. + */ +export function isCompletionsEnabledFromObject(completionsEnablementObject: Record | undefined, modeId: string = '*'): boolean { + if (!isObject(completionsEnablementObject)) { + return false; // default to disabled if setting is not available + } + + if (typeof completionsEnablementObject[modeId] !== 'undefined') { + return Boolean(completionsEnablementObject[modeId]); // go with setting if explicitly defined + } + + return Boolean(completionsEnablementObject['*']); // fallback to global setting otherwise +} diff --git a/src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource.ts b/src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource.ts index b936f4d216d..83d4831495d 100644 --- a/src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource.ts +++ b/src/vs/editor/contrib/inlineCompletions/browser/model/inlineCompletionsSource.ts @@ -28,6 +28,7 @@ import { Command, InlineCompletionEndOfLifeReasonKind, InlineCompletionTriggerKi import { ILanguageConfigurationService } from '../../../../common/languages/languageConfigurationRegistry.js'; import { ITextModel } from '../../../../common/model.js'; import { offsetEditFromContentChanges } from '../../../../common/model/textModelStringEdit.js'; +import { isCompletionsEnabledFromObject } from '../../../../common/services/completionsEnablement.js'; import { IFeatureDebounceInformation } from '../../../../common/services/languageFeatureDebounce.js'; import { IModelContentChangedEvent } from '../../../../common/textModelEvents.js'; import { formatRecordableLogEntry, IRecordableEditorLogEntry, IRecordableLogEntry, StructuredLogger } from '../structuredLogger.js'; @@ -445,7 +446,7 @@ export class InlineCompletionsSource extends Disposable { } - if (!isCompletionsEnabled(this._completionsEnabled, this._textModel.getLanguageId())) { + if (!isCompletionsEnabledFromObject(this._completionsEnabled, this._textModel.getLanguageId())) { return; } @@ -571,18 +572,6 @@ function isSubset(set1: Set, set2: Set): boolean { return [...set1].every(item => set2.has(item)); } -function isCompletionsEnabled(completionsEnablementObject: Record | undefined, modeId: string = '*'): boolean { - if (completionsEnablementObject === undefined) { - return false; // default to disabled if setting is not available - } - - if (typeof completionsEnablementObject[modeId] !== 'undefined') { - return Boolean(completionsEnablementObject[modeId]); // go with setting if explicitly defined - } - - return Boolean(completionsEnablementObject['*']); // fallback to global setting otherwise -} - class UpdateOperation implements IDisposable { constructor( public readonly request: UpdateRequest, diff --git a/src/vs/editor/contrib/inlineCompletions/test/browser/utils.ts b/src/vs/editor/contrib/inlineCompletions/test/browser/utils.ts index 5b61a15bfb8..d3b3856cef3 100644 --- a/src/vs/editor/contrib/inlineCompletions/test/browser/utils.ts +++ b/src/vs/editor/contrib/inlineCompletions/test/browser/utils.ts @@ -267,6 +267,8 @@ export async function withAsyncTestCodeEditorAndInlineCompletionsModel( options.serviceCollection.set(IDefaultAccountService, { _serviceBrand: undefined, onDidChangeDefaultAccount: Event.None, + onDidChangePolicyData: Event.None, + policyData: null, getDefaultAccount: async () => null, setDefaultAccountProvider: () => { }, getDefaultAccountAuthenticationProvider: () => { return { id: 'mockProvider', name: 'Mock Provider', enterprise: false }; }, diff --git a/src/vs/editor/standalone/browser/standaloneServices.ts b/src/vs/editor/standalone/browser/standaloneServices.ts index 61c629eda52..61aa37410e2 100644 --- a/src/vs/editor/standalone/browser/standaloneServices.ts +++ b/src/vs/editor/standalone/browser/standaloneServices.ts @@ -100,7 +100,7 @@ import { IDataChannelService, NullDataChannelService } from '../../../platform/d import { IWebWorkerService } from '../../../platform/webWorker/browser/webWorkerService.js'; import { StandaloneWebWorkerService } from './services/standaloneWebWorkerService.js'; import { IDefaultAccountService } from '../../../platform/defaultAccount/common/defaultAccount.js'; -import { IDefaultAccount, IDefaultAccountAuthenticationProvider } from '../../../base/common/defaultAccount.js'; +import { IDefaultAccount, IDefaultAccountAuthenticationProvider, IPolicyData } from '../../../base/common/defaultAccount.js'; class SimpleModel implements IResolvedTextEditorModel { @@ -1115,6 +1115,8 @@ class StandaloneDefaultAccountService implements IDefaultAccountService { declare readonly _serviceBrand: undefined; readonly onDidChangeDefaultAccount: Event = Event.None; + readonly onDidChangePolicyData: Event = Event.None; + readonly policyData: IPolicyData | null = null; async getDefaultAccount(): Promise { return null; diff --git a/src/vs/platform/defaultAccount/common/defaultAccount.ts b/src/vs/platform/defaultAccount/common/defaultAccount.ts index d3bee567a79..63a9b956608 100644 --- a/src/vs/platform/defaultAccount/common/defaultAccount.ts +++ b/src/vs/platform/defaultAccount/common/defaultAccount.ts @@ -5,11 +5,13 @@ import { createDecorator } from '../../instantiation/common/instantiation.js'; import { Event } from '../../../base/common/event.js'; -import { IDefaultAccount, IDefaultAccountAuthenticationProvider } from '../../../base/common/defaultAccount.js'; +import { IDefaultAccount, IDefaultAccountAuthenticationProvider, IPolicyData } from '../../../base/common/defaultAccount.js'; export interface IDefaultAccountProvider { readonly defaultAccount: IDefaultAccount | null; readonly onDidChangeDefaultAccount: Event; + readonly policyData: IPolicyData | null; + readonly onDidChangePolicyData: Event; getDefaultAccountAuthenticationProvider(): IDefaultAccountAuthenticationProvider; refresh(): Promise; signIn(options?: { additionalScopes?: readonly string[];[key: string]: unknown }): Promise; @@ -20,6 +22,8 @@ export const IDefaultAccountService = createDecorator('d export interface IDefaultAccountService { readonly _serviceBrand: undefined; readonly onDidChangeDefaultAccount: Event; + readonly onDidChangePolicyData: Event; + readonly policyData: IPolicyData | null; getDefaultAccount(): Promise; getDefaultAccountAuthenticationProvider(): IDefaultAccountAuthenticationProvider; setDefaultAccountProvider(provider: IDefaultAccountProvider): void; diff --git a/src/vs/platform/extensions/common/extensions.ts b/src/vs/platform/extensions/common/extensions.ts index e8470285f7f..021ad016e02 100644 --- a/src/vs/platform/extensions/common/extensions.ts +++ b/src/vs/platform/extensions/common/extensions.ts @@ -235,6 +235,7 @@ export interface IExtensionContributions { readonly chatPromptFiles?: ReadonlyArray; readonly chatInstructions?: ReadonlyArray; readonly chatAgents?: ReadonlyArray; + readonly chatSkills?: ReadonlyArray; readonly languageModelTools?: ReadonlyArray; readonly languageModelToolSets?: ReadonlyArray; readonly mcpServerDefinitionProviders?: ReadonlyArray; diff --git a/src/vs/platform/policy/common/policy.ts b/src/vs/platform/policy/common/policy.ts index a02d49e28d9..f8b86c80704 100644 --- a/src/vs/platform/policy/common/policy.ts +++ b/src/vs/platform/policy/common/policy.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { IStringDictionary } from '../../../base/common/collections.js'; -import { IDefaultAccount } from '../../../base/common/defaultAccount.js'; +import { IPolicyData } from '../../../base/common/defaultAccount.js'; import { Emitter, Event } from '../../../base/common/event.js'; import { Iterable } from '../../../base/common/iterator.js'; import { Disposable } from '../../../base/common/lifecycle.js'; @@ -14,7 +14,7 @@ import { createDecorator } from '../../instantiation/common/instantiation.js'; export type PolicyValue = string | number | boolean; export type PolicyDefinition = { type: 'string' | 'number' | 'boolean'; - value?: (account: IDefaultAccount) => string | number | boolean | undefined; + value?: (policyData: IPolicyData) => string | number | boolean | undefined; }; export const IPolicyService = createDecorator('policy'); diff --git a/src/vs/platform/quickinput/browser/media/quickInput.css b/src/vs/platform/quickinput/browser/media/quickInput.css index bd509719a3c..0636687742d 100644 --- a/src/vs/platform/quickinput/browser/media/quickInput.css +++ b/src/vs/platform/quickinput/browser/media/quickInput.css @@ -20,11 +20,6 @@ border-top-left-radius: 5px; } -.quick-input-widget.no-drag .quick-input-titlebar, -.quick-input-widget.no-drag .quick-input-title, -.quick-input-widget.no-drag .quick-input-header { - cursor: default; -} .quick-input-widget .monaco-inputbox .monaco-action-bar { top: 0; } diff --git a/src/vs/platform/quickinput/browser/quickInputController.ts b/src/vs/platform/quickinput/browser/quickInputController.ts index 419f83a03e3..a3a85e36a35 100644 --- a/src/vs/platform/quickinput/browser/quickInputController.ts +++ b/src/vs/platform/quickinput/browser/quickInputController.ts @@ -37,8 +37,6 @@ import { TriStateCheckbox, createToggleActionViewItemProvider } from '../../../b import { defaultCheckboxStyles } from '../../theme/browser/defaultStyles.js'; import { QuickInputTreeController } from './tree/quickInputTreeController.js'; import { QuickTree } from './tree/quickTree.js'; -import { AnchorAlignment, AnchorPosition, layout2d } from '../../../base/common/layout.js'; -import { getAnchorRect } from '../../../base/browser/ui/contextview/contextview.js'; const $ = dom.$; @@ -537,7 +535,6 @@ export class QuickInputController extends Disposable { input.quickNavigate = options.quickNavigate; input.hideInput = !!options.hideInput; input.contextKey = options.contextKey; - input.anchor = options.anchor; input.busy = true; Promise.all([picks, options.activeItem]) .then(([items, _activeItem]) => { @@ -707,7 +704,6 @@ export class QuickInputController extends Disposable { ui.container.style.display = ''; this.updateLayout(); - this.dndController?.setEnabled(!controller.anchor); this.dndController?.layoutContainer(); ui.inputBox.setFocus(); this.quickInputTypeContext.set(controller.type); @@ -859,52 +855,16 @@ export class QuickInputController extends Disposable { private updateLayout() { if (this.ui && this.isVisible()) { const style = this.ui.container.style; - let width = Math.min(this.dimension!.width * 0.62 /* golden cut */, QuickInputController.MAX_WIDTH); + const width = Math.min(this.dimension!.width * 0.62 /* golden cut */, QuickInputController.MAX_WIDTH); style.width = width + 'px'; - let listHeight = this.dimension && this.dimension.height * 0.4; - // Position - if (this.controller?.anchor) { - const container = this.layoutService.getContainer(dom.getActiveWindow()).getBoundingClientRect(); - const anchor = getAnchorRect(this.controller.anchor); - width = 380; - listHeight = this.dimension ? Math.min(this.dimension.height * 0.2, 200) : 200; - - // Beware: - // We need to add some extra pixels to the height to account for the input and padding. - const containerHeight = Math.floor(listHeight) + 6 + 26 + 16; - const { top, left, right, bottom, anchorAlignment, anchorPosition } = layout2d(container, { width, height: containerHeight }, anchor); - - if (anchorAlignment === AnchorAlignment.RIGHT) { - style.right = `${right}px`; - style.left = 'initial'; - } else { - style.left = `${left}px`; - style.right = 'initial'; - } - - if (anchorPosition === AnchorPosition.BELOW) { - style.bottom = `${bottom}px`; - style.top = 'initial'; - } else { - style.top = `${top}px`; - style.bottom = 'initial'; - } - - style.width = `${width}px`; - style.height = ''; - } else { - style.top = `${this.viewState?.top ? Math.round(this.dimension!.height * this.viewState.top) : this.titleBarOffset}px`; - style.left = `${Math.round((this.dimension!.width * (this.viewState?.left ?? 0.5 /* center */)) - (width / 2))}px`; - style.right = ''; - style.bottom = ''; - style.height = ''; - } + style.top = `${this.viewState?.top ? Math.round(this.dimension!.height * this.viewState.top) : this.titleBarOffset}px`; + style.left = `${Math.round((this.dimension!.width * (this.viewState?.left ?? 0.5 /* center */)) - (width / 2))}px`; this.ui.inputBox.layout(); - this.ui.list.layout(listHeight); - this.ui.tree.layout(listHeight); + this.ui.list.layout(this.dimension && this.dimension.height * 0.4); + this.ui.tree.layout(this.dimension && this.dimension.height * 0.4); } } @@ -999,8 +959,6 @@ export interface IQuickInputControllerHost extends ILayoutService { } class QuickInputDragAndDropController extends Disposable { readonly dndViewState = observableValue<{ top?: number; left?: number; done: boolean } | undefined>(this, undefined); - private _enabled = true; - private readonly _snapThreshold = 20; private readonly _snapLineHorizontalRatio = 0.25; @@ -1036,10 +994,6 @@ class QuickInputDragAndDropController extends Disposable { } layoutContainer(dimension = this._layoutService.activeContainerDimension): void { - if (!this._enabled) { - return; - } - const state = this.dndViewState.get(); const dragAreaRect = this._quickInputContainer.getBoundingClientRect(); if (state?.top && state?.left) { @@ -1051,11 +1005,6 @@ class QuickInputDragAndDropController extends Disposable { } } - setEnabled(enabled: boolean): void { - this._enabled = enabled; - this._quickInputContainer.classList.toggle('no-drag', !enabled); - } - setAlignment(alignment: 'top' | 'center' | { top: number; left: number }, done = true): void { if (alignment === 'top') { this.dndViewState.set({ @@ -1086,10 +1035,6 @@ class QuickInputDragAndDropController extends Disposable { // Double click this._register(dom.addDisposableGenericMouseUpListener(dragArea, (event: MouseEvent) => { - if (!this._enabled) { - return; - } - const originEvent = new StandardMouseEvent(dom.getWindow(dragArea), event); if (originEvent.detail !== 2) { return; @@ -1106,10 +1051,6 @@ class QuickInputDragAndDropController extends Disposable { // Mouse down this._register(dom.addDisposableGenericMouseDownListener(dragArea, (e: MouseEvent) => { - if (!this._enabled) { - return; - } - const activeWindow = dom.getWindow(this._layoutService.activeContainer); const originEvent = new StandardMouseEvent(activeWindow, e); diff --git a/src/vs/platform/quickinput/common/quickInput.ts b/src/vs/platform/quickinput/common/quickInput.ts index 9426be48e2f..9ff9d71fe6c 100644 --- a/src/vs/platform/quickinput/common/quickInput.ts +++ b/src/vs/platform/quickinput/common/quickInput.ts @@ -197,11 +197,6 @@ export interface IPickOptions { */ activeItem?: Promise | T; - /** - * an optional anchor for the picker - */ - anchor?: HTMLElement | { x: number; y: number }; - onKeyMods?: (keyMods: IKeyMods) => void; onDidFocus?: (entry: T) => void; onDidTriggerItemButton?: (context: IQuickPickItemButtonContext) => void; @@ -358,11 +353,6 @@ export interface IQuickInput extends IDisposable { */ ignoreFocusOut: boolean; - /** - * An optional anchor for the quick input. - */ - anchor?: HTMLElement | { x: number; y: number }; - /** * Shows the quick input. */ diff --git a/src/vs/workbench/browser/parts/editor/breadcrumbsControl.ts b/src/vs/workbench/browser/parts/editor/breadcrumbsControl.ts index 094ee8995fa..ba678499fec 100644 --- a/src/vs/workbench/browser/parts/editor/breadcrumbsControl.ts +++ b/src/vs/workbench/browser/parts/editor/breadcrumbsControl.ts @@ -547,7 +547,7 @@ export class BreadcrumbsControl { const pickerArrowSize = 8; let pickerArrowOffset: number; - const data = dom.getDomNodePagePosition(event.node.firstChild as HTMLElement); + const data = dom.getDomNodePagePosition(event.node); const y = data.top + data.height + pickerArrowSize; if (y + maxHeight >= window.innerHeight) { maxHeight = window.innerHeight - y - 30 /* room for shadow and status bar*/; diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts b/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts index 548deb481d5..3e4f7655a1e 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatExecuteActions.ts @@ -491,7 +491,7 @@ export class OpenSessionTargetPickerAction extends Action2 { tooltip: localize('setSessionTarget', "Set Session Target"), category: CHAT_CATEGORY, f1: false, - precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.or(ChatContextKeys.chatSessionIsEmpty, ChatContextKeys.inAgentSessionsWelcome)), + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ContextKeyExpr.or(ChatContextKeys.chatSessionIsEmpty, ChatContextKeys.inAgentSessionsWelcome), ChatContextKeys.currentlyEditingInput.negate(), ChatContextKeys.currentlyEditing.negate()), menu: [ { id: MenuId.ChatInput, @@ -526,7 +526,7 @@ export class OpenDelegationPickerAction extends Action2 { tooltip: localize('delegateSession', "Delegate Session"), category: CHAT_CATEGORY, f1: false, - precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.chatSessionIsEmpty.negate()), + precondition: ContextKeyExpr.and(ChatContextKeys.enabled, ChatContextKeys.chatSessionIsEmpty.negate(), ChatContextKeys.currentlyEditingInput.negate(), ChatContextKeys.currentlyEditing.negate()), menu: [ { id: MenuId.ChatInput, diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts index f22d0690712..3af559ab6c8 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsActions.ts @@ -155,7 +155,7 @@ export class PickAgentSessionAction extends Action2 { async run(accessor: ServicesAccessor): Promise { const instantiationService = accessor.get(IInstantiationService); - const agentSessionsPicker = instantiationService.createInstance(AgentSessionsPicker, undefined); + const agentSessionsPicker = instantiationService.createInstance(AgentSessionsPicker); await agentSessionsPicker.pickAgentSession(); } } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsPicker.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsPicker.ts index 7700808a868..2550c4b0184 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsPicker.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessionsPicker.ts @@ -67,7 +67,6 @@ export class AgentSessionsPicker { private readonly sorter = new AgentSessionsSorter(); constructor( - private readonly anchor: HTMLElement | undefined, @IAgentSessionsService private readonly agentSessionsService: IAgentSessionsService, @IQuickInputService private readonly quickInputService: IQuickInputService, @IInstantiationService private readonly instantiationService: IInstantiationService, @@ -78,7 +77,6 @@ export class AgentSessionsPicker { const disposables = new DisposableStore(); const picker = disposables.add(this.quickInputService.createQuickPick({ useSeparators: true })); - picker.anchor = this.anchor; picker.items = this.createPickerItems(); picker.canAcceptInBackground = true; picker.placeholder = localize('chatAgentPickerPlaceholder', "Search agent sessions by name"); diff --git a/src/vs/workbench/contrib/chat/browser/chat.contribution.ts b/src/vs/workbench/contrib/chat/browser/chat.contribution.ts index f1ca19dc37d..d211a1d0929 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.contribution.ts @@ -320,7 +320,7 @@ configurationRegistry.registerConfiguration({ name: 'ChatToolsAutoApprove', category: PolicyCategory.InteractiveSession, minimumVersion: '1.99', - value: (account) => account.policyData?.chat_preview_features_enabled === false ? false : undefined, + value: (policyData) => policyData.chat_preview_features_enabled === false ? false : undefined, localization: { description: { key: 'autoApprove2.description', @@ -473,11 +473,11 @@ configurationRegistry.registerConfiguration({ name: 'ChatMCP', category: PolicyCategory.InteractiveSession, minimumVersion: '1.99', - value: (account) => { - if (account.policyData?.mcp === false) { + value: (policyData) => { + if (policyData.mcp === false) { return McpAccessValue.None; } - if (account.policyData?.mcpAccess === 'registry_only') { + if (policyData.mcpAccess === 'registry_only') { return McpAccessValue.Registry; } return undefined; @@ -588,7 +588,7 @@ configurationRegistry.registerConfiguration({ name: 'ChatAgentMode', category: PolicyCategory.InteractiveSession, minimumVersion: '1.99', - value: (account) => account.policyData?.chat_agent_enabled === false ? false : undefined, + value: (policyData) => policyData.chat_agent_enabled === false ? false : undefined, localization: { description: { key: 'chat.agent.enabled.description', @@ -665,7 +665,7 @@ configurationRegistry.registerConfiguration({ name: 'McpGalleryServiceUrl', category: PolicyCategory.InteractiveSession, minimumVersion: '1.101', - value: (account) => account.policyData?.mcpRegistryUrl, + value: (policyData) => policyData.mcpRegistryUrl, localization: { description: { key: 'mcp.gallery.serviceUrl', diff --git a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatus.ts b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatus.ts index ef3e5989e8c..ad964b4534d 100644 --- a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatus.ts +++ b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatus.ts @@ -4,24 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { ChatEntitlement, IChatEntitlementService } from '../../../../services/chat/common/chatEntitlementService.js'; -import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; -import product from '../../../../../platform/product/common/product.js'; -import { isObject } from '../../../../../base/common/types.js'; export function isNewUser(chatEntitlementService: IChatEntitlementService): boolean { return !chatEntitlementService.sentiment.installed || // chat not installed chatEntitlementService.entitlement === ChatEntitlement.Available; // not yet signed up to chat } - -export function isCompletionsEnabled(configurationService: IConfigurationService, modeId: string = '*'): boolean { - const result = configurationService.getValue>(product.defaultChatAgent.completionsEnablementSetting); - if (!isObject(result)) { - return false; - } - - if (typeof result[modeId] !== 'undefined') { - return Boolean(result[modeId]); // go with setting if explicitly defined - } - - return Boolean(result['*']); // fallback to global setting otherwise -} diff --git a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusDashboard.ts b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusDashboard.ts index 7d94ce384e4..7ddbb06cc8c 100644 --- a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusDashboard.ts +++ b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusDashboard.ts @@ -40,13 +40,14 @@ import { EditorResourceAccessor, SideBySideEditor } from '../../../../common/edi import { IChatEntitlementService, ChatEntitlementService, ChatEntitlement, IQuotaSnapshot, getChatPlanName } from '../../../../services/chat/common/chatEntitlementService.js'; import { IEditorService } from '../../../../services/editor/common/editorService.js'; import { IChatSessionsService } from '../../common/chatSessionsService.js'; -import { isNewUser, isCompletionsEnabled } from './chatStatus.js'; +import { isNewUser } from './chatStatus.js'; import { IChatStatusItemService, ChatStatusEntry } from './chatStatusItemService.js'; import product from '../../../../../platform/product/common/product.js'; import { contrastBorder, inputValidationErrorBorder, inputValidationInfoBorder, inputValidationWarningBorder, registerColor, transparent } from '../../../../../platform/theme/common/colorRegistry.js'; import { Color } from '../../../../../base/common/color.js'; import { IViewsService } from '../../../../services/views/common/viewsService.js'; import { ChatViewId } from '../chat.js'; +import { isCompletionsEnabled } from '../../../../../editor/common/services/completionsEnablement.js'; const defaultChat = product.defaultChatAgent; diff --git a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusEntry.ts b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusEntry.ts index f465335f45e..0e1160d71e4 100644 --- a/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusEntry.ts +++ b/src/vs/workbench/contrib/chat/browser/chatStatus/chatStatusEntry.ts @@ -19,8 +19,9 @@ import { IChatSessionsService } from '../../common/chatSessionsService.js'; import { ChatStatusDashboard } from './chatStatusDashboard.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { disposableWindowInterval } from '../../../../../base/browser/dom.js'; -import { isNewUser, isCompletionsEnabled } from './chatStatus.js'; +import { isNewUser } from './chatStatus.js'; import product from '../../../../../platform/product/common/product.js'; +import { isCompletionsEnabled } from '../../../../../editor/common/services/completionsEnablement.js'; export class ChatStatusBarEntry extends Disposable implements IWorkbenchContribution { diff --git a/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts b/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts index 4aa9eea127e..3b1f279ef88 100644 --- a/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts +++ b/src/vs/workbench/contrib/chat/browser/promptSyntax/newPromptFileActions.ts @@ -163,7 +163,7 @@ function getDefaultContentSnippet(promptType: PromptsType, name: string | undefi `name: ${name ?? '${1:agent-name}'}`, `description: \${2:Describe what this custom agent does and when to use it.}`, `argument-hint: \${3:The inputs this agent expects, e.g., "a task to implement" or "a question to answer".}`, - `# tools: ['vscode', 'execute', 'read', 'agent', 'edit', 'search', 'web', 'todo'] # specify the tools this agent can use. if not set, all enabled tools are allowed`, + `# tools: ['vscode', 'execute', 'read', 'agent', 'edit', 'search', 'web', 'todo'] # specify the tools this agent can use. If not set, all enabled tools are allowed.`, `---`, `\${4:Define what this custom agent does, including its behavior, capabilities, and any specific instructions for its operation.}`, ].join('\n'); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatMcpAppModel.ts b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatMcpAppModel.ts index 34fbe127cd9..7541799ba29 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatMcpAppModel.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/toolInvocationParts/chatMcpAppModel.ts @@ -723,7 +723,7 @@ export class ChatMcpAppModel extends Disposable { jsonrpc: '2.0', id, error: { code, message }, - } satisfies MCP.JSONRPCError); + } satisfies MCP.JSONRPCErrorResponse); } private async _sendNotification(message: McpApps.HostNotification): Promise { diff --git a/src/vs/workbench/contrib/chat/browser/widget/media/chat.css b/src/vs/workbench/contrib/chat/browser/widget/media/chat.css index f82ce561de4..6663d5f2a08 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/media/chat.css +++ b/src/vs/workbench/contrib/chat/browser/widget/media/chat.css @@ -771,7 +771,7 @@ have to be updated for changes to the rules above, or to support more deeply nes box-sizing: border-box; cursor: text; background-color: var(--vscode-input-background); - border: 1px solid var(--vscode-chat-requestBorder, var(--vscode-input-border, transparent)); + border: 1px solid var(--vscode-input-border, transparent); border-radius: 4px; padding: 0 6px 6px 6px; /* top padding is inside the editor widget */ diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatContextUsageWidget.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatContextUsageWidget.ts index d50a6efd846..3a336dc2111 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatContextUsageWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatContextUsageWidget.ts @@ -140,46 +140,31 @@ export class ChatContextUsageWidget extends Disposable { const store = new DisposableStore(); this._hoverDisposable.value = store; - const getOrCreateDetails = (): ChatContextUsageDetails => { - if (!this._contextUsageDetails.value) { - this._contextUsageDetails.value = this.instantiationService.createInstance(ChatContextUsageDetails); - } - if (this.currentData) { - this._contextUsageDetails.value.update(this.currentData); + const createDetails = (): ChatContextUsageDetails | undefined => { + if (!this._isVisible.get() || !this.currentData) { + return undefined; } + this._contextUsageDetails.value = this.instantiationService.createInstance(ChatContextUsageDetails); + this._contextUsageDetails.value.update(this.currentData); return this._contextUsageDetails.value; }; - const resolveHoverOptions = (): IDelayedHoverOptions => { - const details = getOrCreateDetails(); - return { - content: details.domNode, - appearance: { showPointer: true, compact: true }, - persistence: { hideOnHover: false }, - trapFocus: true - }; + const hoverOptions: Omit = { + appearance: { showPointer: true, compact: true }, + persistence: { hideOnHover: false }, + trapFocus: true }; - store.add(this.hoverService.setupDelayedHover( - this.domNode, - resolveHoverOptions - )); + store.add(this.hoverService.setupDelayedHover(this.domNode, () => ({ + ...hoverOptions, + content: createDetails()?.domNode ?? '' + }))); - // Helper to show sticky hover with focus const showStickyHover = () => { - if (this.currentData) { - // Force hide any existing hover to ensure we can show our sticky one - this.hoverService.hideHover(true); - - const details = getOrCreateDetails(); + const details = createDetails(); + if (details) { this.hoverService.showInstantHover( - { - content: details.domNode, - target: this.domNode, - appearance: { showPointer: true, compact: true }, - persistence: { hideOnHover: false, sticky: true }, - trapFocus: true, - }, + { ...hoverOptions, content: details.domNode, target: this.domNode, persistence: { hideOnHover: false, sticky: true } }, true ); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewTitleControl.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewTitleControl.ts index 22f6b218a23..8cd698568b8 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewTitleControl.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewTitleControl.ts @@ -59,8 +59,6 @@ export class ChatViewTitleControl extends Disposable { } private registerActions(): void { - const that = this; - this._register(registerAction2(class extends Action2 { constructor() { super({ @@ -78,7 +76,7 @@ export class ChatViewTitleControl extends Disposable { async run(accessor: ServicesAccessor): Promise { const instantiationService = accessor.get(IInstantiationService); - const agentSessionsPicker = instantiationService.createInstance(AgentSessionsPicker, that.titleLabel.value?.element); + const agentSessionsPicker = instantiationService.createInstance(AgentSessionsPicker); await agentSessionsPicker.pickAgentSession(); } })); diff --git a/src/vs/workbench/contrib/chat/common/promptSyntax/chatPromptFilesContribution.ts b/src/vs/workbench/contrib/chat/common/promptSyntax/chatPromptFilesContribution.ts index 8e9d41c3db7..6468c60cdfa 100644 --- a/src/vs/workbench/contrib/chat/common/promptSyntax/chatPromptFilesContribution.ts +++ b/src/vs/workbench/contrib/chat/common/promptSyntax/chatPromptFilesContribution.ts @@ -4,10 +4,10 @@ *--------------------------------------------------------------------------------------------*/ -import { DisposableMap } from '../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableMap } from '../../../../../base/common/lifecycle.js'; import { joinPath, isEqualOrParent } from '../../../../../base/common/resources.js'; import { localize } from '../../../../../nls.js'; -import { ExtensionIdentifier } from '../../../../../platform/extensions/common/extensions.js'; +import { ExtensionIdentifier, IExtensionManifest } from '../../../../../platform/extensions/common/extensions.js'; import { IWorkbenchContribution } from '../../../../common/contributions.js'; import * as extensionsRegistry from '../../../../services/extensions/common/extensionsRegistry.js'; import { IPromptsService, PromptsStorage } from './service/promptsService.js'; @@ -15,6 +15,9 @@ import { PromptsType } from './promptTypes.js'; import { UriComponents } from '../../../../../base/common/uri.js'; import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { SyncDescriptor } from '../../../../../platform/instantiation/common/descriptors.js'; +import { Registry } from '../../../../../platform/registry/common/platform.js'; +import { Extensions, IExtensionFeaturesRegistry, IExtensionFeatureTableRenderer, IRenderedData, IRowData, ITableData } from '../../../../services/extensionManagement/common/extensionFeatures.js'; interface IRawChatFileContribution { readonly path: string; @@ -162,3 +165,80 @@ CommandsRegistry.registerCommand('_listExtensionPromptFiles', async (accessor): return result; }); + +class ChatPromptFilesDataRenderer extends Disposable implements IExtensionFeatureTableRenderer { + readonly type = 'table'; + + constructor(private readonly contributionPoint: ChatContributionPoint) { + super(); + } + + shouldRender(manifest: IExtensionManifest): boolean { + return !!manifest.contributes?.[this.contributionPoint]; + } + + render(manifest: IExtensionManifest): IRenderedData { + const contributions = manifest.contributes?.[this.contributionPoint] ?? []; + if (!contributions.length) { + return { data: { headers: [], rows: [] }, dispose: () => { } }; + } + + const headers = [ + localize('chatFilesName', "Name"), + localize('chatFilesDescription', "Description"), + localize('chatFilesPath', "Path"), + ]; + + const rows: IRowData[][] = contributions.map(d => { + return [ + d.name ?? '-', + d.description ?? '-', + d.path, + ]; + }); + + return { + data: { + headers, + rows + }, + dispose: () => { } + }; + } +} + +Registry.as(Extensions.ExtensionFeaturesRegistry).registerExtensionFeature({ + id: ChatContributionPoint.chatPromptFiles, + label: localize('chatPromptFiles', "Chat Prompt Files"), + access: { + canToggle: false + }, + renderer: new SyncDescriptor(ChatPromptFilesDataRenderer, [ChatContributionPoint.chatPromptFiles]), +}); + +Registry.as(Extensions.ExtensionFeaturesRegistry).registerExtensionFeature({ + id: ChatContributionPoint.chatInstructions, + label: localize('chatInstructions', "Chat Instructions"), + access: { + canToggle: false + }, + renderer: new SyncDescriptor(ChatPromptFilesDataRenderer, [ChatContributionPoint.chatInstructions]), +}); + +Registry.as(Extensions.ExtensionFeaturesRegistry).registerExtensionFeature({ + id: ChatContributionPoint.chatAgents, + label: localize('chatAgents', "Chat Agents"), + access: { + canToggle: false + }, + renderer: new SyncDescriptor(ChatPromptFilesDataRenderer, [ChatContributionPoint.chatAgents]), +}); + +Registry.as(Extensions.ExtensionFeaturesRegistry).registerExtensionFeature({ + id: ChatContributionPoint.chatSkills, + label: localize('chatSkills', "Chat Skills"), + access: { + canToggle: false + }, + renderer: new SyncDescriptor(ChatPromptFilesDataRenderer, [ChatContributionPoint.chatSkills]), +}); diff --git a/src/vs/workbench/contrib/inlineChat/browser/inlineChatAffordance.ts b/src/vs/workbench/contrib/inlineChat/browser/inlineChatAffordance.ts index 58db6c0bd36..5d53da9301b 100644 --- a/src/vs/workbench/contrib/inlineChat/browser/inlineChatAffordance.ts +++ b/src/vs/workbench/contrib/inlineChat/browser/inlineChatAffordance.ts @@ -52,7 +52,7 @@ export class InlineChatAffordance extends Disposable { this._store.add(autorun(r => { const value = debouncedSelection.read(r); - if (!value || value.isEmpty() || !explicitSelection) { + if (!value || value.isEmpty() || !explicitSelection || _editor.getModel()?.getValueInRange(value).match(/^\s+$/)) { selectionData.set(undefined, undefined); return; } diff --git a/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts b/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts index d7e0ed232f7..b71f9791274 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts @@ -133,6 +133,11 @@ export class McpServerRequestHandler extends Disposable { elicitation: opts.elicitationRequestHandler ? { create: {} } : undefined, }, }, + extensions: { + 'io.modelcontextprotocol/ui': { + mimeTypes: ['text/html;profile=mcp-app'] + } + } }, clientInfo: { name: productService.nameLong, @@ -321,22 +326,26 @@ export class McpServerRequestHandler extends Disposable { /** * Handle successful responses */ - private handleResult(response: MCP.JSONRPCResponse): void { - const request = this._pendingRequests.get(response.id); - if (request) { - this._pendingRequests.delete(response.id); - request.promise.complete(response.result); + private handleResult(response: MCP.JSONRPCResultResponse): void { + if (response.id !== undefined) { + const request = this._pendingRequests.get(response.id); + if (request) { + this._pendingRequests.delete(response.id); + request.promise.complete(response.result); + } } } /** * Handle error responses */ - private handleError(response: MCP.JSONRPCError): void { - const request = this._pendingRequests.get(response.id); - if (request) { - this._pendingRequests.delete(response.id); - request.promise.error(new MpcResponseError(response.error.message, response.error.code, response.error.data)); + private handleError(response: MCP.JSONRPCErrorResponse): void { + if (response.id !== undefined) { + const request = this._pendingRequests.get(response.id); + if (request) { + this._pendingRequests.delete(response.id); + request.promise.error(new MpcResponseError(response.error.message, response.error.code, response.error.data)); + } } } @@ -394,7 +403,7 @@ export class McpServerRequestHandler extends Disposable { e = McpError.unknown(e); } - const errorResponse: MCP.JSONRPCError = { + const errorResponse: MCP.JSONRPCErrorResponse = { jsonrpc: MCP.JSONRPC_VERSION, id: request.id, error: { diff --git a/src/vs/workbench/contrib/mcp/common/mcpTaskManager.ts b/src/vs/workbench/contrib/mcp/common/mcpTaskManager.ts index 75dac9f1002..689e457469c 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpTaskManager.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpTaskManager.ts @@ -89,6 +89,7 @@ export class McpTaskManager extends Disposable { status: 'working', createdAt, ttl, + lastUpdatedAt: new Date().toISOString(), pollInterval: 1000, // Suggest 1 second polling interval }; @@ -171,6 +172,8 @@ export class McpTaskManager extends Disposable { } entry.task.status = status; + entry.task.lastUpdatedAt = new Date().toISOString(); + if (statusMessage !== undefined) { entry.task.statusMessage = statusMessage; } diff --git a/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts b/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts index a095b35bb9a..db33783efc6 100644 --- a/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts +++ b/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts @@ -37,14 +37,48 @@ export namespace MCP { export type JSONRPCMessage = | JSONRPCRequest | JSONRPCNotification - | JSONRPCResponse - | JSONRPCError; + | JSONRPCResponse; /** @internal */ export const LATEST_PROTOCOL_VERSION = "2025-11-25"; /** @internal */ export const JSONRPC_VERSION = "2.0"; + /** + * Represents the contents of a `_meta` field, which clients and servers use to attach additional metadata to their interactions. + * + * Certain key names are reserved by MCP for protocol-level metadata; implementations MUST NOT make assumptions about values at these keys. Additionally, specific schema definitions may reserve particular names for purpose-specific metadata, as declared in those definitions. + * + * Valid keys have two segments: + * + * **Prefix:** + * - Optional - if specified, MUST be a series of _labels_ separated by dots (`.`), followed by a slash (`/`). + * - Labels MUST start with a letter and end with a letter or digit. Interior characters may be letters, digits, or hyphens (`-`). + * - Any prefix consisting of zero or more labels, followed by `modelcontextprotocol` or `mcp`, followed by any label, is **reserved** for MCP use. For example: `modelcontextprotocol.io/`, `mcp.dev/`, `api.modelcontextprotocol.org/`, and `tools.mcp.com/` are all reserved. + * + * **Name:** + * - Unless empty, MUST start and end with an alphanumeric character (`[a-z0-9A-Z]`). + * - Interior characters may be alphanumeric, hyphens (`-`), underscores (`_`), or dots (`.`). + * + * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details. + * @category Common Types + */ + export type MetaObject = Record; + + /** + * Extends {@link MetaObject} with additional request-specific fields. All key naming rules from `MetaObject` apply. + * + * @see {@link MetaObject} for key naming rules and reserved prefixes. + * @see [General fields: `_meta`](/specification/draft/basic/index#meta) for more details. + * @category Common Types + */ + export interface RequestMetaObject extends MetaObject { + /** + * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by {@link ProgressNotification | notifications/progress}). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. + */ + progressToken?: ProgressToken; + } + /** * A progress token, used to associate progress notifications with the original request. * @@ -67,30 +101,22 @@ export namespace MCP { export interface TaskAugmentedRequestParams extends RequestParams { /** * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a CreateTaskResult immediately, and the actual result can be - * retrieved later via tasks/result. + * The request will return a {@link CreateTaskResult} immediately, and the actual result can be + * retrieved later via {@link GetTaskPayloadRequest | tasks/result}. * * Task augmentation is subject to capability negotiation - receivers MUST declare support * for task augmentation of specific request types in their capabilities. */ task?: TaskMetadata; } + /** * Common params for any request. * - * @internal + * @category Common Types */ export interface RequestParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken?: ProgressToken; - [key: string]: unknown; - }; + _meta?: RequestMetaObject; } /** @internal */ @@ -101,12 +127,13 @@ export namespace MCP { params?: { [key: string]: any }; } - /** @internal */ + /** + * Common params for any notification. + * + * @category Common Types + */ export interface NotificationParams { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** @internal */ @@ -118,18 +145,17 @@ export namespace MCP { } /** + * Common result fields. + * * @category Common Types */ export interface Result { - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; [key: string]: unknown; } /** - * @category Common Types + * @category Errors */ export interface Error { /** @@ -177,12 +203,30 @@ export namespace MCP { * * @category JSON-RPC */ - export interface JSONRPCResponse { + export interface JSONRPCResultResponse { jsonrpc: typeof JSONRPC_VERSION; id: RequestId; result: Result; } + /** + * A response to a request that indicates an error occurred. + * + * @category JSON-RPC + */ + export interface JSONRPCErrorResponse { + jsonrpc: typeof JSONRPC_VERSION; + id?: RequestId; + error: Error; + } + + /** + * A response to a request, containing either the result or error. + * + * @category JSON-RPC + */ + export type JSONRPCResponse = JSONRPCResultResponse | JSONRPCErrorResponse; + // Standard JSON-RPC error codes export const PARSE_ERROR = -32700; export const INVALID_REQUEST = -32600; @@ -190,28 +234,113 @@ export namespace MCP { export const INVALID_PARAMS = -32602; export const INTERNAL_ERROR = -32603; + /** + * A JSON-RPC error indicating that invalid JSON was received by the server. This error is returned when the server cannot parse the JSON text of a message. + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Invalid JSON + * {@includeCode ./examples/ParseError/invalid-json.json} + * + * @category Errors + */ + export interface ParseError extends Error { + code: typeof PARSE_ERROR; + } + + /** + * A JSON-RPC error indicating that the request is not a valid request object. This error is returned when the message structure does not conform to the JSON-RPC 2.0 specification requirements for a request (e.g., missing required fields like `jsonrpc` or `method`, or using invalid types for these fields). + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @category Errors + */ + export interface InvalidRequestError extends Error { + code: typeof INVALID_REQUEST; + } + + /** + * A JSON-RPC error indicating that the requested method does not exist or is not available. + * + * In MCP, this error is returned when a request is made for a method that requires a capability that has not been declared. This can occur in either direction: + * + * - A server returning this error when the client requests a capability it doesn't support (e.g., requesting completions when the `completions` capability was not advertised) + * - A client returning this error when the server requests a capability it doesn't support (e.g., requesting roots when the client did not declare the `roots` capability) + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Roots not supported + * {@includeCode ./examples/MethodNotFoundError/roots-not-supported.json} + * + * @category Errors + */ + export interface MethodNotFoundError extends Error { + code: typeof METHOD_NOT_FOUND; + } + + /** + * A JSON-RPC error indicating that the method parameters are invalid or malformed. + * + * In MCP, this error is returned in various contexts when request parameters fail validation: + * + * - **Tools**: Unknown tool name or invalid tool arguments + * - **Prompts**: Unknown prompt name or missing required arguments + * - **Pagination**: Invalid or expired cursor values + * - **Logging**: Invalid log level + * - **Tasks**: Invalid or nonexistent task ID, invalid cursor, or attempting to cancel a task already in a terminal status + * - **Elicitation**: Server requests an elicitation mode not declared in client capabilities + * - **Sampling**: Missing tool result or tool results mixed with other content + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Unknown tool + * {@includeCode ./examples/InvalidParamsError/unknown-tool.json} + * + * @example Invalid tool arguments + * {@includeCode ./examples/InvalidParamsError/invalid-tool-arguments.json} + * + * @example Unknown prompt + * {@includeCode ./examples/InvalidParamsError/unknown-prompt.json} + * + * @example Invalid cursor + * {@includeCode ./examples/InvalidParamsError/invalid-cursor.json} + * + * @category Errors + */ + export interface InvalidParamsError extends Error { + code: typeof INVALID_PARAMS; + } + + /** + * A JSON-RPC error indicating that an internal error occurred on the receiver. This error is returned when the receiver encounters an unexpected condition that prevents it from fulfilling the request. + * + * @see {@link https://www.jsonrpc.org/specification#error_object | JSON-RPC 2.0 Error Object} + * + * @example Unexpected error + * {@includeCode ./examples/InternalError/unexpected-error.json} + * + * @category Errors + */ + export interface InternalError extends Error { + code: typeof INTERNAL_ERROR; + } + // Implementation-specific JSON-RPC error codes [-32000, -32099] /** @internal */ export const URL_ELICITATION_REQUIRED = -32042; - /** - * A response to a request that indicates an error occurred. - * - * @category JSON-RPC - */ - export interface JSONRPCError { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - error: Error; - } - /** * An error response that indicates that the server requires the client to provide additional information via an elicitation request. * + * @example Authorization required + * {@includeCode ./examples/URLElicitationRequiredError/authorization-required.json} + * * @internal */ - export interface URLElicitationRequiredError - extends Omit { + export interface URLElicitationRequiredError extends Omit< + JSONRPCErrorResponse, + "error" + > { error: Error & { code: typeof URL_ELICITATION_REQUIRED; data: { @@ -223,7 +352,7 @@ export namespace MCP { /* Empty result */ /** - * A response that indicates success but carries no data. + * A result that indicates success but carries no data. * * @category Common Types */ @@ -233,6 +362,9 @@ export namespace MCP { /** * Parameters for a `notifications/cancelled` notification. * + * @example User-requested cancellation + * {@includeCode ./examples/CancelledNotificationParams/user-requested-cancellation.json} + * * @category `notifications/cancelled` */ export interface CancelledNotificationParams extends NotificationParams { @@ -241,7 +373,7 @@ export namespace MCP { * * This MUST correspond to the ID of a request previously issued in the same direction. * This MUST be provided for cancelling non-task requests. - * This MUST NOT be used for cancelling tasks (use the `tasks/cancel` request instead). + * This MUST NOT be used for cancelling tasks (use the {@link CancelTaskRequest | tasks/cancel} request instead). */ requestId?: RequestId; @@ -260,7 +392,10 @@ export namespace MCP { * * A client MUST NOT attempt to cancel its `initialize` request. * - * For task cancellation, use the `tasks/cancel` request instead of this notification. + * For task cancellation, use the {@link CancelTaskRequest | tasks/cancel} request instead of this notification. + * + * @example User-requested cancellation + * {@includeCode ./examples/CancelledNotification/user-requested-cancellation.json} * * @category `notifications/cancelled` */ @@ -273,6 +408,9 @@ export namespace MCP { /** * Parameters for an `initialize` request. * + * @example Full client capabilities + * {@includeCode ./examples/InitializeRequestParams/full-client-capabilities.json} + * * @category `initialize` */ export interface InitializeRequestParams extends RequestParams { @@ -287,6 +425,9 @@ export namespace MCP { /** * This request is sent from the client to the server when it first connects, asking it to begin initialization. * + * @example Initialize request + * {@includeCode ./examples/InitializeRequest/initialize-request.json} + * * @category `initialize` */ export interface InitializeRequest extends JSONRPCRequest { @@ -295,7 +436,10 @@ export namespace MCP { } /** - * After receiving an initialize request from the client, the server sends this response. + * The result returned by the server for an {@link InitializeRequest | initialize} request. + * + * @example Full server capabilities + * {@includeCode ./examples/InitializeResult/full-server-capabilities.json} * * @category `initialize` */ @@ -315,9 +459,24 @@ export namespace MCP { instructions?: string; } + /** + * A successful response from the server for a {@link InitializeRequest | initialize} request. + * + * @example Initialize result response + * {@includeCode ./examples/InitializeResultResponse/initialize-result-response.json} + * + * @category `initialize` + */ + export interface InitializeResultResponse extends JSONRPCResultResponse { + result: InitializeResult; + } + /** * This notification is sent from the client to the server after initialization has finished. * + * @example Initialized notification + * {@includeCode ./examples/InitializedNotification/initialized-notification.json} + * * @category `notifications/initialized` */ export interface InitializedNotification extends JSONRPCNotification { @@ -337,6 +496,12 @@ export namespace MCP { experimental?: { [key: string]: object }; /** * Present if the client supports listing roots. + * + * @example Roots - minimum baseline support + * {@includeCode ./examples/ClientCapabilities/roots-minimum-baseline-support.json} + * + * @example Roots - list changed notifications + * {@includeCode ./examples/ClientCapabilities/roots-list-changed-notifications.json} */ roots?: { /** @@ -346,20 +511,35 @@ export namespace MCP { }; /** * Present if the client supports sampling from an LLM. + * + * @example Sampling - minimum baseline support + * {@includeCode ./examples/ClientCapabilities/sampling-minimum-baseline-support.json} + * + * @example Sampling - tool use support + * {@includeCode ./examples/ClientCapabilities/sampling-tool-use-support.json} + * + * @example Sampling - context inclusion support (soft-deprecated) + * {@includeCode ./examples/ClientCapabilities/sampling-context-inclusion-support-soft-deprecated.json} */ sampling?: { /** - * Whether the client supports context inclusion via includeContext parameter. + * Whether the client supports context inclusion via `includeContext` parameter. * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). */ context?: object; /** - * Whether the client supports tool use via tools and toolChoice parameters. + * Whether the client supports tool use via `tools` and `toolChoice` parameters. */ tools?: object; }; /** * Present if the client supports elicitation from the server. + * + * @example Elicitation - form and URL mode support + * {@includeCode ./examples/ClientCapabilities/elicitation-form-and-url-mode-support.json} + * + * @example Elicitation - form mode only (implicit) + * {@includeCode ./examples/ClientCapabilities/elicitation-form-only-implicit.json} */ elicitation?: { form?: object; url?: object }; @@ -368,11 +548,11 @@ export namespace MCP { */ tasks?: { /** - * Whether this client supports tasks/list. + * Whether this client supports {@link ListTasksRequest | tasks/list}. */ list?: object; /** - * Whether this client supports tasks/cancel. + * Whether this client supports {@link CancelTaskRequest | tasks/cancel}. */ cancel?: object; /** @@ -384,7 +564,7 @@ export namespace MCP { */ sampling?: { /** - * Whether the client supports task-augmented sampling/createMessage requests. + * Whether the client supports task-augmented `sampling/createMessage` requests. */ createMessage?: object; }; @@ -393,12 +573,21 @@ export namespace MCP { */ elicitation?: { /** - * Whether the client supports task-augmented elicitation/create requests. + * Whether the client supports task-augmented {@link ElicitRequest | elicitation/create} requests. */ create?: object; }; }; }; + /** + * Optional MCP extensions that the client supports. Keys are extension identifiers + * (e.g., "io.modelcontextprotocol/oauth-client-credentials"), and values are + * per-extension settings objects. An empty object indicates support with no settings. + * + * @example Extensions - UI extension with MIME type support + * {@includeCode ./examples/ClientCapabilities/extensions-ui-mime-types.json} + */ + extensions?: { [key: string]: object }; } /** @@ -413,14 +602,26 @@ export namespace MCP { experimental?: { [key: string]: object }; /** * Present if the server supports sending log messages to the client. + * + * @example Logging - minimum baseline support + * {@includeCode ./examples/ServerCapabilities/logging-minimum-baseline-support.json} */ logging?: object; /** * Present if the server supports argument autocompletion suggestions. + * + * @example Completions - minimum baseline support + * {@includeCode ./examples/ServerCapabilities/completions-minimum-baseline-support.json} */ completions?: object; /** * Present if the server offers any prompt templates. + * + * @example Prompts - minimum baseline support + * {@includeCode ./examples/ServerCapabilities/prompts-minimum-baseline-support.json} + * + * @example Prompts - list changed notifications + * {@includeCode ./examples/ServerCapabilities/prompts-list-changed-notifications.json} */ prompts?: { /** @@ -430,6 +631,18 @@ export namespace MCP { }; /** * Present if the server offers any resources to read. + * + * @example Resources - minimum baseline support + * {@includeCode ./examples/ServerCapabilities/resources-minimum-baseline-support.json} + * + * @example Resources - subscription to individual resource updates (only) + * {@includeCode ./examples/ServerCapabilities/resources-subscription-to-individual-resource-updates-only.json} + * + * @example Resources - list changed notifications (only) + * {@includeCode ./examples/ServerCapabilities/resources-list-changed-notifications-only.json} + * + * @example Resources - all notifications + * {@includeCode ./examples/ServerCapabilities/resources-all-notifications.json} */ resources?: { /** @@ -443,6 +656,12 @@ export namespace MCP { }; /** * Present if the server offers any tools to call. + * + * @example Tools - minimum baseline support + * {@includeCode ./examples/ServerCapabilities/tools-minimum-baseline-support.json} + * + * @example Tools - list changed notifications + * {@includeCode ./examples/ServerCapabilities/tools-list-changed-notifications.json} */ tools?: { /** @@ -455,11 +674,11 @@ export namespace MCP { */ tasks?: { /** - * Whether this server supports tasks/list. + * Whether this server supports {@link ListTasksRequest | tasks/list}. */ list?: object; /** - * Whether this server supports tasks/cancel. + * Whether this server supports {@link CancelTaskRequest | tasks/cancel}. */ cancel?: object; /** @@ -471,12 +690,21 @@ export namespace MCP { */ tools?: { /** - * Whether the server supports task-augmented tools/call requests. + * Whether the server supports task-augmented {@link CallToolRequest | tools/call} requests. */ call?: object; }; }; }; + /** + * Optional MCP extensions that the server supports. Keys are extension identifiers + * (e.g., "io.modelcontextprotocol/apps"), and values are per-extension settings + * objects. An empty object indicates support with no settings. + * + * @example Extensions - UI extension support + * {@includeCode ./examples/ServerCapabilities/extensions-ui.json} + */ + extensions?: { [key: string]: object }; } /** @@ -489,7 +717,7 @@ export namespace MCP { * A standard URI pointing to an icon resource. May be an HTTP/HTTPS URL or a * `data:` URI with Base64-encoded image data. * - * Consumers SHOULD takes steps to ensure URLs serving icons are from the + * Consumers SHOULD take steps to ensure URLs serving icons are from the * same domain as the client/server or a trusted domain. * * Consumers SHOULD take appropriate precautions when consuming SVGs as they can contain @@ -514,8 +742,8 @@ export namespace MCP { sizes?: string[]; /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates + * Optional specifier for the theme this icon is designed for. `"light"` indicates + * the icon is designed to be used with a light background, and `"dark"` indicates * the icon is designed to be used with a dark background. * * If not provided, the client should assume the icon can be used with any theme. @@ -558,7 +786,7 @@ export namespace MCP { * Intended for UI and end-user contexts - optimized to be human-readable and easily understood, * even by those unfamiliar with domain-specific terminology. * - * If not provided, the name should be used for display (except for Tool, + * If not provided, the name should be used for display (except for {@link Tool}, * where `annotations.title` should be given precedence over using `name`, * if present). */ @@ -571,6 +799,9 @@ export namespace MCP { * @category `initialize` */ export interface Implementation extends BaseMetadata, Icons { + /** + * The version of this implementation. + */ version: string; /** @@ -594,6 +825,9 @@ export namespace MCP { /** * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. * + * @example Ping request + * {@includeCode ./examples/PingRequest/ping-request.json} + * * @category `ping` */ export interface PingRequest extends JSONRPCRequest { @@ -601,10 +835,25 @@ export namespace MCP { params?: RequestParams; } + /** + * A successful response for a {@link PingRequest | ping} request. + * + * @example Ping result response + * {@includeCode ./examples/PingResultResponse/ping-result-response.json} + * + * @category `ping` + */ + export interface PingResultResponse extends JSONRPCResultResponse { + result: EmptyResult; + } + /* Progress notifications */ /** - * Parameters for a `notifications/progress` notification. + * Parameters for a {@link ProgressNotification | notifications/progress} notification. + * + * @example Progress message + * {@includeCode ./examples/ProgressNotificationParams/progress-message.json} * * @category `notifications/progress` */ @@ -634,6 +883,9 @@ export namespace MCP { /** * An out-of-band notification used to inform the receiver of a progress update for a long-running request. * + * @example Progress message + * {@includeCode ./examples/ProgressNotification/progress-message.json} + * * @category `notifications/progress` */ export interface ProgressNotification extends JSONRPCNotification { @@ -643,9 +895,12 @@ export namespace MCP { /* Pagination */ /** - * Common parameters for paginated requests. + * Common params for paginated requests. * - * @internal + * @example List request with cursor + * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json} + * + * @category Common Types */ export interface PaginatedRequestParams extends RequestParams { /** @@ -673,6 +928,9 @@ export namespace MCP { /** * Sent from the client to request a list of resources the server has. * + * @example List resources request + * {@includeCode ./examples/ListResourcesRequest/list-resources-request.json} + * * @category `resources/list` */ export interface ListResourcesRequest extends PaginatedRequest { @@ -680,7 +938,10 @@ export namespace MCP { } /** - * The server's response to a resources/list request from the client. + * The result returned by the server for a {@link ListResourcesRequest | resources/list} request. + * + * @example Resources list with cursor + * {@includeCode ./examples/ListResourcesResult/resources-list-with-cursor.json} * * @category `resources/list` */ @@ -688,9 +949,24 @@ export namespace MCP { resources: Resource[]; } + /** + * A successful response from the server for a {@link ListResourcesRequest | resources/list} request. + * + * @example List resources result response + * {@includeCode ./examples/ListResourcesResultResponse/list-resources-result-response.json} + * + * @category `resources/list` + */ + export interface ListResourcesResultResponse extends JSONRPCResultResponse { + result: ListResourcesResult; + } + /** * Sent from the client to request a list of resource templates the server has. * + * @example List resource templates request + * {@includeCode ./examples/ListResourceTemplatesRequest/list-resource-templates-request.json} + * * @category `resources/templates/list` */ export interface ListResourceTemplatesRequest extends PaginatedRequest { @@ -698,7 +974,10 @@ export namespace MCP { } /** - * The server's response to a resources/templates/list request from the client. + * The result returned by the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request. + * + * @example Resource templates list + * {@includeCode ./examples/ListResourceTemplatesResult/resource-templates-list.json} * * @category `resources/templates/list` */ @@ -707,7 +986,19 @@ export namespace MCP { } /** - * Common parameters when working with resources. + * A successful response from the server for a {@link ListResourceTemplatesRequest | resources/templates/list} request. + * + * @example List resource templates result response + * {@includeCode ./examples/ListResourceTemplatesResultResponse/list-resource-templates-result-response.json} + * + * @category `resources/templates/list` + */ + export interface ListResourceTemplatesResultResponse extends JSONRPCResultResponse { + result: ListResourceTemplatesResult; + } + + /** + * Common params for resource-related requests. * * @internal */ @@ -730,6 +1021,9 @@ export namespace MCP { /** * Sent from the client to the server, to read a specific resource URI. * + * @example Read resource request + * {@includeCode ./examples/ReadResourceRequest/read-resource-request.json} + * * @category `resources/read` */ export interface ReadResourceRequest extends JSONRPCRequest { @@ -738,7 +1032,10 @@ export namespace MCP { } /** - * The server's response to a resources/read request from the client. + * The result returned by the server for a {@link ReadResourceRequest | resources/read} request. + * + * @example File resource contents + * {@includeCode ./examples/ReadResourceResult/file-resource-contents.json} * * @category `resources/read` */ @@ -746,9 +1043,24 @@ export namespace MCP { contents: (TextResourceContents | BlobResourceContents)[]; } + /** + * A successful response from the server for a {@link ReadResourceRequest | resources/read} request. + * + * @example Read resource result response + * {@includeCode ./examples/ReadResourceResultResponse/read-resource-result-response.json} + * + * @category `resources/read` + */ + export interface ReadResourceResultResponse extends JSONRPCResultResponse { + result: ReadResourceResult; + } + /** * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. * + * @example Resources list changed + * {@includeCode ./examples/ResourceListChangedNotification/resources-list-changed.json} + * * @category `notifications/resources/list_changed` */ export interface ResourceListChangedNotification extends JSONRPCNotification { @@ -759,12 +1071,18 @@ export namespace MCP { /** * Parameters for a `resources/subscribe` request. * + * @example Subscribe to file resource + * {@includeCode ./examples/SubscribeRequestParams/subscribe-to-file-resource.json} + * * @category `resources/subscribe` */ export interface SubscribeRequestParams extends ResourceRequestParams { } /** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. + * Sent from the client to request {@link ResourceUpdatedNotification | resources/updated} notifications from the server whenever a particular resource changes. + * + * @example Subscribe request + * {@includeCode ./examples/SubscribeRequest/subscribe-request.json} * * @category `resources/subscribe` */ @@ -773,6 +1091,18 @@ export namespace MCP { params: SubscribeRequestParams; } + /** + * A successful response from the server for a {@link SubscribeRequest | resources/subscribe} request. + * + * @example Subscribe result response + * {@includeCode ./examples/SubscribeResultResponse/subscribe-result-response.json} + * + * @category `resources/subscribe` + */ + export interface SubscribeResultResponse extends JSONRPCResultResponse { + result: EmptyResult; + } + /** * Parameters for a `resources/unsubscribe` request. * @@ -781,7 +1111,10 @@ export namespace MCP { export interface UnsubscribeRequestParams extends ResourceRequestParams { } /** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. + * Sent from the client to request cancellation of {@link ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@link SubscribeRequest | resources/subscribe} request. + * + * @example Unsubscribe request + * {@includeCode ./examples/UnsubscribeRequest/unsubscribe-request.json} * * @category `resources/unsubscribe` */ @@ -790,9 +1123,24 @@ export namespace MCP { params: UnsubscribeRequestParams; } + /** + * A successful response from the server for a {@link UnsubscribeRequest | resources/unsubscribe} request. + * + * @example Unsubscribe result response + * {@includeCode ./examples/UnsubscribeResultResponse/unsubscribe-result-response.json} + * + * @category `resources/unsubscribe` + */ + export interface UnsubscribeResultResponse extends JSONRPCResultResponse { + result: EmptyResult; + } + /** * Parameters for a `notifications/resources/updated` notification. * + * @example File resource updated + * {@includeCode ./examples/ResourceUpdatedNotificationParams/file-resource-updated.json} + * * @category `notifications/resources/updated` */ export interface ResourceUpdatedNotificationParams extends NotificationParams { @@ -805,7 +1153,10 @@ export namespace MCP { } /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@link SubscribeRequest | resources/subscribe} request. + * + * @example File resource updated notification + * {@includeCode ./examples/ResourceUpdatedNotification/file-resource-updated-notification.json} * * @category `notifications/resources/updated` */ @@ -817,6 +1168,9 @@ export namespace MCP { /** * A known resource that the server is capable of reading. * + * @example File resource with annotations + * {@includeCode ./examples/Resource/file-resource-with-annotations.json} + * * @category `resources/list` */ export interface Resource extends BaseMetadata, Icons { @@ -851,10 +1205,7 @@ export namespace MCP { */ size?: number; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** @@ -887,10 +1238,7 @@ export namespace MCP { */ annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** @@ -910,13 +1258,13 @@ export namespace MCP { */ mimeType?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** + * @example Text file contents + * {@includeCode ./examples/TextResourceContents/text-file-contents.json} + * * @category Content */ export interface TextResourceContents extends ResourceContents { @@ -927,6 +1275,9 @@ export namespace MCP { } /** + * @example Image file contents + * {@includeCode ./examples/BlobResourceContents/image-file-contents.json} + * * @category Content */ export interface BlobResourceContents extends ResourceContents { @@ -942,6 +1293,9 @@ export namespace MCP { /** * Sent from the client to request a list of prompts and prompt templates the server has. * + * @example List prompts request + * {@includeCode ./examples/ListPromptsRequest/list-prompts-request.json} + * * @category `prompts/list` */ export interface ListPromptsRequest extends PaginatedRequest { @@ -949,7 +1303,10 @@ export namespace MCP { } /** - * The server's response to a prompts/list request from the client. + * The result returned by the server for a {@link ListPromptsRequest | prompts/list} request. + * + * @example Prompts list with cursor + * {@includeCode ./examples/ListPromptsResult/prompts-list-with-cursor.json} * * @category `prompts/list` */ @@ -957,9 +1314,24 @@ export namespace MCP { prompts: Prompt[]; } + /** + * A successful response from the server for a {@link ListPromptsRequest | prompts/list} request. + * + * @example List prompts result response + * {@includeCode ./examples/ListPromptsResultResponse/list-prompts-result-response.json} + * + * @category `prompts/list` + */ + export interface ListPromptsResultResponse extends JSONRPCResultResponse { + result: ListPromptsResult; + } + /** * Parameters for a `prompts/get` request. * + * @example Get code review prompt + * {@includeCode ./examples/GetPromptRequestParams/get-code-review-prompt.json} + * * @category `prompts/get` */ export interface GetPromptRequestParams extends RequestParams { @@ -976,6 +1348,9 @@ export namespace MCP { /** * Used by the client to get a prompt provided by the server. * + * @example Get prompt request + * {@includeCode ./examples/GetPromptRequest/get-prompt-request.json} + * * @category `prompts/get` */ export interface GetPromptRequest extends JSONRPCRequest { @@ -984,7 +1359,10 @@ export namespace MCP { } /** - * The server's response to a prompts/get request from the client. + * The result returned by the server for a {@link GetPromptRequest | prompts/get} request. + * + * @example Code review prompt + * {@includeCode ./examples/GetPromptResult/code-review-prompt.json} * * @category `prompts/get` */ @@ -996,6 +1374,18 @@ export namespace MCP { messages: PromptMessage[]; } + /** + * A successful response from the server for a {@link GetPromptRequest | prompts/get} request. + * + * @example Get prompt result response + * {@includeCode ./examples/GetPromptResultResponse/get-prompt-result-response.json} + * + * @category `prompts/get` + */ + export interface GetPromptResultResponse extends JSONRPCResultResponse { + result: GetPromptResult; + } + /** * A prompt or prompt template that the server offers. * @@ -1012,10 +1402,7 @@ export namespace MCP { */ arguments?: PromptArgument[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** @@ -1044,7 +1431,7 @@ export namespace MCP { /** * Describes a message returned as part of a prompt. * - * This is similar to `SamplingMessage`, but also supports the embedding of + * This is similar to {@link SamplingMessage}, but also supports the embedding of * resources from the MCP server. * * @category `prompts/get` @@ -1057,7 +1444,10 @@ export namespace MCP { /** * A resource that the server is capable of reading, included in a prompt or tool call result. * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * Note: resource links returned by tools are not guaranteed to appear in the results of {@link ListResourcesRequest | resources/list} requests. + * + * @example File resource link + * {@includeCode ./examples/ResourceLink/file-resource-link.json} * * @category Content */ @@ -1071,6 +1461,9 @@ export namespace MCP { * It is up to the client how best to render embedded resources for the benefit * of the LLM and/or the user. * + * @example Embedded file resource with annotations + * {@includeCode ./examples/EmbeddedResource/embedded-file-resource-with-annotations.json} + * * @category Content */ export interface EmbeddedResource { @@ -1082,14 +1475,14 @@ export namespace MCP { */ annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. * + * @example Prompts list changed + * {@includeCode ./examples/PromptListChangedNotification/prompts-list-changed.json} + * * @category `notifications/prompts/list_changed` */ export interface PromptListChangedNotification extends JSONRPCNotification { @@ -1101,6 +1494,9 @@ export namespace MCP { /** * Sent from the client to request a list of tools the server has. * + * @example List tools request + * {@includeCode ./examples/ListToolsRequest/list-tools-request.json} + * * @category `tools/list` */ export interface ListToolsRequest extends PaginatedRequest { @@ -1108,7 +1504,10 @@ export namespace MCP { } /** - * The server's response to a tools/list request from the client. + * The result returned by the server for a {@link ListToolsRequest | tools/list} request. + * + * @example Tools list with cursor + * {@includeCode ./examples/ListToolsResult/tools-list-with-cursor.json} * * @category `tools/list` */ @@ -1117,7 +1516,28 @@ export namespace MCP { } /** - * The server's response to a tool call. + * A successful response from the server for a {@link ListToolsRequest | tools/list} request. + * + * @example List tools result response + * {@includeCode ./examples/ListToolsResultResponse/list-tools-result-response.json} + * + * @category `tools/list` + */ + export interface ListToolsResultResponse extends JSONRPCResultResponse { + result: ListToolsResult; + } + + /** + * The result returned by the server for a {@link CallToolRequest | tools/call} request. + * + * @example Result with unstructured text + * {@includeCode ./examples/CallToolResult/result-with-unstructured-text.json} + * + * @example Result with structured content + * {@includeCode ./examples/CallToolResult/result-with-structured-content.json} + * + * @example Invalid tool input error + * {@includeCode ./examples/CallToolResult/invalid-tool-input-error.json} * * @category `tools/call` */ @@ -1149,9 +1569,27 @@ export namespace MCP { isError?: boolean; } + /** + * A successful response from the server for a {@link CallToolRequest | tools/call} request. + * + * @example Call tool result response + * {@includeCode ./examples/CallToolResultResponse/call-tool-result-response.json} + * + * @category `tools/call` + */ + export interface CallToolResultResponse extends JSONRPCResultResponse { + result: CallToolResult; + } + /** * Parameters for a `tools/call` request. * + * @example `get_weather` tool call params + * {@includeCode ./examples/CallToolRequestParams/get-weather-tool-call-params.json} + * + * @example Tool call params with progress token + * {@includeCode ./examples/CallToolRequestParams/tool-call-params-with-progress-token.json} + * * @category `tools/call` */ export interface CallToolRequestParams extends TaskAugmentedRequestParams { @@ -1168,6 +1606,9 @@ export namespace MCP { /** * Used by the client to invoke a tool provided by the server. * + * @example Call tool request + * {@includeCode ./examples/CallToolRequest/call-tool-request.json} + * * @category `tools/call` */ export interface CallToolRequest extends JSONRPCRequest { @@ -1178,6 +1619,9 @@ export namespace MCP { /** * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. * + * @example Tools list changed + * {@includeCode ./examples/ToolListChangedNotification/tools-list-changed.json} + * * @category `notifications/tools/list_changed` */ export interface ToolListChangedNotification extends JSONRPCNotification { @@ -1186,13 +1630,13 @@ export namespace MCP { } /** - * Additional properties describing a Tool to clients. + * Additional properties describing a {@link Tool} to clients. * - * NOTE: all properties in ToolAnnotations are **hints**. + * NOTE: all properties in `ToolAnnotations` are **hints**. * They are not guaranteed to provide a faithful description of * tool behavior (including descriptive properties like `title`). * - * Clients should never make tool use decisions based on ToolAnnotations + * Clients should never make tool use decisions based on `ToolAnnotations` * received from untrusted servers. * * @category `tools/list` @@ -1252,11 +1696,11 @@ export namespace MCP { * This allows clients to handle long-running operations through polling * the task system. * - * - "forbidden": Tool does not support task-augmented execution (default when absent) - * - "optional": Tool may support task-augmented execution - * - "required": Tool requires task-augmented execution + * - `"forbidden"`: Tool does not support task-augmented execution (default when absent) + * - `"optional"`: Tool may support task-augmented execution + * - `"required"`: Tool requires task-augmented execution * - * Default: "forbidden" + * Default: `"forbidden"` */ taskSupport?: "forbidden" | "optional" | "required"; } @@ -1264,6 +1708,18 @@ export namespace MCP { /** * Definition for a tool the client can call. * + * @example With default 2020-12 input schema + * {@includeCode ./examples/Tool/with-default-2020-12-input-schema.json} + * + * @example With explicit draft-07 input schema + * {@includeCode ./examples/Tool/with-explicit-draft-07-input-schema.json} + * + * @example With no parameters + * {@includeCode ./examples/Tool/with-no-parameters.json} + * + * @example With output schema for structured content + * {@includeCode ./examples/Tool/with-output-schema-for-structured-content.json} + * * @category `tools/list` */ export interface Tool extends BaseMetadata, Icons { @@ -1291,10 +1747,10 @@ export namespace MCP { /** * An optional JSON Schema object defining the structure of the tool's output returned in - * the structuredContent field of a CallToolResult. + * the structuredContent field of a {@link CallToolResult}. * - * Defaults to JSON Schema 2020-12 when no explicit $schema is provided. - * Currently restricted to type: "object" at the root level. + * Defaults to JSON Schema 2020-12 when no explicit `$schema` is provided. + * Currently restricted to `type: "object"` at the root level. */ outputSchema?: { $schema?: string; @@ -1306,14 +1762,11 @@ export namespace MCP { /** * Optional additional tool information. * - * Display name precedence order is: title, annotations.title, then name. + * Display name precedence order is: `title`, `annotations.title`, then `name`. */ annotations?: ToolAnnotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /* Tasks */ @@ -1386,6 +1839,11 @@ export namespace MCP { */ createdAt: string; + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + /** * Actual retention duration from creation in milliseconds, null for unlimited. */ @@ -1398,7 +1856,7 @@ export namespace MCP { } /** - * A response to a task-augmented request. + * The result returned for a task-augmented request. * * @category `tasks` */ @@ -1406,6 +1864,15 @@ export namespace MCP { task: Task; } + /** + * A successful response for a task-augmented request. + * + * @category `tasks` + */ + export interface CreateTaskResultResponse extends JSONRPCResultResponse { + result: CreateTaskResult; + } + /** * A request to retrieve the state of a task. * @@ -1422,12 +1889,21 @@ export namespace MCP { } /** - * The response to a tasks/get request. + * The result returned for a {@link GetTaskRequest | tasks/get} request. * * @category `tasks/get` */ export type GetTaskResult = Result & Task; + /** + * A successful response for a {@link GetTaskRequest | tasks/get} request. + * + * @category `tasks/get` + */ + export interface GetTaskResultResponse extends JSONRPCResultResponse { + result: GetTaskResult; + } + /** * A request to retrieve the result of a completed task. * @@ -1444,9 +1920,9 @@ export namespace MCP { } /** - * The response to a tasks/result request. + * The result returned for a {@link GetTaskPayloadRequest | tasks/result} request. * The structure matches the result type of the original request. - * For example, a tools/call task would return the CallToolResult structure. + * For example, a {@link CallToolRequest | tools/call} task would return the {@link CallToolResult} structure. * * @category `tasks/result` */ @@ -1454,6 +1930,15 @@ export namespace MCP { [key: string]: unknown; } + /** + * A successful response for a {@link GetTaskPayloadRequest | tasks/result} request. + * + * @category `tasks/result` + */ + export interface GetTaskPayloadResultResponse extends JSONRPCResultResponse { + result: GetTaskPayloadResult; + } + /** * A request to cancel a task. * @@ -1470,12 +1955,21 @@ export namespace MCP { } /** - * The response to a tasks/cancel request. + * The result returned for a {@link CancelTaskRequest | tasks/cancel} request. * * @category `tasks/cancel` */ export type CancelTaskResult = Result & Task; + /** + * A successful response for a {@link CancelTaskRequest | tasks/cancel} request. + * + * @category `tasks/cancel` + */ + export interface CancelTaskResultResponse extends JSONRPCResultResponse { + result: CancelTaskResult; + } + /** * A request to retrieve a list of tasks. * @@ -1486,7 +1980,7 @@ export namespace MCP { } /** - * The response to a tasks/list request. + * The result returned for a {@link ListTasksRequest | tasks/list} request. * * @category `tasks/list` */ @@ -1494,6 +1988,15 @@ export namespace MCP { tasks: Task[]; } + /** + * A successful response for a {@link ListTasksRequest | tasks/list} request. + * + * @category `tasks/list` + */ + export interface ListTasksResultResponse extends JSONRPCResultResponse { + result: ListTasksResult; + } + /** * Parameters for a `notifications/tasks/status` notification. * @@ -1516,11 +2019,14 @@ export namespace MCP { /** * Parameters for a `logging/setLevel` request. * + * @example Set log level to "info" + * {@includeCode ./examples/SetLevelRequestParams/set-log-level-to-info.json} + * * @category `logging/setLevel` */ export interface SetLevelRequestParams extends RequestParams { /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/message. + * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as {@link LoggingMessageNotification | notifications/message}. */ level: LoggingLevel; } @@ -1528,6 +2034,9 @@ export namespace MCP { /** * A request from the client to the server, to enable or adjust logging. * + * @example Set logging level request + * {@includeCode ./examples/SetLevelRequest/set-logging-level-request.json} + * * @category `logging/setLevel` */ export interface SetLevelRequest extends JSONRPCRequest { @@ -1535,9 +2044,24 @@ export namespace MCP { params: SetLevelRequestParams; } + /** + * A successful response from the server for a {@link SetLevelRequest | logging/setLevel} request. + * + * @example Set logging level result response + * {@includeCode ./examples/SetLevelResultResponse/set-logging-level-result-response.json} + * + * @category `logging/setLevel` + */ + export interface SetLevelResultResponse extends JSONRPCResultResponse { + result: EmptyResult; + } + /** * Parameters for a `notifications/message` notification. * + * @example Log database connection failed + * {@includeCode ./examples/LoggingMessageNotificationParams/log-database-connection-failed.json} + * * @category `notifications/message` */ export interface LoggingMessageNotificationParams extends NotificationParams { @@ -1556,7 +2080,10 @@ export namespace MCP { } /** - * JSONRPCNotification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. + * JSONRPCNotification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @example Log database connection failed + * {@includeCode ./examples/LoggingMessageNotification/log-database-connection-failed.json} * * @category `notifications/message` */ @@ -1587,6 +2114,15 @@ export namespace MCP { /** * Parameters for a `sampling/createMessage` request. * + * @example Basic request + * {@includeCode ./examples/CreateMessageRequestParams/basic-request.json} + * + * @example Request with tools + * {@includeCode ./examples/CreateMessageRequestParams/request-with-tools.json} + * + * @example Follow-up request with tool results + * {@includeCode ./examples/CreateMessageRequestParams/follow-up-with-tool-results.json} + * * @category `sampling/createMessage` */ export interface CreateMessageRequestParams extends TaskAugmentedRequestParams { @@ -1603,8 +2139,8 @@ export namespace MCP { * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. * The client MAY ignore this request. * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. + * Default is `"none"`. Values `"thisServer"` and `"allServers"` are soft-deprecated. Servers SHOULD only use these values if the client + * declares {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases. */ includeContext?: "none" | "thisServer" | "allServers"; /** @@ -1624,12 +2160,12 @@ export namespace MCP { metadata?: object; /** * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared. */ tools?: Tool[]; /** * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. + * The client MUST return an error if this field is provided but {@link ClientCapabilities.sampling.tools} is not declared. * Default is `{ mode: "auto" }`. */ toolChoice?: ToolChoice; @@ -1643,9 +2179,9 @@ export namespace MCP { export interface ToolChoice { /** * Controls the tool use ability of the model: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools + * - `"auto"`: Model decides whether to use tools (default) + * - `"required"`: Model MUST use at least one tool before completing + * - `"none"`: Model MUST NOT use any tools */ mode?: "auto" | "required" | "none"; } @@ -1653,6 +2189,9 @@ export namespace MCP { /** * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. * + * @example Sampling request + * {@includeCode ./examples/CreateMessageRequest/sampling-request.json} + * * @category `sampling/createMessage` */ export interface CreateMessageRequest extends JSONRPCRequest { @@ -1661,10 +2200,19 @@ export namespace MCP { } /** - * The client's response to a sampling/createMessage request from the server. + * The result returned by the client for a {@link CreateMessageRequest | sampling/createMessage} request. * The client should inform the user before returning the sampled message, to allow them * to inspect the response (human in the loop) and decide whether to allow the server to see it. * + * @example Text response + * {@includeCode ./examples/CreateMessageResult/text-response.json} + * + * @example Tool use response + * {@includeCode ./examples/CreateMessageResult/tool-use-response.json} + * + * @example Final response after tool use + * {@includeCode ./examples/CreateMessageResult/final-response.json} + * * @category `sampling/createMessage` */ export interface CreateMessageResult extends Result, SamplingMessage { @@ -1677,29 +2225,48 @@ export namespace MCP { * The reason why sampling stopped, if known. * * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools + * - `"endTurn"`: Natural end of the assistant's turn + * - `"stopSequence"`: A stop sequence was encountered + * - `"maxTokens"`: Maximum token limit was reached + * - `"toolUse"`: The model wants to use one or more tools * * This field is an open string to allow for provider-specific stop reasons. */ stopReason?: "endTurn" | "stopSequence" | "maxTokens" | "toolUse" | string; } + /** + * A successful response from the client for a {@link CreateMessageRequest | sampling/createMessage} request. + * + * @example Sampling result response + * {@includeCode ./examples/CreateMessageResultResponse/sampling-result-response.json} + * + * @category `sampling/createMessage` + */ + export interface CreateMessageResultResponse extends JSONRPCResultResponse { + result: CreateMessageResult; + } + /** * Describes a message issued to or received from an LLM API. * + * @example Single content block + * {@includeCode ./examples/SamplingMessage/single-content-block.json} + * + * @example Multiple content blocks + * {@includeCode ./examples/SamplingMessage/multiple-content-blocks.json} + * * @category `sampling/createMessage` */ export interface SamplingMessage { role: Role; content: SamplingMessageContentBlock | SamplingMessageContentBlock[]; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } + + /** + * @category `sampling/createMessage` + */ export type SamplingMessageContentBlock = | TextContent | ImageContent @@ -1757,6 +2324,9 @@ export namespace MCP { /** * Text provided to or from an LLM. * + * @example Text content + * {@includeCode ./examples/TextContent/text-content.json} + * * @category Content */ export interface TextContent { @@ -1772,15 +2342,15 @@ export namespace MCP { */ annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * An image provided to or from an LLM. * + * @example `image/png` content with annotations + * {@includeCode ./examples/ImageContent/image-png-content-with-annotations.json} + * * @category Content */ export interface ImageContent { @@ -1803,15 +2373,15 @@ export namespace MCP { */ annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * Audio provided to or from an LLM. * + * @example `audio/wav` content + * {@includeCode ./examples/AudioContent/audio-wav-content.json} + * * @category Content */ export interface AudioContent { @@ -1834,15 +2404,15 @@ export namespace MCP { */ annotations?: Annotations; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * A request from the assistant to call a tool. * + * @example `get_weather` tool use + * {@includeCode ./examples/ToolUseContent/get-weather-tool-use.json} + * * @category `sampling/createMessage` */ export interface ToolUseContent { @@ -1868,15 +2438,16 @@ export namespace MCP { /** * Optional metadata about the tool use. Clients SHOULD preserve this field when * including tool uses in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * The result of a tool use, provided by the user back to the assistant. * + * @example `get_weather` tool result + * {@includeCode ./examples/ToolResultContent/get-weather-tool-result.json} + * * @category `sampling/createMessage` */ export interface ToolResultContent { @@ -1885,14 +2456,14 @@ export namespace MCP { /** * The ID of the tool use this result corresponds to. * - * This MUST match the ID from a previous ToolUseContent. + * This MUST match the ID from a previous {@link ToolUseContent}. */ toolUseId: string; /** * The unstructured result content of the tool use. * - * This has the same format as CallToolResult.content and can include text, images, + * This has the same format as {@link CallToolResult.content} and can include text, images, * audio, resource links, and embedded resources. */ content: ContentBlock[]; @@ -1900,7 +2471,7 @@ export namespace MCP { /** * An optional structured result object. * - * If the tool defined an outputSchema, this SHOULD conform to that schema. + * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema. */ structuredContent?: { [key: string]: unknown }; @@ -1915,10 +2486,8 @@ export namespace MCP { /** * Optional metadata about the tool result. Clients SHOULD preserve this field when * including tool results in subsequent sampling requests to enable caching optimizations. - * - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** @@ -1934,6 +2503,9 @@ export namespace MCP { * up to the client to decide how to interpret these preferences and how to * balance them against other considerations. * + * @example With hints and priorities + * {@includeCode ./examples/ModelPreferences/with-hints-and-priorities.json} + * * @category `sampling/createMessage` */ export interface ModelPreferences { @@ -2010,6 +2582,12 @@ export namespace MCP { * Parameters for a `completion/complete` request. * * @category `completion/complete` + * + * @example Prompt argument completion + * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion.json} + * + * @example Prompt argument completion with context + * {@includeCode ./examples/CompleteRequestParams/prompt-argument-completion-with-context.json} */ export interface CompleteRequestParams extends RequestParams { ref: PromptReference | ResourceTemplateReference; @@ -2041,6 +2619,9 @@ export namespace MCP { /** * A request from the client to the server, to ask for completion options. * + * @example Completion request + * {@includeCode ./examples/CompleteRequest/completion-request.json} + * * @category `completion/complete` */ export interface CompleteRequest extends JSONRPCRequest { @@ -2049,9 +2630,15 @@ export namespace MCP { } /** - * The server's response to a completion/complete request + * The result returned by the server for a {@link CompleteRequest | completion/complete} request. * * @category `completion/complete` + * + * @example Single completion value + * {@includeCode ./examples/CompleteResult/single-completion-value.json} + * + * @example Multiple completion values with more available + * {@includeCode ./examples/CompleteResult/multiple-completion-values-with-more-available.json} */ export interface CompleteResult extends Result { completion: { @@ -2070,6 +2657,18 @@ export namespace MCP { }; } + /** + * A successful response from the server for a {@link CompleteRequest | completion/complete} request. + * + * @example Completion result response + * {@includeCode ./examples/CompleteResultResponse/completion-result-response.json} + * + * @category `completion/complete` + */ + export interface CompleteResultResponse extends JSONRPCResultResponse { + result: CompleteResult; + } + /** * A reference to a resource or resource template definition. * @@ -2104,6 +2703,9 @@ export namespace MCP { * This request is typically used when the server needs to understand the file system * structure or access specific locations that the client has permission to read from. * + * @example List roots request + * {@includeCode ./examples/ListRootsRequest/list-roots-request.json} + * * @category `roots/list` */ export interface ListRootsRequest extends JSONRPCRequest { @@ -2112,24 +2714,45 @@ export namespace MCP { } /** - * The client's response to a roots/list request from the server. - * This result contains an array of Root objects, each representing a root directory + * The result returned by the client for a {@link ListRootsRequest | roots/list} request. + * This result contains an array of {@link Root} objects, each representing a root directory * or file that the server can operate on. * + * @example Single root directory + * {@includeCode ./examples/ListRootsResult/single-root-directory.json} + * + * @example Multiple root directories + * {@includeCode ./examples/ListRootsResult/multiple-root-directories.json} + * * @category `roots/list` */ export interface ListRootsResult extends Result { roots: Root[]; } + /** + * A successful response from the client for a {@link ListRootsRequest | roots/list} request. + * + * @example List roots result response + * {@includeCode ./examples/ListRootsResultResponse/list-roots-result-response.json} + * + * @category `roots/list` + */ + export interface ListRootsResultResponse extends JSONRPCResultResponse { + result: ListRootsResult; + } + /** * Represents a root directory or file that the server can operate on. * + * @example Project directory root + * {@includeCode ./examples/Root/project-directory.json} + * * @category `roots/list` */ export interface Root { /** - * The URI identifying the root. This *must* start with file:// for now. + * The URI identifying the root. This *must* start with `file://` for now. * This restriction may be relaxed in future versions of the protocol to allow * other URI schemes. * @@ -2143,16 +2766,16 @@ export namespace MCP { */ name?: string; - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta?: { [key: string]: unknown }; + _meta?: MetaObject; } /** * A notification from the client to the server, informing it that the list of roots has changed. * This notification should be sent whenever the client adds, removes, or modifies any root. - * The server should then request an updated list of roots using the ListRootsRequest. + * The server should then request an updated list of roots using the {@link ListRootsRequest}. + * + * @example Roots list changed + * {@includeCode ./examples/RootsListChangedNotification/roots-list-changed.json} * * @category `notifications/roots/list_changed` */ @@ -2164,6 +2787,12 @@ export namespace MCP { /** * The parameters for a request to elicit non-sensitive information from the user via a form in the client. * + * @example Elicit single field + * {@includeCode ./examples/ElicitRequestFormParams/elicit-single-field.json} + * + * @example Elicit multiple fields + * {@includeCode ./examples/ElicitRequestFormParams/elicit-multiple-fields.json} + * * @category `elicitation/create` */ export interface ElicitRequestFormParams extends TaskAugmentedRequestParams { @@ -2194,6 +2823,9 @@ export namespace MCP { /** * The parameters for a request to elicit information from the user via a URL in the client. * + * @example Elicit sensitive data + * {@includeCode ./examples/ElicitRequestURLParams/elicit-sensitive-data.json} + * * @category `elicitation/create` */ export interface ElicitRequestURLParams extends TaskAugmentedRequestParams { @@ -2233,6 +2865,9 @@ export namespace MCP { /** * A request from the server to elicit additional information from the user via the client. * + * @example Elicitation request + * {@includeCode ./examples/ElicitRequest/elicitation-request.json} + * * @category `elicitation/create` */ export interface ElicitRequest extends JSONRPCRequest { @@ -2253,6 +2888,9 @@ export namespace MCP { | EnumSchema; /** + * @example Email input schema + * {@includeCode ./examples/StringSchema/email-input-schema.json} + * * @category `elicitation/create` */ export interface StringSchema { @@ -2266,6 +2904,9 @@ export namespace MCP { } /** + * @example Number input schema + * {@includeCode ./examples/NumberSchema/number-input-schema.json} + * * @category `elicitation/create` */ export interface NumberSchema { @@ -2278,6 +2919,9 @@ export namespace MCP { } /** + * @example Boolean input schema + * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json} + * * @category `elicitation/create` */ export interface BooleanSchema { @@ -2290,6 +2934,9 @@ export namespace MCP { /** * Schema for single-selection enumeration without display titles for options. * + * @example Color select schema + * {@includeCode ./examples/UntitledSingleSelectEnumSchema/color-select-schema.json} + * * @category `elicitation/create` */ export interface UntitledSingleSelectEnumSchema { @@ -2315,6 +2962,9 @@ export namespace MCP { /** * Schema for single-selection enumeration with display titles for each option. * + * @example Titled color select schema + * {@includeCode ./examples/TitledSingleSelectEnumSchema/titled-color-select-schema.json} + * * @category `elicitation/create` */ export interface TitledSingleSelectEnumSchema { @@ -2357,6 +3007,9 @@ export namespace MCP { /** * Schema for multiple-selection enumeration without display titles for options. * + * @example Color multi-select schema + * {@includeCode ./examples/UntitledMultiSelectEnumSchema/color-multi-select-schema.json} + * * @category `elicitation/create` */ export interface UntitledMultiSelectEnumSchema { @@ -2396,6 +3049,9 @@ export namespace MCP { /** * Schema for multiple-selection enumeration with display titles for each option. * + * @example Titled color multi-select schema + * {@includeCode ./examples/TitledMultiSelectEnumSchema/titled-color-multi-select-schema.json} + * * @category `elicitation/create` */ export interface TitledMultiSelectEnumSchema { @@ -2449,7 +3105,7 @@ export namespace MCP { | TitledMultiSelectEnumSchema; /** - * Use TitledSingleSelectEnumSchema instead. + * Use {@link TitledSingleSelectEnumSchema} instead. * This interface will be removed in a future version. * * @category `elicitation/create` @@ -2477,30 +3133,54 @@ export namespace MCP { | LegacyTitledEnumSchema; /** - * The client's response to an elicitation request. + * The result returned by the client for an {@link ElicitRequest | elicitation/create} request. + * + * @example Input single field + * {@includeCode ./examples/ElicitResult/input-single-field.json} + * + * @example Input multiple fields + * {@includeCode ./examples/ElicitResult/input-multiple-fields.json} + * + * @example Accept URL mode (no content) + * {@includeCode ./examples/ElicitResult/accept-url-mode-no-content.json} * * @category `elicitation/create` */ export interface ElicitResult extends Result { /** * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice + * - `"accept"`: User submitted the form/confirmed the action + * - `"decline"`: User explicitly declined the action + * - `"cancel"`: User dismissed without making an explicit choice */ action: "accept" | "decline" | "cancel"; /** - * The submitted form data, only present when action is "accept" and mode was "form". + * The submitted form data, only present when action is `"accept"` and mode was `"form"`. * Contains values matching the requested schema. * Omitted for out-of-band mode responses. */ content?: { [key: string]: string | number | boolean | string[] }; } + /** + * A successful response from the client for a {@link ElicitRequest | elicitation/create} request. + * + * @example Elicitation result response + * {@includeCode ./examples/ElicitResultResponse/elicitation-result-response.json} + * + * @category `elicitation/create` + */ + export interface ElicitResultResponse extends JSONRPCResultResponse { + result: ElicitResult; + } + /** * An optional notification from the server to the client, informing it of a completion of a out-of-band elicitation request. * + * @example Elicitation complete + * {@includeCode ./examples/ElicitationCompleteNotification/elicitation-complete.json} + * * @category `notifications/elicitation/complete` */ export interface ElicitationCompleteNotification extends JSONRPCNotification { @@ -2588,6 +3268,7 @@ export namespace MCP { | ListResourcesResult | ReadResourceResult | CallToolResult + | CreateTaskResult | ListToolsResult | GetTaskResult | GetTaskPayloadResult diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts index 3f268d17355..b051bac13ef 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts @@ -220,7 +220,7 @@ suite('Workbench - MCP - ServerRequestHandler', () => { const sentMessages = transport.getSentMessages(); const pingResponse = sentMessages.find(m => 'id' in m && m.id === pingRequest.id && 'result' in m - ) as MCP.JSONRPCResponse; + ) as MCP.JSONRPCResultResponse; assert.ok(pingResponse, 'No ping response was sent'); assert.deepStrictEqual(pingResponse.result, {}); @@ -246,7 +246,7 @@ suite('Workbench - MCP - ServerRequestHandler', () => { const sentMessages = transport.getSentMessages(); const rootsResponse = sentMessages.find(m => 'id' in m && m.id === rootsRequest.id && 'result' in m - ) as MCP.JSONRPCResponse; + ) as MCP.JSONRPCResultResponse; assert.ok(rootsResponse, 'No roots/list response was sent'); assert.strictEqual((rootsResponse.result as MCP.ListRootsResult).roots.length, 2); @@ -400,6 +400,7 @@ suite.skip('Workbench - MCP - McpTask', () => { // TODO@connor4312 https://githu taskId: 'task1', status: 'working', createdAt: new Date().toISOString(), + lastUpdatedAt: new Date().toISOString(), ttl: null, ...overrides }; diff --git a/src/vs/workbench/contrib/welcomeAgentSessions/browser/agentSessionsWelcome.ts b/src/vs/workbench/contrib/welcomeAgentSessions/browser/agentSessionsWelcome.ts index 8779c2596b1..3edf21e7f57 100644 --- a/src/vs/workbench/contrib/welcomeAgentSessions/browser/agentSessionsWelcome.ts +++ b/src/vs/workbench/contrib/welcomeAgentSessions/browser/agentSessionsWelcome.ts @@ -209,6 +209,7 @@ export class AgentSessionsWelcomePage extends EditorPane { clearNode(sessionsSection); this.buildSessionsOrPrompts(sessionsSection); } + this.layoutSessionsControl(); })); this.scrollableElement?.scanDomNode(); diff --git a/src/vs/workbench/contrib/welcomeAgentSessions/browser/media/agentSessionsWelcome.css b/src/vs/workbench/contrib/welcomeAgentSessions/browser/media/agentSessionsWelcome.css index a69ab12ebae..3021512101f 100644 --- a/src/vs/workbench/contrib/welcomeAgentSessions/browser/media/agentSessionsWelcome.css +++ b/src/vs/workbench/contrib/welcomeAgentSessions/browser/media/agentSessionsWelcome.css @@ -163,34 +163,34 @@ /* * Transform items into 2-column layout: - * - Items 0,1 form visual row 1 (top: 0) - * - Items 2,3 form visual row 2 (top: 52) - * - Items 4,5 form visual row 3 (top: 104) - * Left column (even): items stay in place or move up - * Right column (odd): items move right and up + * - Odd items (1, 3, 5, ...) stay in left column + * - Even items (2, 4, 6, ...) move to right column + * Each pair forms a visual row. + * Left column items need to move up by floor((index-1)/2) rows + * Right column items need to move right and up by (index/2) rows + * Row height is 52px. */ -/* Item 1 (index 1): move to right column of row 1 */ -.agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(2) { - transform: translateX(100%) translateY(-52px); -} - -/* Item 2 (index 2): move up to row 2 left column */ +/* Left column items (odd positions): move up to form 2-column layout */ +/* Item 3: move up 1 row */ .agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(3) { transform: translateY(-52px); } - -/* Item 3 (index 3): move to right column of row 2 */ -.agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(4) { - transform: translateX(100%) translateY(-104px); -} - -/* Item 4 (index 4): move up to row 3 left column */ +/* Item 5: move up 2 rows */ .agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(5) { transform: translateY(-104px); } -/* Item 5 (index 5): move to right column of row 3 */ +/* Right column items (even positions): move right and up */ +/* Item 2: move right, up 1 row */ +.agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(2) { + transform: translateX(100%) translateY(-52px); +} +/* Item 4: move right, up 2 rows */ +.agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(4) { + transform: translateX(100%) translateY(-104px); +} +/* Item 6: move right, up 3 rows */ .agentSessionsWelcome-sessionsGrid .monaco-list-row:nth-child(6) { transform: translateX(100%) translateY(-156px); } diff --git a/src/vs/workbench/services/accounts/browser/defaultAccount.ts b/src/vs/workbench/services/accounts/browser/defaultAccount.ts index e45b4e10c3c..f0a645aea45 100644 --- a/src/vs/workbench/services/accounts/browser/defaultAccount.ts +++ b/src/vs/workbench/services/accounts/browser/defaultAccount.ts @@ -111,12 +111,16 @@ export class DefaultAccountService extends Disposable implements IDefaultAccount declare _serviceBrand: undefined; private defaultAccount: IDefaultAccount | null = null; + get policyData(): IPolicyData | null { return this.defaultAccountProvider?.policyData ?? null; } private readonly initBarrier = new Barrier(); private readonly _onDidChangeDefaultAccount = this._register(new Emitter()); readonly onDidChangeDefaultAccount = this._onDidChangeDefaultAccount.event; + private readonly _onDidChangePolicyData = this._register(new Emitter()); + readonly onDidChangePolicyData = this._onDidChangePolicyData.event; + private readonly defaultAccountConfig: IDefaultAccountConfig; private defaultAccountProvider: IDefaultAccountProvider | null = null; @@ -148,11 +152,15 @@ export class DefaultAccountService extends Disposable implements IDefaultAccount } this.defaultAccountProvider = provider; + if (this.defaultAccountProvider.policyData) { + this._onDidChangePolicyData.fire(this.defaultAccountProvider.policyData); + } provider.refresh().then(account => { this.defaultAccount = account; }).finally(() => { this.initBarrier.open(); this._register(provider.onDidChangeDefaultAccount(account => this.setDefaultAccount(account))); + this._register(provider.onDidChangePolicyData(policyData => this._onDidChangePolicyData.fire(policyData))); }); } @@ -178,6 +186,16 @@ export class DefaultAccountService extends Disposable implements IDefaultAccount } } +interface IAccountPolicyData { + readonly accountId: string; + readonly policyData: IPolicyData; +} + +interface IDefaultAccountData { + defaultAccount: IDefaultAccount; + policyData: IAccountPolicyData | null; +} + type DefaultAccountStatusTelemetry = { status: string; initial: boolean; @@ -192,12 +210,18 @@ type DefaultAccountStatusTelemetryClassification = { class DefaultAccountProvider extends Disposable implements IDefaultAccountProvider { - private _defaultAccount: IDefaultAccount | null = null; - get defaultAccount(): IDefaultAccount | null { return this._defaultAccount ?? null; } + private _defaultAccount: IDefaultAccountData | null = null; + get defaultAccount(): IDefaultAccount | null { return this._defaultAccount?.defaultAccount ?? null; } + + private _policyData: IAccountPolicyData | null = null; + get policyData(): IPolicyData | null { return this._policyData?.policyData ?? null; } private readonly _onDidChangeDefaultAccount = this._register(new Emitter()); readonly onDidChangeDefaultAccount = this._onDidChangeDefaultAccount.event; + private readonly _onDidChangePolicyData = this._register(new Emitter()); + readonly onDidChangePolicyData = this._onDidChangePolicyData.event; + private readonly accountStatusContext: IContextKey; private initialized = false; private readonly initPromise: Promise; @@ -220,6 +244,7 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid ) { super(); this.accountStatusContext = CONTEXT_DEFAULT_ACCOUNT_STATE.bindTo(contextKeyService); + this._policyData = this.getCachedPolicyData(); this.initPromise = this.init() .finally(() => { this.telemetryService.publicLog2('defaultaccount:status', { status: this.defaultAccount ? 'available' : 'unavailable', initial: true }); @@ -227,6 +252,22 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid }); } + private getCachedPolicyData(): IAccountPolicyData | null { + const cached = this.storageService.get(CACHED_POLICY_DATA_KEY, StorageScope.APPLICATION); + if (cached) { + try { + const { accountId, policyData } = JSON.parse(cached); + if (accountId && policyData) { + this.logService.debug('[DefaultAccount] Initializing with cached policy data'); + return { accountId, policyData }; + } + } catch (error) { + this.logService.error('[DefaultAccount] Failed to parse cached policy data', getErrorMessage(error)); + } + } + return null; + } + private async init(): Promise { if (isWeb && !this.environmentService.remoteAuthority) { this.logService.debug('[DefaultAccount] Running in web without remote, skipping initialization'); @@ -323,7 +364,7 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid } } - private async fetchDefaultAccount(): Promise { + private async fetchDefaultAccount(): Promise { const defaultAccountProvider = this.getDefaultAccountAuthenticationProvider(); this.logService.debug('[DefaultAccount] Default account provider ID:', defaultAccountProvider.id); @@ -336,24 +377,47 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid return await this.getDefaultAccountForAuthenticationProvider(defaultAccountProvider); } - private setDefaultAccount(account: IDefaultAccount | null): void { + private setDefaultAccount(account: IDefaultAccountData | null): void { if (equals(this._defaultAccount, account)) { return; } this.logService.trace('[DefaultAccount] Updating default account:', account); - this._defaultAccount = account; - this._onDidChangeDefaultAccount.fire(this._defaultAccount); - if (this._defaultAccount) { + if (account) { + this._defaultAccount = account; + this.setPolicyData(account.policyData); + this._onDidChangeDefaultAccount.fire(this._defaultAccount.defaultAccount); this.accountStatusContext.set(DefaultAccountStatus.Available); this.logService.debug('[DefaultAccount] Account status set to Available'); } else { + this._defaultAccount = null; + this.setPolicyData(null); + this._onDidChangeDefaultAccount.fire(null); this.accountDataPollScheduler.cancel(); this.accountStatusContext.set(DefaultAccountStatus.Unavailable); this.logService.debug('[DefaultAccount] Account status set to Unavailable'); } } + private setPolicyData(accountPolicyData: IAccountPolicyData | null): void { + if (equals(this._policyData, accountPolicyData)) { + return; + } + this._policyData = accountPolicyData; + this.cachePolicyData(accountPolicyData); + this._onDidChangePolicyData.fire(this._policyData?.policyData ?? null); + } + + private cachePolicyData(accountPolicyData: IAccountPolicyData | null): void { + if (accountPolicyData) { + this.logService.debug('[DefaultAccount] Caching policy data for account:', accountPolicyData.accountId); + this.storageService.store(CACHED_POLICY_DATA_KEY, JSON.stringify(accountPolicyData), StorageScope.APPLICATION, StorageTarget.MACHINE); + } else { + this.logService.debug('[DefaultAccount] Removing cached policy data'); + this.storageService.remove(CACHED_POLICY_DATA_KEY, StorageScope.APPLICATION); + } + } + private scheduleAccountDataPoll(): void { if (!this._defaultAccount) { return; @@ -373,7 +437,7 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid return result; } - private async getDefaultAccountForAuthenticationProvider(authenticationProvider: IDefaultAccountAuthenticationProvider): Promise { + private async getDefaultAccountForAuthenticationProvider(authenticationProvider: IDefaultAccountAuthenticationProvider): Promise { try { this.logService.debug('[DefaultAccount] Getting Default Account from authenticated sessions for provider:', authenticationProvider.id); const sessions = await this.findMatchingProviderSession(authenticationProvider.id, this.defaultAccountConfig.authenticationProvider.scopes); @@ -390,7 +454,7 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid } } - private async getDefaultAccountFromAuthenticatedSessions(authenticationProvider: IDefaultAccountAuthenticationProvider, sessions: AuthenticationSession[]): Promise { + private async getDefaultAccountFromAuthenticatedSessions(authenticationProvider: IDefaultAccountAuthenticationProvider, sessions: AuthenticationSession[]): Promise { try { const accountId = sessions[0].account.id; const [entitlementsData, tokenEntitlementsData] = await Promise.all([ @@ -398,7 +462,7 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid this.getTokenEntitlements(sessions), ]); - let policyData = this.getCachedPolicyData(accountId); + let policyData: Mutable | undefined = this._policyData?.accountId === accountId ? { ...this._policyData.policyData } : undefined; if (tokenEntitlementsData) { policyData = policyData ?? {}; policyData.chat_agent_enabled = tokenEntitlementsData.chat_agent_enabled; @@ -411,18 +475,16 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid policyData.mcpAccess = mcpRegistryProvider.registry_access; } } - this.cachePolicyData(accountId, policyData); } - const account: IDefaultAccount = { + const defaultAccount: IDefaultAccount = { authenticationProvider, sessionId: sessions[0].id, enterprise: authenticationProvider.enterprise || sessions[0].account.label.includes('_'), entitlementsData, - policyData, }; this.logService.debug('[DefaultAccount] Successfully created default account for provider:', authenticationProvider.id); - return account; + return { defaultAccount, policyData: policyData ? { accountId, policyData } : null }; } catch (error) { this.logService.error('[DefaultAccount] Failed to create default account for provider:', authenticationProvider.id, getErrorMessage(error)); return null; @@ -515,28 +577,6 @@ class DefaultAccountProvider extends Disposable implements IDefaultAccountProvid return undefined; } - private cachePolicyData(accountId: string, policyData: IPolicyData): void { - this.logService.debug('[DefaultAccount] Caching policy data for account:', accountId); - this.storageService.store(CACHED_POLICY_DATA_KEY, JSON.stringify({ accountId, policyData }), StorageScope.APPLICATION, StorageTarget.MACHINE); - } - - private getCachedPolicyData(accountId: string): Mutable | undefined { - const cached = this.storageService.get(CACHED_POLICY_DATA_KEY, StorageScope.APPLICATION); - if (cached) { - try { - const { accountId: cachedAccountId, policyData } = JSON.parse(cached); - if (cachedAccountId === accountId) { - this.logService.debug('[DefaultAccount] Using cached policy data for account:', accountId); - return policyData; - } - this.logService.debug('[DefaultAccount] Cached policy data is for different account, ignoring'); - } catch (error) { - this.logService.error('[DefaultAccount] Failed to parse cached policy data', getErrorMessage(error)); - } - } - return undefined; - } - private async getEntitlements(sessions: AuthenticationSession[]): Promise { const entitlementUrl = this.getEntitlementUrl(); if (!entitlementUrl) { @@ -744,7 +784,6 @@ class DefaultAccountProviderContribution extends Disposable implements IWorkbenc @IProductService productService: IProductService, @IInstantiationService instantiationService: IInstantiationService, @IDefaultAccountService defaultAccountService: IDefaultAccountService, - @ILogService logService: ILogService, ) { super(); const defaultAccountProvider = this._register(instantiationService.createInstance(DefaultAccountProvider, toDefaultAccountConfig(productService.defaultChatAgent))); @@ -752,4 +791,4 @@ class DefaultAccountProviderContribution extends Disposable implements IWorkbenc } } -registerWorkbenchContribution2(DefaultAccountProviderContribution.ID, DefaultAccountProviderContribution, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(DefaultAccountProviderContribution.ID, DefaultAccountProviderContribution, WorkbenchPhase.BlockStartup); diff --git a/src/vs/workbench/services/policies/common/accountPolicyService.ts b/src/vs/workbench/services/policies/common/accountPolicyService.ts index e84e364e7d8..ffd32cb2fa6 100644 --- a/src/vs/workbench/services/policies/common/accountPolicyService.ts +++ b/src/vs/workbench/services/policies/common/accountPolicyService.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ import { IStringDictionary } from '../../../../base/common/collections.js'; -import { IDefaultAccount } from '../../../../base/common/defaultAccount.js'; import { ILogService } from '../../../../platform/log/common/log.js'; import { AbstractPolicyService, IPolicyService, PolicyDefinition } from '../../../../platform/policy/common/policy.js'; import { IDefaultAccountService } from '../../../../platform/defaultAccount/common/defaultAccount.js'; @@ -12,32 +11,26 @@ import { IDefaultAccountService } from '../../../../platform/defaultAccount/comm export class AccountPolicyService extends AbstractPolicyService implements IPolicyService { - private account: IDefaultAccount | null = null; - constructor( @ILogService private readonly logService: ILogService, @IDefaultAccountService private readonly defaultAccountService: IDefaultAccountService ) { super(); - this.defaultAccountService.getDefaultAccount() - .then(account => { - this.account = account; - this._updatePolicyDefinitions(this.policyDefinitions); - this._register(this.defaultAccountService.onDidChangeDefaultAccount(account => { - this.account = account; - this._updatePolicyDefinitions(this.policyDefinitions); - })); - }); + this._updatePolicyDefinitions(this.policyDefinitions); + this._register(this.defaultAccountService.onDidChangePolicyData(() => { + this._updatePolicyDefinitions(this.policyDefinitions); + })); } protected async _updatePolicyDefinitions(policyDefinitions: IStringDictionary): Promise { this.logService.trace(`AccountPolicyService#_updatePolicyDefinitions: Got ${Object.keys(policyDefinitions).length} policy definitions`); const updated: string[] = []; + const policyData = this.defaultAccountService.policyData; for (const key in policyDefinitions) { const policy = policyDefinitions[key]; - const policyValue = this.account && policy.value ? policy.value(this.account) : undefined; + const policyValue = policyData && policy.value ? policy.value(policyData) : undefined; if (policyValue !== undefined) { if (this.policies.get(key) !== policyValue) { this.policies.set(key, policyValue); diff --git a/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts b/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts index 555a62494c0..d157a664c3b 100644 --- a/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts +++ b/src/vs/workbench/services/policies/test/browser/accountPolicyService.test.ts @@ -13,7 +13,7 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { Registry } from '../../../../../platform/registry/common/platform.js'; import { Extensions, IConfigurationNode, IConfigurationRegistry } from '../../../../../platform/configuration/common/configurationRegistry.js'; import { DefaultConfiguration, PolicyConfiguration } from '../../../../../platform/configuration/common/configurations.js'; -import { IDefaultAccount, IDefaultAccountAuthenticationProvider } from '../../../../../base/common/defaultAccount.js'; +import { IDefaultAccount, IDefaultAccountAuthenticationProvider, IPolicyData } from '../../../../../base/common/defaultAccount.js'; import { PolicyCategory } from '../../../../../base/common/policy.js'; import { TestProductService } from '../../../../test/common/workbenchTestServices.js'; @@ -30,9 +30,11 @@ const BASE_DEFAULT_ACCOUNT: IDefaultAccount = { class DefaultAccountProvider implements IDefaultAccountProvider { readonly onDidChangeDefaultAccount = Event.None; + readonly onDidChangePolicyData = Event.None; constructor( readonly defaultAccount: IDefaultAccount, + readonly policyData: IPolicyData = {}, ) { } getDefaultAccountAuthenticationProvider(): IDefaultAccountAuthenticationProvider { @@ -81,7 +83,7 @@ suite('AccountPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? 'policyValueB' : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? 'policyValueB' : undefined, } }, 'setting.C': { @@ -92,7 +94,7 @@ suite('AccountPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? JSON.stringify(['policyValueC1', 'policyValueC2']) : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? JSON.stringify(['policyValueC1', 'policyValueC2']) : undefined, } }, 'setting.D': { @@ -103,7 +105,7 @@ suite('AccountPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? false : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? false : undefined, } }, 'setting.E': { @@ -127,8 +129,8 @@ suite('AccountPolicyService', () => { }); - async function assertDefaultBehavior(defaultAccount: IDefaultAccount) { - defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(defaultAccount)); + async function assertDefaultBehavior(policyData: IPolicyData | undefined) { + defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(BASE_DEFAULT_ACCOUNT, policyData)); await defaultAccountService.refresh(); await policyConfiguration.initialize(); @@ -159,18 +161,16 @@ suite('AccountPolicyService', () => { test('should initialize with default account', async () => { - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT }; - await assertDefaultBehavior(defaultAccount); + await assertDefaultBehavior(undefined); }); test('should initialize with default account and preview features enabled', async () => { - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT, policyData: { chat_preview_features_enabled: true } }; - await assertDefaultBehavior(defaultAccount); + await assertDefaultBehavior({ chat_preview_features_enabled: true }); }); test('should initialize with default account and preview features disabled', async () => { - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT, policyData: { chat_preview_features_enabled: false } }; - defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(defaultAccount)); + const policyData: IPolicyData = { chat_preview_features_enabled: false }; + defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(BASE_DEFAULT_ACCOUNT, policyData)); await defaultAccountService.refresh(); await policyConfiguration.initialize(); diff --git a/src/vs/workbench/services/policies/test/browser/multiplexPolicyService.test.ts b/src/vs/workbench/services/policies/test/browser/multiplexPolicyService.test.ts index 49c631ca49b..2da5b33f162 100644 --- a/src/vs/workbench/services/policies/test/browser/multiplexPolicyService.test.ts +++ b/src/vs/workbench/services/policies/test/browser/multiplexPolicyService.test.ts @@ -20,7 +20,7 @@ import { IFileService } from '../../../../../platform/files/common/files.js'; import { InMemoryFileSystemProvider } from '../../../../../platform/files/common/inMemoryFilesystemProvider.js'; import { FileService } from '../../../../../platform/files/common/fileService.js'; import { VSBuffer } from '../../../../../base/common/buffer.js'; -import { IDefaultAccount, IDefaultAccountAuthenticationProvider } from '../../../../../base/common/defaultAccount.js'; +import { IDefaultAccount, IDefaultAccountAuthenticationProvider, IPolicyData } from '../../../../../base/common/defaultAccount.js'; import { PolicyCategory } from '../../../../../base/common/policy.js'; import { TestProductService } from '../../../../test/common/workbenchTestServices.js'; @@ -37,9 +37,11 @@ const BASE_DEFAULT_ACCOUNT: IDefaultAccount = { class DefaultAccountProvider implements IDefaultAccountProvider { readonly onDidChangeDefaultAccount = Event.None; + readonly onDidChangePolicyData = Event.None; constructor( readonly defaultAccount: IDefaultAccount, + readonly policyData: IPolicyData = {}, ) { } getDefaultAccountAuthenticationProvider(): IDefaultAccountAuthenticationProvider { @@ -90,7 +92,7 @@ suite('MultiplexPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? 'policyValueB' : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? 'policyValueB' : undefined, } }, 'setting.C': { @@ -101,7 +103,7 @@ suite('MultiplexPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? JSON.stringify(['policyValueC1', 'policyValueC2']) : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? JSON.stringify(['policyValueC1', 'policyValueC2']) : undefined, } }, 'setting.D': { @@ -112,7 +114,7 @@ suite('MultiplexPolicyService', () => { category: PolicyCategory.Extensions, minimumVersion: '1.0.0', localization: { description: { key: '', value: '' } }, - value: account => account.policyData?.chat_preview_features_enabled === false ? false : undefined, + value: policyData => policyData.chat_preview_features_enabled === false ? false : undefined, } }, 'setting.E': { @@ -186,8 +188,7 @@ suite('MultiplexPolicyService', () => { test('policy from file only', async () => { await clear(); - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT }; - defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(defaultAccount)); + defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(BASE_DEFAULT_ACCOUNT)); await defaultAccountService.refresh(); await fileService.writeFile(policyFile, @@ -228,8 +229,8 @@ suite('MultiplexPolicyService', () => { test('policy from default account only', async () => { await clear(); - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT, policyData: { chat_preview_features_enabled: false } }; - defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(defaultAccount)); + const policyData: IPolicyData = { chat_preview_features_enabled: false }; + defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(BASE_DEFAULT_ACCOUNT, policyData)); await defaultAccountService.refresh(); await fileService.writeFile(policyFile, @@ -269,8 +270,8 @@ suite('MultiplexPolicyService', () => { test('policy from file and default account', async () => { await clear(); - const defaultAccount = { ...BASE_DEFAULT_ACCOUNT, policyData: { chat_preview_features_enabled: false } }; - defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(defaultAccount)); + const policyData: IPolicyData = { chat_preview_features_enabled: false }; + defaultAccountService.setDefaultAccountProvider(new DefaultAccountProvider(BASE_DEFAULT_ACCOUNT, policyData)); await defaultAccountService.refresh(); await fileService.writeFile(policyFile,