diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 3e7b3c6765f24..8d0d6552d05ec 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -54,7 +54,7 @@ "message": 3 }, "background": { - "beginsPattern": "Starting compilation...", + "beginsPattern": "Starting compilation\\.\\.\\.", "endsPattern": "Finished compilation with" } } diff --git a/extensions/debug-auto-launch/.vscodeignore b/extensions/debug-auto-launch/.vscodeignore index 360fcfd1c990b..1ebf0088b62a4 100644 --- a/extensions/debug-auto-launch/.vscodeignore +++ b/extensions/debug-auto-launch/.vscodeignore @@ -1,5 +1,5 @@ src/** -tsconfig.json +tsconfig*.json out/** extension.webpack.config.js package-lock.json diff --git a/extensions/debug-server-ready/.vscodeignore b/extensions/debug-server-ready/.vscodeignore index 536dd0720a3b9..04b88eb4a4520 100644 --- a/extensions/debug-server-ready/.vscodeignore +++ b/extensions/debug-server-ready/.vscodeignore @@ -1,5 +1,5 @@ src/** -tsconfig.json +tsconfig*.json out/** extension.webpack.config.js package-lock.json diff --git a/extensions/extension-editing/.vscodeignore b/extensions/extension-editing/.vscodeignore index 8d4da76b9cb1d..82f90155181a7 100644 --- a/extensions/extension-editing/.vscodeignore +++ b/extensions/extension-editing/.vscodeignore @@ -1,7 +1,6 @@ test/** src/** -tsconfig.json +tsconfig*.json out/** -extension.webpack.config.js -extension-browser.webpack.config.js +esbuild*.mts package-lock.json diff --git a/extensions/extension-editing/esbuild.browser.mts b/extensions/extension-editing/esbuild.browser.mts new file mode 100644 index 0000000000000..170f3cda31380 --- /dev/null +++ b/extensions/extension-editing/esbuild.browser.mts @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +import * as path from 'node:path'; +import { run } from '../esbuild-extension-common.mts'; + +const srcDir = path.join(import.meta.dirname, 'src'); +const outDir = path.join(import.meta.dirname, 'dist', 'browser'); + +run({ + platform: 'browser', + entryPoints: { + 'extensionEditingBrowserMain': path.join(srcDir, 'extensionEditingBrowserMain.ts'), + }, + srcDir, + outdir: outDir, +}, process.argv); diff --git a/extensions/terminal-suggest/extension.webpack.config.js b/extensions/extension-editing/esbuild.mts similarity index 50% rename from extensions/terminal-suggest/extension.webpack.config.js rename to extensions/extension-editing/esbuild.mts index 8ac2b3abb22d2..5bb9e7ca8f462 100644 --- a/extensions/terminal-suggest/extension.webpack.config.js +++ b/extensions/extension-editing/esbuild.mts @@ -2,19 +2,17 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// @ts-check -import withDefaults from '../shared.webpack.config.mjs'; +import * as path from 'node:path'; +import { run } from '../esbuild-extension-common.mts'; -export default withDefaults({ - context: import.meta.dirname, - entry: { - extension: './src/terminalSuggestMain.ts' - }, - output: { - filename: 'terminalSuggestMain.js' +const srcDir = path.join(import.meta.dirname, 'src'); +const outDir = path.join(import.meta.dirname, 'dist'); + +run({ + platform: 'node', + entryPoints: { + 'extensionEditingMain': path.join(srcDir, 'extensionEditingMain.ts'), }, - resolve: { - mainFields: ['module', 'main'], - extensions: ['.ts', '.js'] // support ts-files and js-files - } -}); + srcDir, + outdir: outDir, +}, process.argv); diff --git a/extensions/extension-editing/tsconfig.browser.json b/extensions/extension-editing/tsconfig.browser.json new file mode 100644 index 0000000000000..797e0a447b14f --- /dev/null +++ b/extensions/extension-editing/tsconfig.browser.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": {}, + "exclude": [ + "./src/test/**" + ], + "files": [ + "./src/extensionEditingBrowserMain.ts" + ] +} diff --git a/extensions/git-base/.vscodeignore b/extensions/git-base/.vscodeignore index aefad98382800..835918d940378 100644 --- a/extensions/git-base/.vscodeignore +++ b/extensions/git-base/.vscodeignore @@ -3,5 +3,5 @@ build/** cgmanifest.json extension.webpack.config.js extension-browser.webpack.config.js -tsconfig.json +tsconfig*.json diff --git a/extensions/git/.vscodeignore b/extensions/git/.vscodeignore index 1e6130d5c7d74..a1fc5df7d26b8 100644 --- a/extensions/git/.vscodeignore +++ b/extensions/git/.vscodeignore @@ -1,7 +1,7 @@ src/** test/** out/** -tsconfig.json +tsconfig*.json build/** extension.webpack.config.js package-lock.json diff --git a/extensions/github-authentication/.vscodeignore b/extensions/github-authentication/.vscodeignore index 0d0ea746e796d..0f1797efe9561 100644 --- a/extensions/github-authentication/.vscodeignore +++ b/extensions/github-authentication/.vscodeignore @@ -5,5 +5,5 @@ out/** build/** extension.webpack.config.js extension-browser.webpack.config.js -tsconfig.json +tsconfig*.json package-lock.json diff --git a/extensions/github/.vscodeignore b/extensions/github/.vscodeignore index 54d237c1f3ec4..77ec048a6daff 100644 --- a/extensions/github/.vscodeignore +++ b/extensions/github/.vscodeignore @@ -3,6 +3,6 @@ src/** out/** build/** extension.webpack.config.js -tsconfig.json +tsconfig*.json package-lock.json testWorkspace/** diff --git a/extensions/html-language-features/.vscodeignore b/extensions/html-language-features/.vscodeignore index b1586b6bc845e..3e57ff5a65730 100644 --- a/extensions/html-language-features/.vscodeignore +++ b/extensions/html-language-features/.vscodeignore @@ -7,8 +7,7 @@ client/src/** server/src/** client/out/** server/out/** -client/tsconfig.json -server/tsconfig.json +**/tsconfig*.json server/test/** server/bin/** server/build/** diff --git a/extensions/ipynb/.vscodeignore b/extensions/ipynb/.vscodeignore index 543420a2de021..8805685e2220b 100644 --- a/extensions/ipynb/.vscodeignore +++ b/extensions/ipynb/.vscodeignore @@ -2,7 +2,7 @@ src/** notebook-src/** out/** -tsconfig.json +tsconfig*.json extension.webpack.config.js extension-browser.webpack.config.js package-lock.json diff --git a/extensions/javascript/.vscodeignore b/extensions/javascript/.vscodeignore index b66f1626fbbd6..488fc2248af70 100644 --- a/extensions/javascript/.vscodeignore +++ b/extensions/javascript/.vscodeignore @@ -1,5 +1,5 @@ test/** src/**/*.ts syntaxes/Readme.md -tsconfig.json +tsconfig*.json cgmanifest.json diff --git a/extensions/json-language-features/.vscodeignore b/extensions/json-language-features/.vscodeignore index 807b3e4cbae53..3da299742b903 100644 --- a/extensions/json-language-features/.vscodeignore +++ b/extensions/json-language-features/.vscodeignore @@ -5,8 +5,7 @@ client/src/** server/src/** client/out/** server/out/** -client/tsconfig.json -server/tsconfig.json +**/tsconfig*.json server/test/** server/bin/** server/build/** diff --git a/extensions/markdown-basics/.vscodeignore b/extensions/markdown-basics/.vscodeignore index 89fb2149dcb97..96ebcbb17323f 100644 --- a/extensions/markdown-basics/.vscodeignore +++ b/extensions/markdown-basics/.vscodeignore @@ -1,4 +1,4 @@ test/** src/** -tsconfig.json +tsconfig*.json cgmanifest.json diff --git a/extensions/microsoft-authentication/.vscodeignore b/extensions/microsoft-authentication/.vscodeignore index e2daf4b8a89ba..3e683c7e56dd4 100644 --- a/extensions/microsoft-authentication/.vscodeignore +++ b/extensions/microsoft-authentication/.vscodeignore @@ -7,7 +7,7 @@ package-lock.json src/** .gitignore vsc-extension-quickstart.md -**/tsconfig.json +**/tsconfig*.json **/tslint.json **/*.map **/*.ts diff --git a/extensions/notebook-renderers/.vscodeignore b/extensions/notebook-renderers/.vscodeignore index d8277ac1813a4..3f07e7128a912 100644 --- a/extensions/notebook-renderers/.vscodeignore +++ b/extensions/notebook-renderers/.vscodeignore @@ -1,6 +1,6 @@ src/** notebook/** -tsconfig.json +tsconfig*.json .gitignore esbuild.* src/** diff --git a/extensions/php-language-features/.vscodeignore b/extensions/php-language-features/.vscodeignore index e326d20ef52f2..4a97d0f9e7c4b 100644 --- a/extensions/php-language-features/.vscodeignore +++ b/extensions/php-language-features/.vscodeignore @@ -1,6 +1,6 @@ .vscode/** src/** out/** -tsconfig.json -extension.webpack.config.js +tsconfig*.json +esbuild*.mts package-lock.json diff --git a/extensions/extension-editing/extension-browser.webpack.config.js b/extensions/php-language-features/esbuild.mts similarity index 52% rename from extensions/extension-editing/extension-browser.webpack.config.js rename to extensions/php-language-features/esbuild.mts index fffaf0ebe0439..ffd0d402c6e67 100644 --- a/extensions/extension-editing/extension-browser.webpack.config.js +++ b/extensions/php-language-features/esbuild.mts @@ -2,16 +2,17 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// @ts-check -import { browser as withBrowserDefaults } from '../shared.webpack.config.mjs'; +import * as path from 'node:path'; +import { run } from '../esbuild-extension-common.mts'; -export default withBrowserDefaults({ - context: import.meta.dirname, - entry: { - extension: './src/extensionEditingBrowserMain.ts' - }, - output: { - filename: 'extensionEditingBrowserMain.js' - } -}); +const srcDir = path.join(import.meta.dirname, 'src'); +const outDir = path.join(import.meta.dirname, 'dist'); +run({ + platform: 'node', + entryPoints: { + 'phpMain': path.join(srcDir, 'phpMain.ts'), + }, + srcDir, + outdir: outDir, +}, process.argv); diff --git a/extensions/php/.vscodeignore b/extensions/php/.vscodeignore index 5da0ed79e4608..b69551f2053c5 100644 --- a/extensions/php/.vscodeignore +++ b/extensions/php/.vscodeignore @@ -2,6 +2,6 @@ test/** build/** out/test/** src/** -tsconfig.json +tsconfig*.json cgmanifest.json -.vscode \ No newline at end of file +.vscode diff --git a/extensions/prompt-basics/.vscodeignore b/extensions/prompt-basics/.vscodeignore index 89fb2149dcb97..96ebcbb17323f 100644 --- a/extensions/prompt-basics/.vscodeignore +++ b/extensions/prompt-basics/.vscodeignore @@ -1,4 +1,4 @@ test/** src/** -tsconfig.json +tsconfig*.json cgmanifest.json diff --git a/extensions/terminal-suggest/.vscodeignore b/extensions/terminal-suggest/.vscodeignore index d9b5dc0447cc9..3965a7d70ba5e 100644 --- a/extensions/terminal-suggest/.vscodeignore +++ b/extensions/terminal-suggest/.vscodeignore @@ -1,9 +1,8 @@ src/** out/** -tsconfig.json +tsconfig*.json .vscode/** -extension.webpack.config.js -extension-browser.webpack.config.js +esbuild*.mts package-lock.json fixtures/** scripts/** diff --git a/extensions/php-language-features/extension.webpack.config.js b/extensions/terminal-suggest/esbuild.mts similarity index 50% rename from extensions/php-language-features/extension.webpack.config.js rename to extensions/terminal-suggest/esbuild.mts index 81e71e442ec5a..a24c30e4fc792 100644 --- a/extensions/php-language-features/extension.webpack.config.js +++ b/extensions/terminal-suggest/esbuild.mts @@ -2,15 +2,17 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// @ts-check -import withDefaults from '../shared.webpack.config.mjs'; +import * as path from 'node:path'; +import { run } from '../esbuild-extension-common.mts'; -export default withDefaults({ - context: import.meta.dirname, - entry: { - extension: './src/phpMain.ts', +const srcDir = path.join(import.meta.dirname, 'src'); +const outDir = path.join(import.meta.dirname, 'dist'); + +run({ + platform: 'node', + entryPoints: { + 'terminalSuggestMain': path.join(srcDir, 'terminalSuggestMain.ts'), }, - output: { - filename: 'phpMain.js' - } -}); + srcDir, + outdir: outDir, +}, process.argv); diff --git a/extensions/theme-2026/themes/2026-dark.json b/extensions/theme-2026/themes/2026-dark.json index 2ef19c0e59d42..7025fb3d65a58 100644 --- a/extensions/theme-2026/themes/2026-dark.json +++ b/extensions/theme-2026/themes/2026-dark.json @@ -252,8 +252,8 @@ "gauge.warningBackground": "#E3B97E4D", "gauge.errorForeground": "#f48771", "gauge.errorBackground": "#F287724D", - "chat.requestBubbleBackground": "#488FAE26", - "chat.requestBubbleHoverBackground": "#488FAE46", + "chat.requestBubbleBackground": "#ffffff13", + "chat.requestBubbleHoverBackground": "#ffffff22", "editorCommentsWidget.rangeBackground": "#488FAE26", "editorCommentsWidget.rangeActiveBackground": "#488FAE46", "charts.foreground": "#CCCCCC", diff --git a/extensions/tunnel-forwarding/.vscodeignore b/extensions/tunnel-forwarding/.vscodeignore index 360fcfd1c990b..0628555db0021 100644 --- a/extensions/tunnel-forwarding/.vscodeignore +++ b/extensions/tunnel-forwarding/.vscodeignore @@ -1,5 +1,5 @@ src/** -tsconfig.json +tsconfig*.json out/** -extension.webpack.config.js +esbuild*.mts package-lock.json diff --git a/extensions/extension-editing/extension.webpack.config.js b/extensions/tunnel-forwarding/esbuild.mts similarity index 51% rename from extensions/extension-editing/extension.webpack.config.js rename to extensions/tunnel-forwarding/esbuild.mts index 1d7ce38597d25..2b75ca703da06 100644 --- a/extensions/extension-editing/extension.webpack.config.js +++ b/extensions/tunnel-forwarding/esbuild.mts @@ -2,18 +2,17 @@ * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -// @ts-check -import withDefaults from '../shared.webpack.config.mjs'; +import * as path from 'node:path'; +import { run } from '../esbuild-extension-common.mts'; -export default withDefaults({ - context: import.meta.dirname, - entry: { - extension: './src/extensionEditingMain.ts', - }, - output: { - filename: 'extensionEditingMain.js' +const srcDir = path.join(import.meta.dirname, 'src'); +const outDir = path.join(import.meta.dirname, 'dist'); + +run({ + platform: 'node', + entryPoints: { + 'extension': path.join(srcDir, 'extension.ts'), }, - externals: { - '../../../product.json': 'commonjs ../../../product.json', - } -}); + srcDir, + outdir: outDir, +}, process.argv); diff --git a/extensions/tunnel-forwarding/extension.webpack.config.js b/extensions/tunnel-forwarding/extension.webpack.config.js deleted file mode 100644 index 0c857b362f5da..0000000000000 --- a/extensions/tunnel-forwarding/extension.webpack.config.js +++ /dev/null @@ -1,16 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ -// @ts-check -import withDefaults from '../shared.webpack.config.mjs'; - -export default withDefaults({ - context: import.meta.dirname, - entry: { - extension: './src/extension.ts', - }, - resolve: { - mainFields: ['module', 'main'] - } -}); diff --git a/extensions/typescript-basics/.vscodeignore b/extensions/typescript-basics/.vscodeignore index 0a0a50bc3e054..e850ef593ee23 100644 --- a/extensions/typescript-basics/.vscodeignore +++ b/extensions/typescript-basics/.vscodeignore @@ -1,6 +1,6 @@ build/** src/** test/** -tsconfig.json +tsconfig*.json cgmanifest.json syntaxes/Readme.md diff --git a/extensions/typescript-language-features/package.json b/extensions/typescript-language-features/package.json index baf20de579dc0..66a1c65819d74 100644 --- a/extensions/typescript-language-features/package.json +++ b/extensions/typescript-language-features/package.json @@ -442,6 +442,26 @@ "markdownDeprecationMessage": "%configuration.suggestionActions.enabled.unifiedDeprecationMessage%", "scope": "resource" }, + "js/ts.updateImportsOnFileMove.enabled": { + "type": "string", + "enum": [ + "prompt", + "always", + "never" + ], + "markdownEnumDescriptions": [ + "%typescript.updateImportsOnFileMove.enabled.prompt%", + "%typescript.updateImportsOnFileMove.enabled.always%", + "%typescript.updateImportsOnFileMove.enabled.never%" + ], + "default": "prompt", + "description": "%typescript.updateImportsOnFileMove.enabled%", + "scope": "resource", + "tags": [ + "JavaScript", + "TypeScript" + ] + }, "typescript.updateImportsOnFileMove.enabled": { "type": "string", "enum": [ @@ -456,6 +476,7 @@ ], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", + "markdownDeprecationMessage": "%configuration.updateImportsOnFileMove.enabled.unifiedDeprecationMessage%", "scope": "resource" }, "javascript.updateImportsOnFileMove.enabled": { @@ -472,20 +493,50 @@ ], "default": "prompt", "description": "%typescript.updateImportsOnFileMove.enabled%", + "markdownDeprecationMessage": "%configuration.updateImportsOnFileMove.enabled.unifiedDeprecationMessage%", "scope": "resource" }, + "js/ts.autoClosingTags.enabled": { + "type": "boolean", + "default": true, + "description": "%typescript.autoClosingTags%", + "scope": "language-overridable", + "tags": [ + "JavaScript", + "TypeScript" + ] + }, "typescript.autoClosingTags": { "type": "boolean", "default": true, "description": "%typescript.autoClosingTags%", + "markdownDeprecationMessage": "%configuration.autoClosingTags.enabled.unifiedDeprecationMessage%", "scope": "language-overridable" }, "javascript.autoClosingTags": { "type": "boolean", "default": true, "description": "%typescript.autoClosingTags%", + "markdownDeprecationMessage": "%configuration.autoClosingTags.enabled.unifiedDeprecationMessage%", "scope": "language-overridable" }, + "js/ts.workspaceSymbols.scope": { + "type": "string", + "enum": [ + "allOpenProjects", + "currentProject" + ], + "enumDescriptions": [ + "%typescript.workspaceSymbols.scope.allOpenProjects%", + "%typescript.workspaceSymbols.scope.currentProject%" + ], + "default": "allOpenProjects", + "markdownDescription": "%typescript.workspaceSymbols.scope%", + "scope": "window", + "tags": [ + "TypeScript" + ] + }, "typescript.workspaceSymbols.scope": { "type": "string", "enum": [ @@ -498,37 +549,72 @@ ], "default": "allOpenProjects", "markdownDescription": "%typescript.workspaceSymbols.scope%", + "markdownDeprecationMessage": "%configuration.workspaceSymbols.scope.unifiedDeprecationMessage%", "scope": "window" }, + "js/ts.preferGoToSourceDefinition": { + "type": "boolean", + "default": false, + "description": "%configuration.preferGoToSourceDefinition%", + "scope": "window", + "tags": [ + "JavaScript", + "TypeScript" + ] + }, "typescript.preferGoToSourceDefinition": { "type": "boolean", "default": false, "description": "%configuration.preferGoToSourceDefinition%", + "markdownDeprecationMessage": "%configuration.preferGoToSourceDefinition.unifiedDeprecationMessage%", "scope": "window" }, "javascript.preferGoToSourceDefinition": { "type": "boolean", "default": false, "description": "%configuration.preferGoToSourceDefinition%", + "markdownDeprecationMessage": "%configuration.preferGoToSourceDefinition.unifiedDeprecationMessage%", "scope": "window" }, + "js/ts.workspaceSymbols.excludeLibrarySymbols": { + "type": "boolean", + "default": true, + "markdownDescription": "%typescript.workspaceSymbols.excludeLibrarySymbols%", + "scope": "window", + "tags": [ + "TypeScript" + ] + }, "typescript.workspaceSymbols.excludeLibrarySymbols": { "type": "boolean", "default": true, "markdownDescription": "%typescript.workspaceSymbols.excludeLibrarySymbols%", + "markdownDeprecationMessage": "%configuration.workspaceSymbols.excludeLibrarySymbols.unifiedDeprecationMessage%", "scope": "window" }, + "js/ts.updateImportsOnPaste.enabled": { + "scope": "window", + "type": "boolean", + "default": true, + "markdownDescription": "%configuration.updateImportsOnPaste%", + "tags": [ + "JavaScript", + "TypeScript" + ] + }, "javascript.updateImportsOnPaste.enabled": { "scope": "window", "type": "boolean", "default": true, - "markdownDescription": "%configuration.updateImportsOnPaste%" + "markdownDescription": "%configuration.updateImportsOnPaste%", + "markdownDeprecationMessage": "%configuration.updateImportsOnPaste.enabled.unifiedDeprecationMessage%" }, "typescript.updateImportsOnPaste.enabled": { "scope": "window", "type": "boolean", "default": true, - "markdownDescription": "%configuration.updateImportsOnPaste%" + "markdownDescription": "%configuration.updateImportsOnPaste%", + "markdownDeprecationMessage": "%configuration.updateImportsOnPaste.enabled.unifiedDeprecationMessage%" }, "js/ts.hover.maximumLength": { "type": "number", diff --git a/extensions/typescript-language-features/package.nls.json b/extensions/typescript-language-features/package.nls.json index cc9fc7e38cc2a..799c5fedf2f65 100644 --- a/extensions/typescript-language-features/package.nls.json +++ b/extensions/typescript-language-features/package.nls.json @@ -121,6 +121,7 @@ "configuration.suggest.autoImports": "Enable/disable auto import suggestions.", "configuration.suggest.autoImports.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.suggest.autoImports#` instead.", "configuration.preferGoToSourceDefinition": "Makes `Go to Definition` avoid type declaration files when possible by triggering `Go to Source Definition` instead. This allows `Go to Source Definition` to be triggered with the mouse gesture.", + "configuration.preferGoToSourceDefinition.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.preferGoToSourceDefinition#` instead.", "inlayHints.parameterNames.none": "Disable parameter name hints.", "inlayHints.parameterNames.literals": "Enable parameter name hints only for literal arguments.", "inlayHints.parameterNames.all": "Enable parameter name hints for literal and non-literal arguments.", @@ -215,11 +216,14 @@ "typescript.preferences.autoImportSpecifierExcludeRegexes": "Specify regular expressions to exclude auto imports with matching import specifiers. Examples:\n\n- `^node:`\n- `lib/internal` (slashes don't need to be escaped...)\n- `/lib\\/internal/i` (...unless including surrounding slashes for `i` or `u` flags)\n- `^lodash$` (only allow subpath imports from lodash)", "typescript.preferences.preferTypeOnlyAutoImports": "Include the `type` keyword in auto-imports whenever possible. Requires using TypeScript 5.3+ in the workspace.", "typescript.workspaceSymbols.excludeLibrarySymbols": "Exclude symbols that come from library files in `Go to Symbol in Workspace` results. Requires using TypeScript 5.3+ in the workspace.", + "configuration.workspaceSymbols.excludeLibrarySymbols.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.workspaceSymbols.excludeLibrarySymbols#` instead.", "typescript.updateImportsOnFileMove.enabled": "Enable/disable automatic updating of import paths when you rename or move a file in VS Code.", "typescript.updateImportsOnFileMove.enabled.prompt": "Prompt on each rename.", "typescript.updateImportsOnFileMove.enabled.always": "Always update paths automatically.", "typescript.updateImportsOnFileMove.enabled.never": "Never rename paths and don't prompt.", + "configuration.updateImportsOnFileMove.enabled.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.updateImportsOnFileMove.enabled#` instead.", "typescript.autoClosingTags": "Enable/disable automatic closing of JSX tags.", + "configuration.autoClosingTags.enabled.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.autoClosingTags.enabled#` instead.", "typescript.suggest.enabled": "Enable/disable autocomplete suggestions.", "configuration.suggest.enabled.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.suggest.enabled#` instead.", "configuration.suggest.completeJSDocs": "Enable/disable suggestion to complete JSDoc comments.", @@ -270,6 +274,7 @@ "typescript.workspaceSymbols.scope": "Controls which files are searched by [Go to Symbol in Workspace](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name).", "typescript.workspaceSymbols.scope.allOpenProjects": "Search all open JavaScript or TypeScript projects for symbols.", "typescript.workspaceSymbols.scope.currentProject": "Only search for symbols in the current JavaScript or TypeScript project.", + "configuration.workspaceSymbols.scope.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.workspaceSymbols.scope#` instead.", "typescript.sortImports": "Sort Imports", "typescript.removeUnusedImports": "Remove Unused Imports", "typescript.findAllFileReferences": "Find File References", @@ -283,6 +288,7 @@ "configuration.tsserver.web.typeAcquisition.enabled": "Enable/disable package acquisition on the web. This enables IntelliSense for imported packages. Requires `#typescript.tsserver.web.projectWideIntellisense.enabled#`. Currently not supported for Safari.", "configuration.tsserver.nodePath": "Run TS Server on a custom Node installation. This can be a path to a Node executable, or 'node' if you want VS Code to detect a Node installation.", "configuration.updateImportsOnPaste": "Automatically update imports when pasting code. Requires TypeScript 5.6+.", + "configuration.updateImportsOnPaste.enabled.unifiedDeprecationMessage": "This setting is deprecated. Use `#js/ts.updateImportsOnPaste.enabled#` instead.", "configuration.hover.maximumLength": "The maximum number of characters in a hover. If the hover is longer than this, it will be truncated. Requires TypeScript 5.9+.", "walkthroughs.nodejsWelcome.title": "Get started with JavaScript and Node.js", "walkthroughs.nodejsWelcome.description": "Make the most of Visual Studio Code's first-class JavaScript experience.", diff --git a/extensions/typescript-language-features/src/configuration/configuration.ts b/extensions/typescript-language-features/src/configuration/configuration.ts index 211beb52f4099..22601ead8eac2 100644 --- a/extensions/typescript-language-features/src/configuration/configuration.ts +++ b/extensions/typescript-language-features/src/configuration/configuration.ts @@ -291,8 +291,8 @@ export abstract class BaseServiceConfigurationProvider implements ServiceConfigu return configuration.get('typescript.tsserver.enableTracing', false); } - private readWorkspaceSymbolsExcludeLibrarySymbols(configuration: vscode.WorkspaceConfiguration): boolean { - return configuration.get('typescript.workspaceSymbols.excludeLibrarySymbols', true); + private readWorkspaceSymbolsExcludeLibrarySymbols(_configuration: vscode.WorkspaceConfiguration): boolean { + return readUnifiedConfig('workspaceSymbols.excludeLibrarySymbols', true, { scope: null, fallbackSection: 'typescript' }); } private readWebProjectWideIntellisenseEnable(configuration: vscode.WorkspaceConfiguration): boolean { diff --git a/extensions/typescript-language-features/src/languageFeatures/copyPaste.ts b/extensions/typescript-language-features/src/languageFeatures/copyPaste.ts index 98b14148d95a9..1cd8529046656 100644 --- a/extensions/typescript-language-features/src/languageFeatures/copyPaste.ts +++ b/extensions/typescript-language-features/src/languageFeatures/copyPaste.ts @@ -11,8 +11,9 @@ import protocol from '../tsServer/protocol/protocol'; import * as typeConverters from '../typeConverters'; import { ClientCapability, ITypeScriptServiceClient, ServerResponse } from '../typescriptService'; import { raceTimeout } from '../utils/async'; +import { readUnifiedConfig } from '../utils/configuration'; import FileConfigurationManager from './fileConfigurationManager'; -import { conditionalRegistration, requireGlobalConfiguration, requireMinVersion, requireSomeCapability } from './util/dependentRegistration'; +import { conditionalRegistration, requireGlobalUnifiedConfig, requireMinVersion, requireSomeCapability } from './util/dependentRegistration'; class CopyMetadata { @@ -75,7 +76,7 @@ class TsPendingPasteEdit extends TsPasteEdit { } } -const enabledSettingId = 'updateImportsOnPaste.enabled'; +const enabledSettingId = 'updateImportsOnPaste.enabled' as const; class DocumentPasteProvider implements vscode.DocumentPasteEditProvider { @@ -239,8 +240,7 @@ class DocumentPasteProvider implements vscode.DocumentPasteEditProvider(enabledSettingId, true, { scope: document, fallbackSection: this._modeId }); } } @@ -248,7 +248,7 @@ export function register(selector: DocumentSelector, language: LanguageDescripti return conditionalRegistration([ requireSomeCapability(client, ClientCapability.Semantic), requireMinVersion(client, API.v570), - requireGlobalConfiguration(language.id, enabledSettingId), + requireGlobalUnifiedConfig(enabledSettingId, { fallbackSection: language.id }), ], () => { return vscode.languages.registerDocumentPasteEditProvider(selector.semantic, new DocumentPasteProvider(language.id, client, fileConfigurationManager), { providedPasteEditKinds: [DocumentPasteProvider.kind], diff --git a/extensions/typescript-language-features/src/languageFeatures/definitions.ts b/extensions/typescript-language-features/src/languageFeatures/definitions.ts index 76c5818be6cc0..b9e6979a88728 100644 --- a/extensions/typescript-language-features/src/languageFeatures/definitions.ts +++ b/extensions/typescript-language-features/src/languageFeatures/definitions.ts @@ -9,6 +9,7 @@ import { API } from '../tsServer/api'; import * as typeConverters from '../typeConverters'; import { ClientCapability, ITypeScriptServiceClient } from '../typescriptService'; import DefinitionProviderBase from './definitionProviderBase'; +import { readUnifiedConfig } from '../utils/configuration'; import { conditionalRegistration, requireSomeCapability } from './util/dependentRegistration'; export default class TypeScriptDefinitionProvider extends DefinitionProviderBase implements vscode.DefinitionProvider { @@ -32,7 +33,7 @@ export default class TypeScriptDefinitionProvider extends DefinitionProviderBase const span = response.body.textSpan ? typeConverters.Range.fromTextSpan(response.body.textSpan) : undefined; let definitions = response.body.definitions; - if (vscode.workspace.getConfiguration(document.languageId).get('preferGoToSourceDefinition', false) && this.client.apiVersion.gte(API.v470)) { + if (readUnifiedConfig('preferGoToSourceDefinition', false, { scope: document, fallbackSection: document.languageId }) && this.client.apiVersion.gte(API.v470)) { const sourceDefinitionsResponse = await this.client.execute('findSourceDefinition', args, token); if (sourceDefinitionsResponse.type === 'response' && sourceDefinitionsResponse.body?.length) { definitions = sourceDefinitionsResponse.body; diff --git a/extensions/typescript-language-features/src/languageFeatures/tagClosing.ts b/extensions/typescript-language-features/src/languageFeatures/tagClosing.ts index 6b47feb3d0005..a42ccbaddf64d 100644 --- a/extensions/typescript-language-features/src/languageFeatures/tagClosing.ts +++ b/extensions/typescript-language-features/src/languageFeatures/tagClosing.ts @@ -10,6 +10,7 @@ import type * as Proto from '../tsServer/protocol/protocol'; import * as typeConverters from '../typeConverters'; import { ITypeScriptServiceClient } from '../typescriptService'; import { Disposable } from '../utils/dispose'; +import { readUnifiedConfig } from '../utils/configuration'; import { Condition, conditionalRegistration } from './util/dependentRegistration'; class TagClosing extends Disposable { @@ -149,7 +150,7 @@ function requireActiveDocumentSetting( return false; } - return !!vscode.workspace.getConfiguration(language.id, editor.document).get('autoClosingTags'); + return !!readUnifiedConfig('autoClosingTags.enabled', true, { scope: editor.document, fallbackSection: language.id, fallbackSubSectionNameOverride: 'autoClosingTags' }); }, handler => { return vscode.Disposable.from( diff --git a/extensions/typescript-language-features/src/languageFeatures/updatePathsOnRename.ts b/extensions/typescript-language-features/src/languageFeatures/updatePathsOnRename.ts index bdaa1fc69ff79..761b13957e271 100644 --- a/extensions/typescript-language-features/src/languageFeatures/updatePathsOnRename.ts +++ b/extensions/typescript-language-features/src/languageFeatures/updatePathsOnRename.ts @@ -12,6 +12,7 @@ import * as typeConverters from '../typeConverters'; import { ClientCapability, ITypeScriptServiceClient } from '../typescriptService'; import { Delayer } from '../utils/async'; import { nulToken } from '../utils/cancellation'; +import { readUnifiedConfig } from '../utils/configuration'; import { Disposable } from '../utils/dispose'; import FileConfigurationManager from './fileConfigurationManager'; import { conditionalRegistration, requireSomeCapability } from './util/dependentRegistration'; @@ -65,8 +66,8 @@ class UpdateImportsOnFileRenameHandler extends Disposable { continue; } - const config = this.getConfiguration(newUri); - const setting = config.get(updateImportsOnFileMoveName); + const fallbackSection = doesResourceLookLikeATypeScriptFile(newUri) ? 'typescript' : 'javascript'; + const setting = readUnifiedConfig(updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Prompt, { scope: null, fallbackSection }); if (setting === UpdateImportsOnFileMoveSetting.Never) { continue; } @@ -122,8 +123,8 @@ class UpdateImportsOnFileRenameHandler extends Disposable { return false; } - const config = this.getConfiguration(newResources[0]); - const setting = config.get(updateImportsOnFileMoveName); + const fallbackSection = doesResourceLookLikeATypeScriptFile(newResources[0]) ? 'typescript' : 'javascript'; + const setting = readUnifiedConfig(updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Prompt, { scope: null, fallbackSection }); switch (setting) { case UpdateImportsOnFileMoveSetting.Always: return true; @@ -135,10 +136,6 @@ class UpdateImportsOnFileRenameHandler extends Disposable { } } - private getConfiguration(resource: vscode.Uri) { - return vscode.workspace.getConfiguration(doesResourceLookLikeATypeScriptFile(resource) ? 'typescript' : 'javascript', resource); - } - private async promptUser(newResources: readonly vscode.Uri[]): Promise { if (!newResources.length) { return false; @@ -177,7 +174,7 @@ class UpdateImportsOnFileRenameHandler extends Disposable { return false; } case alwaysItem: { - const config = this.getConfiguration(newResources[0]); + const config = vscode.workspace.getConfiguration('js/ts'); config.update( updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Always, @@ -185,7 +182,7 @@ class UpdateImportsOnFileRenameHandler extends Disposable { return true; } case neverItem: { - const config = this.getConfiguration(newResources[0]); + const config = vscode.workspace.getConfiguration('js/ts'); config.update( updateImportsOnFileMoveName, UpdateImportsOnFileMoveSetting.Never, diff --git a/extensions/typescript-language-features/src/languageFeatures/workspaceSymbols.ts b/extensions/typescript-language-features/src/languageFeatures/workspaceSymbols.ts index 24fb7068b7438..d1b586a5a20b9 100644 --- a/extensions/typescript-language-features/src/languageFeatures/workspaceSymbols.ts +++ b/extensions/typescript-language-features/src/languageFeatures/workspaceSymbols.ts @@ -13,6 +13,7 @@ import * as PConst from '../tsServer/protocol/protocol.const'; import * as typeConverters from '../typeConverters'; import { ITypeScriptServiceClient } from '../typescriptService'; import { coalesce } from '../utils/arrays'; +import { readUnifiedConfig } from '../utils/configuration'; function getSymbolKind(item: Proto.NavtoItem): vscode.SymbolKind { switch (item.kind) { @@ -70,7 +71,7 @@ class TypeScriptWorkspaceSymbolProvider implements vscode.WorkspaceSymbolProvide private get searchAllOpenProjects() { return this.client.apiVersion.gte(API.v390) - && vscode.workspace.getConfiguration('typescript').get('workspaceSymbols.scope', 'allOpenProjects') === 'allOpenProjects'; + && readUnifiedConfig('workspaceSymbols.scope', 'allOpenProjects', { scope: null, fallbackSection: 'typescript' }) === 'allOpenProjects'; } private async toOpenedFiledPath(document: vscode.TextDocument) { diff --git a/extensions/typescript-language-features/src/typescriptServiceClient.ts b/extensions/typescript-language-features/src/typescriptServiceClient.ts index 207698de92fca..dfd72176e1f44 100644 --- a/extensions/typescript-language-features/src/typescriptServiceClient.ts +++ b/extensions/typescript-language-features/src/typescriptServiceClient.ts @@ -3,7 +3,6 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { homedir } from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { ServiceConfigurationProvider, SyntaxServerConfiguration, TsServerLogLevel, TypeScriptServiceConfiguration, areServiceConfigurationsEqual } from './configuration/configuration'; @@ -1043,11 +1042,6 @@ export default class TypeScriptServiceClient extends Disposable implements IType if (fpath.startsWith(inMemoryResourcePrefix)) { return; } - if (process.platform === 'darwin' && fpath === path.join(homedir(), 'Library')) { - // ignore directory watch requests on ~/Library - // until microsoft/TypeScript#59831 is resolved - return; - } this.createFileSystemWatcher( (event.body as Proto.CreateDirectoryWatcherEventBody).id, diff --git a/extensions/vscode-api-tests/.vscodeignore b/extensions/vscode-api-tests/.vscodeignore index eb6a48615c78e..43e7067afbd26 100644 --- a/extensions/vscode-api-tests/.vscodeignore +++ b/extensions/vscode-api-tests/.vscodeignore @@ -3,4 +3,4 @@ typings/** **/*.ts **/*.map .gitignore -tsconfig.json +tsconfig*.json diff --git a/extensions/vscode-test-resolver/.vscodeignore b/extensions/vscode-test-resolver/.vscodeignore index eb6a48615c78e..43e7067afbd26 100644 --- a/extensions/vscode-test-resolver/.vscodeignore +++ b/extensions/vscode-test-resolver/.vscodeignore @@ -3,4 +3,4 @@ typings/** **/*.ts **/*.map .gitignore -tsconfig.json +tsconfig*.json diff --git a/src/vs/base/common/jsonRpcProtocol.ts b/src/vs/base/common/jsonRpcProtocol.ts new file mode 100644 index 0000000000000..67c4ed4fc4d82 --- /dev/null +++ b/src/vs/base/common/jsonRpcProtocol.ts @@ -0,0 +1,277 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { DeferredPromise } from './async.js'; +import { CancellationToken, CancellationTokenSource } from './cancellation.js'; +import { CancellationError } from './errors.js'; +import { Disposable, toDisposable } from './lifecycle.js'; +import { hasKey } from './types.js'; + +export type JsonRpcId = string | number; + +export interface IJsonRpcError { + code: number; + message: string; + data?: unknown; +} + +export interface IJsonRpcRequest { + jsonrpc: '2.0'; + id: JsonRpcId; + method: string; + params?: unknown; +} + +export interface IJsonRpcNotification { + jsonrpc: '2.0'; + method: string; + params?: unknown; +} + +export interface IJsonRpcSuccessResponse { + jsonrpc: '2.0'; + id: JsonRpcId; + result: unknown; +} + +export interface IJsonRpcErrorResponse { + jsonrpc: '2.0'; + id?: JsonRpcId; + error: IJsonRpcError; +} + +export type JsonRpcMessage = IJsonRpcRequest | IJsonRpcNotification | IJsonRpcSuccessResponse | IJsonRpcErrorResponse; + +interface IPendingRequest { + promise: DeferredPromise; + cts: CancellationTokenSource; +} + +export interface IJsonRpcProtocolHandlers { + handleRequest?(request: IJsonRpcRequest, token: CancellationToken): Promise | unknown; + handleNotification?(notification: IJsonRpcNotification): void; +} + +export class JsonRpcError extends Error { + constructor( + public readonly code: number, + message: string, + public readonly data?: unknown, + ) { + super(message); + } +} + +/** + * Generic JSON-RPC 2.0 protocol helper. + */ +export class JsonRpcProtocol extends Disposable { + private static readonly ParseError = -32700; + private static readonly MethodNotFound = -32601; + private static readonly InternalError = -32603; + + private _nextRequestId = 1; + private readonly _pendingRequests = new Map(); + + constructor( + private readonly _send: (message: JsonRpcMessage) => void, + private readonly _handlers: IJsonRpcProtocolHandlers, + ) { + super(); + } + + public sendNotification(notification: Omit): void { + this._send({ + jsonrpc: '2.0', + ...notification, + }); + } + + public sendRequest(request: Omit, token: CancellationToken = CancellationToken.None, onCancel?: (id: JsonRpcId) => void): Promise { + if (this._store.isDisposed) { + return Promise.reject(new CancellationError()); + } + + const id = this._nextRequestId++; + const promise = new DeferredPromise(); + const cts = new CancellationTokenSource(); + this._pendingRequests.set(id, { promise, cts }); + + const cancelListener = token.onCancellationRequested(() => { + if (!promise.isSettled) { + this._pendingRequests.delete(id); + cts.cancel(); + onCancel?.(id); + promise.cancel(); + } + cancelListener.dispose(); + }); + + this._send({ + jsonrpc: '2.0', + id, + ...request, + }); + + return promise.p.finally(() => { + cancelListener.dispose(); + this._pendingRequests.delete(id); + cts.dispose(true); + }) as Promise; + } + + public async handleMessage(message: JsonRpcMessage | JsonRpcMessage[]): Promise { + if (Array.isArray(message)) { + for (const single of message) { + await this._handleMessage(single); + } + return; + } + + await this._handleMessage(message); + } + + public cancelPendingRequest(id: JsonRpcId): void { + const request = this._pendingRequests.get(id); + if (request) { + this._pendingRequests.delete(id); + request.cts.cancel(); + request.promise.cancel(); + request.cts.dispose(true); + } + } + + public cancelAllRequests(): void { + for (const [id, pending] of this._pendingRequests) { + this._pendingRequests.delete(id); + pending.cts.cancel(); + pending.promise.cancel(); + pending.cts.dispose(true); + } + } + + private async _handleMessage(message: JsonRpcMessage): Promise { + if (isJsonRpcResponse(message)) { + if (hasKey(message, { result: true })) { + this._handleResult(message); + } else { + this._handleError(message); + } + } + + if (isJsonRpcRequest(message)) { + await this._handleRequest(message); + } + + if (isJsonRpcNotification(message)) { + this._handlers.handleNotification?.(message); + } + } + + private _handleResult(response: IJsonRpcSuccessResponse): void { + const request = this._pendingRequests.get(response.id); + if (request) { + this._pendingRequests.delete(response.id); + request.promise.complete(response.result); + request.cts.dispose(true); + } + } + + private _handleError(response: IJsonRpcErrorResponse): void { + if (response.id === undefined) { + return; + } + + const request = this._pendingRequests.get(response.id); + if (request) { + this._pendingRequests.delete(response.id); + request.promise.error(new JsonRpcError(response.error.code, response.error.message, response.error.data)); + request.cts.dispose(true); + } + } + + private async _handleRequest(request: IJsonRpcRequest): Promise { + if (!this._handlers.handleRequest) { + this._send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: JsonRpcProtocol.MethodNotFound, + message: `Method not found: ${request.method}`, + } + }); + return; + } + + const cts = new CancellationTokenSource(); + this._register(toDisposable(() => cts.dispose(true))); + + try { + const resultOrThenable = this._handlers.handleRequest(request, cts.token); + const result = isThenable(resultOrThenable) ? await resultOrThenable : resultOrThenable; + this._send({ + jsonrpc: '2.0', + id: request.id, + result, + }); + } catch (error) { + if (error instanceof JsonRpcError) { + this._send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: error.code, + message: error.message, + data: error.data, + } + }); + } else { + this._send({ + jsonrpc: '2.0', + id: request.id, + error: { + code: JsonRpcProtocol.InternalError, + message: error instanceof Error ? error.message : 'Internal error', + } + }); + } + } finally { + cts.dispose(true); + } + } + + public override dispose(): void { + this.cancelAllRequests(); + super.dispose(); + } + + public static createParseError(message: string, data?: unknown): IJsonRpcErrorResponse { + return { + jsonrpc: '2.0', + error: { + code: JsonRpcProtocol.ParseError, + message, + data, + } + }; + } +} + +export function isJsonRpcRequest(message: JsonRpcMessage): message is IJsonRpcRequest { + return 'method' in message && 'id' in message && (typeof message.id === 'string' || typeof message.id === 'number'); +} + +export function isJsonRpcResponse(message: JsonRpcMessage): message is IJsonRpcSuccessResponse | IJsonRpcErrorResponse { + return hasKey(message, { id: true, result: true }) || hasKey(message, { id: true, error: true }); +} + +export function isJsonRpcNotification(message: JsonRpcMessage): message is IJsonRpcNotification { + return hasKey(message, { method: true }) && !hasKey(message, { id: true }); +} + + +function isThenable(value: T | Promise): value is Promise { + return typeof value === 'object' && value !== null && 'then' in value && typeof value.then === 'function'; +} diff --git a/src/vs/base/test/common/jsonRpcProtocol.test.ts b/src/vs/base/test/common/jsonRpcProtocol.test.ts new file mode 100644 index 0000000000000..4a167d2cc8a2c --- /dev/null +++ b/src/vs/base/test/common/jsonRpcProtocol.test.ts @@ -0,0 +1,232 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { DeferredPromise } from '../../common/async.js'; +import { CancellationToken, CancellationTokenSource } from '../../common/cancellation.js'; +import { CancellationError } from '../../common/errors.js'; +import { IJsonRpcNotification, IJsonRpcProtocolHandlers, IJsonRpcRequest, JsonRpcError, JsonRpcMessage, JsonRpcProtocol } from '../../common/jsonRpcProtocol.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from './utils.js'; + +suite('JsonRpcProtocol', () => { + + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + const createProtocol = (handlers: IJsonRpcProtocolHandlers = {}) => { + const sentMessages: JsonRpcMessage[] = []; + const protocol = new JsonRpcProtocol(message => sentMessages.push(message), handlers); + store.add(protocol); + return { protocol, sentMessages }; + }; + + test('sendNotification adds jsonrpc envelope', () => { + const { protocol, sentMessages } = createProtocol(); + + protocol.sendNotification({ method: 'notify', params: { value: 1 } }); + + assert.deepStrictEqual(sentMessages, [{ + jsonrpc: '2.0', + method: 'notify', + params: { value: 1 } + }]); + }); + + test('sendRequest resolves on success response', async () => { + const { protocol, sentMessages } = createProtocol(); + + const requestPromise = protocol.sendRequest({ method: 'echo', params: { value: 'ok' } }); + const outgoingRequest = sentMessages[0] as IJsonRpcRequest; + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: outgoingRequest.id, + result: 'done' + }); + + const result = await requestPromise; + assert.strictEqual(result, 'done'); + }); + + test('sendRequest rejects on error response', async () => { + const { protocol, sentMessages } = createProtocol(); + + const requestPromise = protocol.sendRequest({ method: 'fail' }); + const outgoingRequest = sentMessages[0] as IJsonRpcRequest; + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: outgoingRequest.id, + error: { + code: 123, + message: 'Failure', + data: { source: 'test' } + } + }); + + await assert.rejects(requestPromise, error => { + assert.ok(error instanceof JsonRpcError); + assert.strictEqual(error.code, 123); + assert.strictEqual(error.message, 'Failure'); + assert.deepStrictEqual(error.data, { source: 'test' }); + return true; + }); + }); + + test('sendRequest honors cancellation token and invokes onCancel', async () => { + const { protocol, sentMessages } = createProtocol(); + const cts = new CancellationTokenSource(); + let canceledId: string | number | undefined; + + const requestPromise = protocol.sendRequest( + { method: 'cancel-me' }, + cts.token, + id => canceledId = id, + ); + const outgoingRequest = sentMessages[0] as IJsonRpcRequest; + + cts.cancel(); + + await assert.rejects(requestPromise, error => error instanceof CancellationError); + assert.strictEqual(canceledId, outgoingRequest.id); + + cts.dispose(true); + }); + + test('cancelPendingRequest rejects active request', async () => { + const { protocol, sentMessages } = createProtocol(); + + const requestPromise = protocol.sendRequest({ method: 'pending' }); + const outgoingRequest = sentMessages[0] as IJsonRpcRequest; + protocol.cancelPendingRequest(outgoingRequest.id); + + await assert.rejects(requestPromise, error => error instanceof CancellationError); + }); + + test('handleRequest responds with method not found without handler', async () => { + const { protocol, sentMessages } = createProtocol(); + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: 7, + method: 'unknown' + }); + + assert.deepStrictEqual(sentMessages, [{ + jsonrpc: '2.0', + id: 7, + error: { + code: -32601, + message: 'Method not found: unknown' + } + }]); + }); + + test('handleRequest responds with result and passes cancellation token', async () => { + let receivedToken: CancellationToken | undefined; + let wasCanceledDuringHandler: boolean | undefined; + const { protocol, sentMessages } = createProtocol({ + handleRequest: async (request, token) => { + receivedToken = token; + wasCanceledDuringHandler = token.isCancellationRequested; + return `${request.method}:ok`; + } + }); + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: 9, + method: 'compute' + }); + + assert.ok(receivedToken); + assert.strictEqual(wasCanceledDuringHandler, false); + assert.deepStrictEqual(sentMessages, [{ + jsonrpc: '2.0', + id: 9, + result: 'compute:ok' + }]); + }); + + test('handleRequest serializes JsonRpcError', async () => { + const { protocol, sentMessages } = createProtocol({ + handleRequest: () => { + throw new JsonRpcError(88, 'bad request', { detail: true }); + } + }); + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: 'a', + method: 'boom' + }); + + assert.deepStrictEqual(sentMessages, [{ + jsonrpc: '2.0', + id: 'a', + error: { + code: 88, + message: 'bad request', + data: { detail: true } + } + }]); + }); + + test('handleRequest maps unknown errors to internal error', async () => { + const { protocol, sentMessages } = createProtocol({ + handleRequest: () => { + throw new Error('unexpected'); + } + }); + + await protocol.handleMessage({ + jsonrpc: '2.0', + id: 'b', + method: 'explode' + }); + + assert.deepStrictEqual(sentMessages, [{ + jsonrpc: '2.0', + id: 'b', + error: { + code: -32603, + message: 'unexpected' + } + }]); + }); + + test('handleMessage processes batch sequentially', async () => { + const sequence: string[] = []; + const gate = new DeferredPromise(); + const { protocol } = createProtocol({ + handleRequest: async () => { + sequence.push('request:start'); + await gate.p; + sequence.push('request:end'); + return true; + }, + handleNotification: () => { + sequence.push('notification'); + } + }); + + const request: IJsonRpcRequest = { + jsonrpc: '2.0', + id: 1, + method: 'first' + }; + const notification: IJsonRpcNotification = { + jsonrpc: '2.0', + method: 'second' + }; + + const handlingPromise = protocol.handleMessage([request, notification]); + assert.deepStrictEqual(sequence, ['request:start']); + + gate.complete(); + await handlingPromise; + + assert.deepStrictEqual(sequence, ['request:start', 'request:end', 'notification']); + }); +}); diff --git a/src/vs/platform/actions/common/actions.ts b/src/vs/platform/actions/common/actions.ts index 86afa862d5def..5f7568c810bd3 100644 --- a/src/vs/platform/actions/common/actions.ts +++ b/src/vs/platform/actions/common/actions.ts @@ -245,7 +245,6 @@ export class MenuId { static readonly MergeInputResultToolbar = new MenuId('MergeToolbarResultToolbar'); static readonly InlineSuggestionToolbar = new MenuId('InlineSuggestionToolbar'); static readonly InlineEditToolbar = new MenuId('InlineEditToolbar'); - static readonly AgentFeedbackEditorContent = new MenuId('AgentFeedbackEditorContent'); static readonly ChatContext = new MenuId('ChatContext'); static readonly ChatCodeBlock = new MenuId('ChatCodeblock'); static readonly ChatCompareBlock = new MenuId('ChatCompareBlock'); diff --git a/src/vs/platform/browserElements/common/browserElements.ts b/src/vs/platform/browserElements/common/browserElements.ts index 5f6b0c82414a0..2973d9db93918 100644 --- a/src/vs/platform/browserElements/common/browserElements.ts +++ b/src/vs/platform/browserElements/common/browserElements.ts @@ -9,10 +9,21 @@ import { IRectangle } from '../../window/common/window.js'; export const INativeBrowserElementsService = createDecorator('nativeBrowserElementsService'); +export interface IElementAncestor { + readonly tagName: string; + readonly id?: string; + readonly classNames?: string[]; +} + export interface IElementData { readonly outerHTML: string; readonly computedStyle: string; readonly bounds: IRectangle; + readonly ancestors?: IElementAncestor[]; + readonly attributes?: Record; + readonly computedStyles?: Record; + readonly dimensions?: { readonly top: number; readonly left: number; readonly width: number; readonly height: number }; + readonly innerText?: string; } /** diff --git a/src/vs/platform/browserElements/electron-main/nativeBrowserElementsMainService.ts b/src/vs/platform/browserElements/electron-main/nativeBrowserElementsMainService.ts index 4e53a021745ae..5e018a6d718a2 100644 --- a/src/vs/platform/browserElements/electron-main/nativeBrowserElementsMainService.ts +++ b/src/vs/platform/browserElements/electron-main/nativeBrowserElementsMainService.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { IElementData, INativeBrowserElementsService, IBrowserTargetLocator } from '../common/browserElements.js'; +import { IElementData, IElementAncestor, INativeBrowserElementsService, IBrowserTargetLocator } from '../common/browserElements.js'; import { CancellationToken } from '../../../base/common/cancellation.js'; import { IRectangle } from '../../window/common/window.js'; import { BrowserWindow, webContents } from 'electron'; @@ -23,17 +23,20 @@ interface NodeDataResponse { outerHTML: string; computedStyle: string; bounds: IRectangle; + ancestors?: IElementAncestor[]; + attributes?: Record; + computedStyles?: Record; + dimensions?: { top: number; left: number; width: number; height: number }; + innerText?: string; } const MAX_CONSOLE_LOG_ENTRIES = 1000; + +/** Stores captured console log entries, keyed by a locator string. */ const consoleLogStore = new Map(); -function locatorKey(locator: IBrowserTargetLocator): string { - const key = locator.browserViewId ?? locator.webviewId; - if (!key) { - return 'unknown'; - } - return key; +function locatorKey(locator: IBrowserTargetLocator): string | undefined { + return locator.browserViewId ?? locator.webviewId; } export class NativeBrowserElementsMainService extends Disposable implements INativeBrowserElementsMainService { @@ -51,6 +54,10 @@ export class NativeBrowserElementsMainService extends Disposable implements INat async getConsoleLogs(windowId: number | undefined, locator: IBrowserTargetLocator): Promise { const key = locatorKey(locator); + if (!key) { + return undefined; + } + const entries = consoleLogStore.get(key); if (!entries || entries.length === 0) { return undefined; @@ -63,7 +70,10 @@ export class NativeBrowserElementsMainService extends Disposable implements INat if (!window?.win) { return undefined; } + const windowWebContents = window.win.webContents; + // For BrowserView targets, listen to the console-message event directly + // on the BrowserView's webContents. No CDP needed. let targetWebContents: Electron.WebContents | undefined; if (locator.browserViewId) { targetWebContents = this.browserViewMainService.tryGetBrowserView(locator.browserViewId)?.webContents; @@ -74,6 +84,11 @@ export class NativeBrowserElementsMainService extends Disposable implements INat } const key = locatorKey(locator); + if (!key) { + return undefined; + } + + // Initialize log store for this locator if it doesn't exist yet (don't clear on restart) if (!consoleLogStore.has(key)) { consoleLogStore.set(key, []); } @@ -92,32 +107,27 @@ export class NativeBrowserElementsMainService extends Disposable implements INat const cleanupListeners = () => { targetWebContents?.off('console-message', onConsoleMessage); - window.win?.webContents.off('ipc-message', onIpcMessage); + targetWebContents?.off('destroyed', onTargetDestroyed); + windowWebContents.off('ipc-message', onIpcMessage); }; - const onIpcMessage = async (_event: Electron.Event, channel: string, closedCancelAndDetachId: number) => { + const onIpcMessage = (_event: Electron.Event, channel: string, closedCancelAndDetachId: number) => { if (channel === `vscode:cancelConsoleSession${cancelAndDetachId}`) { if (cancelAndDetachId !== closedCancelAndDetachId) { return; } cleanupListeners(); - consoleLogStore.delete(key); } }; - targetWebContents.on('console-message', onConsoleMessage); - - targetWebContents.once('destroyed', () => { + const onTargetDestroyed = () => { cleanupListeners(); - consoleLogStore.delete(key); - }); - - token.onCancellationRequested(() => { - cleanupListeners(); - consoleLogStore.delete(key); - }); + }; - window.win.webContents.on('ipc-message', onIpcMessage); + targetWebContents.on('console-message', onConsoleMessage); + targetWebContents.on('destroyed', onTargetDestroyed); + windowWebContents.on('ipc-message', onIpcMessage); + token.onCancellationRequested(cleanupListeners); } /** @@ -376,7 +386,7 @@ export class NativeBrowserElementsMainService extends Disposable implements INat }, sessionId); } catch (e) { debuggers.detach(); - throw new Error('No target found', e); + throw new Error('No target found', { cause: e }); } if (!targetSessionId) { @@ -409,7 +419,16 @@ export class NativeBrowserElementsMainService extends Disposable implements INat height: clippedBounds.height * zoomFactor }; - return { outerHTML: nodeData.outerHTML, computedStyle: nodeData.computedStyle, bounds: scaledBounds }; + return { + outerHTML: nodeData.outerHTML, + computedStyle: nodeData.computedStyle, + bounds: scaledBounds, + ancestors: nodeData.ancestors, + attributes: nodeData.attributes, + computedStyles: nodeData.computedStyles, + dimensions: nodeData.dimensions, + innerText: nodeData.innerText, + }; } async getNodeData(sessionId: string, debuggers: Electron.Debugger, window: BrowserWindow, cancellationId?: number): Promise { @@ -460,10 +479,91 @@ export class NativeBrowserElementsMainService extends Disposable implements INat throw new Error('Failed to get outerHTML.'); } + // Extract additional structured data for rich hover + let ancestors: IElementAncestor[] | undefined; + let attributes: Record | undefined; + let computedStyles: Record | undefined; + let innerText: string | undefined; + + try { + // Build ancestor chain using JavaScript evaluation (more reliable than DOM.describeNode for parent walking) + const { object: resolvedNode } = await debuggers.sendCommand('DOM.resolveNode', { nodeId }, sessionId); + if (resolvedNode?.objectId) { + const { result: ancestorResult } = await debuggers.sendCommand('Runtime.callFunctionOn', { + objectId: resolvedNode.objectId, + functionDeclaration: `function() { + var chain = []; + var el = this; + while (el && el.nodeType === 1) { + var entry = { tagName: el.tagName.toLowerCase() }; + if (el.id) { entry.id = el.id; } + if (el.className && typeof el.className === 'string') { + var cls = el.className.trim().split(/\\s+/).filter(Boolean); + if (cls.length > 0) { entry.classNames = cls; } + } + chain.unshift(entry); + el = el.parentElement; + } + return chain; + }`, + returnByValue: true, + }, sessionId); + if (ancestorResult?.value && Array.isArray(ancestorResult.value)) { + ancestors = ancestorResult.value; + } + + // Get attributes from the element + const { result: attrResult } = await debuggers.sendCommand('Runtime.callFunctionOn', { + objectId: resolvedNode.objectId, + functionDeclaration: `function() { + var attrs = {}; + for (var i = 0; i < this.attributes.length; i++) { + attrs[this.attributes[i].name] = this.attributes[i].value; + } + return attrs; + }`, + returnByValue: true, + }, sessionId); + if (attrResult?.value) { + attributes = attrResult.value; + } + + // Get inner text (truncated) + const { result: innerTextResult } = await debuggers.sendCommand('Runtime.callFunctionOn', { + objectId: resolvedNode.objectId, + functionDeclaration: 'function() { return this.innerText; }', + returnByValue: true, + }, sessionId); + if (innerTextResult?.value) { + const text = String(innerTextResult.value).trim(); + innerText = text.length > 100 ? text.substring(0, 100) + '\u2026' : text; + } + } + + // Capture all computed styles for model-facing element context. + const { computedStyle: computedStyleArray } = await debuggers.sendCommand('CSS.getComputedStyleForNode', { nodeId }, sessionId); + if (computedStyleArray) { + computedStyles = {}; + for (const prop of computedStyleArray) { + if (prop.name && typeof prop.value === 'string') { + computedStyles[prop.name] = prop.value; + } + } + } + } catch { + // Non-critical: if any enrichment fails, we still have the core data + } + + // TODO: computedStyle here is actually the matched styles resolve({ outerHTML, computedStyle: formatted, - bounds: { x, y, width, height } + bounds: { x, y, width, height }, + ancestors, + attributes, + computedStyles, + dimensions: { top: y, left: x, width, height }, + innerText, }); } catch (err) { debuggers.off('message', onMessage); diff --git a/src/vs/platform/mcp/common/mcpGateway.ts b/src/vs/platform/mcp/common/mcpGateway.ts index 816824dcd4333..e8d2194d37a6b 100644 --- a/src/vs/platform/mcp/common/mcpGateway.ts +++ b/src/vs/platform/mcp/common/mcpGateway.ts @@ -3,12 +3,21 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { Event } from '../../../base/common/event.js'; import { URI } from '../../../base/common/uri.js'; import { createDecorator } from '../../instantiation/common/instantiation.js'; +import { MCP } from './modelContextProtocol.js'; export const IMcpGatewayService = createDecorator('IMcpGatewayService'); export const McpGatewayChannelName = 'mcpGateway'; +export const McpGatewayToolBrokerChannelName = 'mcpGatewayToolBroker'; + +export interface IMcpGatewayToolInvoker { + readonly onDidChangeTools: Event; + listTools(): Promise; + callTool(name: string, args: Record): Promise; +} /** * Result of creating an MCP gateway. @@ -52,7 +61,7 @@ export interface IMcpGatewayService { * @param context Optional context (e.g., client ID) to associate with the gateway for cleanup purposes. * @returns A promise that resolves to the gateway info if successful. */ - createGateway(context: TContext): Promise; + createGateway(context: TContext, toolInvoker?: IMcpGatewayToolInvoker): Promise; /** * Disposes a previously created gateway. diff --git a/src/vs/platform/mcp/common/modelContextProtocol.ts b/src/vs/platform/mcp/common/modelContextProtocol.ts new file mode 100644 index 0000000000000..db33783efc616 --- /dev/null +++ b/src/vs/platform/mcp/common/modelContextProtocol.ts @@ -0,0 +1,3277 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +/* eslint-disable local/code-no-unexternalized-strings */ + +//#region proposals +/** + * MCP protocol proposals. + * - Proposals here MUST have an MCP PR linked to them + * - Proposals here are subject to change and SHALL be removed when + * the upstream MCP PR is merged or closed. + */ +export namespace MCP { + + // Nothing, yet + +} + +//#endregion + +/** + * Schema updated from the Model Context Protocol repository at + * https://github.com/modelcontextprotocol/specification/tree/main/schema + * + * ⚠️ Do not edit within `namespace` manually except to update schema versions ⚠️ + */ +export namespace MCP { + /* JSON-RPC types */ + + /** + * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. + * + * @category JSON-RPC + */ + export type JSONRPCMessage = + | JSONRPCRequest + | JSONRPCNotification + | 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. + * + * @category Common Types + */ + export type ProgressToken = string | number; + + /** + * An opaque token used to represent a cursor for pagination. + * + * @category Common Types + */ + export type Cursor = string; + + /** + * Common params for any task-augmented request. + * + * @internal + */ + export interface TaskAugmentedRequestParams extends RequestParams { + /** + * If specified, the caller is requesting task-augmented execution for this request. + * 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. + * + * @category Common Types + */ + export interface RequestParams { + _meta?: RequestMetaObject; + } + + /** @internal */ + export interface Request { + method: string; + // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; + } + + /** + * Common params for any notification. + * + * @category Common Types + */ + export interface NotificationParams { + _meta?: MetaObject; + } + + /** @internal */ + export interface Notification { + method: string; + // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + params?: { [key: string]: any }; + } + + /** + * Common result fields. + * + * @category Common Types + */ + export interface Result { + _meta?: MetaObject; + [key: string]: unknown; + } + + /** + * @category Errors + */ + export interface Error { + /** + * The error type that occurred. + */ + code: number; + /** + * A short description of the error. The message SHOULD be limited to a concise single sentence. + */ + message: string; + /** + * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). + */ + data?: unknown; + } + + /** + * A uniquely identifying ID for a request in JSON-RPC. + * + * @category Common Types + */ + export type RequestId = string | number; + + /** + * A request that expects a response. + * + * @category JSON-RPC + */ + export interface JSONRPCRequest extends Request { + jsonrpc: typeof JSONRPC_VERSION; + id: RequestId; + } + + /** + * A notification which does not expect a response. + * + * @category JSON-RPC + */ + export interface JSONRPCNotification extends Notification { + jsonrpc: typeof JSONRPC_VERSION; + } + + /** + * A successful (non-error) response to a request. + * + * @category JSON-RPC + */ + 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; + export const METHOD_NOT_FOUND = -32601; + 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; + + /** + * 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< + JSONRPCErrorResponse, + "error" + > { + error: Error & { + code: typeof URL_ELICITATION_REQUIRED; + data: { + elicitations: ElicitRequestURLParams[]; + [key: string]: unknown; + }; + }; + } + + /* Empty result */ + /** + * A result that indicates success but carries no data. + * + * @category Common Types + */ + export type EmptyResult = Result; + + /* Cancellation */ + /** + * 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 { + /** + * The ID of the request to cancel. + * + * 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 {@link CancelTaskRequest | tasks/cancel} request instead). + */ + requestId?: RequestId; + + /** + * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. + */ + reason?: string; + } + + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its `initialize` request. + * + * 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` + */ + export interface CancelledNotification extends JSONRPCNotification { + method: "notifications/cancelled"; + params: CancelledNotificationParams; + } + + /* Initialization */ + /** + * Parameters for an `initialize` request. + * + * @example Full client capabilities + * {@includeCode ./examples/InitializeRequestParams/full-client-capabilities.json} + * + * @category `initialize` + */ + export interface InitializeRequestParams extends RequestParams { + /** + * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. + */ + protocolVersion: string; + capabilities: ClientCapabilities; + clientInfo: Implementation; + } + + /** + * 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 { + method: "initialize"; + params: InitializeRequestParams; + } + + /** + * 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` + */ + export interface InitializeResult extends Result { + /** + * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. + */ + protocolVersion: string; + capabilities: ServerCapabilities; + serverInfo: Implementation; + + /** + * Instructions describing how to use the server and its features. + * + * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. + */ + 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 { + method: "notifications/initialized"; + params?: NotificationParams; + } + + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + * + * @category `initialize` + */ + export interface ClientCapabilities { + /** + * Experimental, non-standard capabilities that the client supports. + */ + 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?: { + /** + * Whether the client supports notifications for changes to the roots list. + */ + listChanged?: boolean; + }; + /** + * 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. + * 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. + */ + 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 }; + + /** + * Present if the client supports task-augmented requests. + */ + tasks?: { + /** + * Whether this client supports {@link ListTasksRequest | tasks/list}. + */ + list?: object; + /** + * Whether this client supports {@link CancelTaskRequest | tasks/cancel}. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for sampling-related requests. + */ + sampling?: { + /** + * Whether the client supports task-augmented `sampling/createMessage` requests. + */ + createMessage?: object; + }; + /** + * Task support for elicitation-related requests. + */ + elicitation?: { + /** + * 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 }; + } + + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + * + * @category `initialize` + */ + export interface ServerCapabilities { + /** + * Experimental, non-standard capabilities that the server supports. + */ + 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?: { + /** + * Whether this server supports notifications for changes to the prompt list. + */ + listChanged?: boolean; + }; + /** + * 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?: { + /** + * Whether this server supports subscribing to resource updates. + */ + subscribe?: boolean; + /** + * Whether this server supports notifications for changes to the resource list. + */ + listChanged?: boolean; + }; + /** + * 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?: { + /** + * Whether this server supports notifications for changes to the tool list. + */ + listChanged?: boolean; + }; + /** + * Present if the server supports task-augmented requests. + */ + tasks?: { + /** + * Whether this server supports {@link ListTasksRequest | tasks/list}. + */ + list?: object; + /** + * Whether this server supports {@link CancelTaskRequest | tasks/cancel}. + */ + cancel?: object; + /** + * Specifies which request types can be augmented with tasks. + */ + requests?: { + /** + * Task support for tool-related requests. + */ + tools?: { + /** + * 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 }; + } + + /** + * An optionally-sized icon that can be displayed in a user interface. + * + * @category Common Types + */ + export interface Icon { + /** + * 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 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 + * executable JavaScript. + * + * @format uri + */ + src: string; + + /** + * Optional MIME type override if the source MIME type is missing or generic. + * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. + */ + mimeType?: string; + + /** + * Optional array of strings that specify sizes at which the icon can be used. + * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. + * + * If not provided, the client should assume that the icon can be used at any size. + */ + 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 + * 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. + */ + theme?: "light" | "dark"; + } + + /** + * Base interface to add `icons` property. + * + * @internal + */ + export interface Icons { + /** + * Optional set of sized icons that the client can display in a user interface. + * + * Clients that support rendering icons MUST support at least the following MIME types: + * - `image/png` - PNG images (safe, universal compatibility) + * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) + * + * Clients that support rendering icons SHOULD also support: + * - `image/svg+xml` - SVG images (scalable but requires security precautions) + * - `image/webp` - WebP images (modern, efficient format) + */ + icons?: Icon[]; + } + + /** + * Base interface for metadata with name (identifier) and title (display name) properties. + * + * @internal + */ + export interface BaseMetadata { + /** + * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). + */ + name: string; + + /** + * 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 {@link Tool}, + * where `annotations.title` should be given precedence over using `name`, + * if present). + */ + title?: string; + } + + /** + * Describes the MCP implementation. + * + * @category `initialize` + */ + export interface Implementation extends BaseMetadata, Icons { + /** + * The version of this implementation. + */ + version: string; + + /** + * An optional human-readable description of what this implementation does. + * + * This can be used by clients or servers to provide context about their purpose + * and capabilities. For example, a server might describe the types of resources + * or tools it provides, while a client might describe its intended use case. + */ + description?: string; + + /** + * An optional URL of the website for this implementation. + * + * @format uri + */ + websiteUrl?: string; + } + + /* Ping */ + /** + * 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 { + method: "ping"; + 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 {@link ProgressNotification | notifications/progress} notification. + * + * @example Progress message + * {@includeCode ./examples/ProgressNotificationParams/progress-message.json} + * + * @category `notifications/progress` + */ + export interface ProgressNotificationParams extends NotificationParams { + /** + * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. + */ + progressToken: ProgressToken; + /** + * The progress thus far. This should increase every time progress is made, even if the total is unknown. + * + * @TJS-type number + */ + progress: number; + /** + * Total number of items to process (or total progress required), if known. + * + * @TJS-type number + */ + total?: number; + /** + * An optional message describing the current progress. + */ + message?: string; + } + + /** + * 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 { + method: "notifications/progress"; + params: ProgressNotificationParams; + } + + /* Pagination */ + /** + * Common params for paginated requests. + * + * @example List request with cursor + * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json} + * + * @category Common Types + */ + export interface PaginatedRequestParams extends RequestParams { + /** + * An opaque token representing the current pagination position. + * If provided, the server should return results starting after this cursor. + */ + cursor?: Cursor; + } + + /** @internal */ + export interface PaginatedRequest extends JSONRPCRequest { + params?: PaginatedRequestParams; + } + + /** @internal */ + export interface PaginatedResult extends Result { + /** + * An opaque token representing the pagination position after the last returned result. + * If present, there may be more results available. + */ + nextCursor?: Cursor; + } + + /* Resources */ + /** + * 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 { + method: "resources/list"; + } + + /** + * 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` + */ + export interface ListResourcesResult extends PaginatedResult { + 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 { + method: "resources/templates/list"; + } + + /** + * 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` + */ + export interface ListResourceTemplatesResult extends PaginatedResult { + resourceTemplates: ResourceTemplate[]; + } + + /** + * 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 + */ + export interface ResourceRequestParams extends RequestParams { + /** + * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. + * + * @format uri + */ + uri: string; + } + + /** + * Parameters for a `resources/read` request. + * + * @category `resources/read` + */ + export interface ReadResourceRequestParams extends ResourceRequestParams { } + + /** + * 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 { + method: "resources/read"; + params: ReadResourceRequestParams; + } + + /** + * 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` + */ + export interface ReadResourceResult extends Result { + 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 { + method: "notifications/resources/list_changed"; + params?: NotificationParams; + } + + /** + * 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 {@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` + */ + export interface SubscribeRequest extends JSONRPCRequest { + method: "resources/subscribe"; + 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. + * + * @category `resources/unsubscribe` + */ + export interface UnsubscribeRequestParams extends ResourceRequestParams { } + + /** + * 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` + */ + export interface UnsubscribeRequest extends JSONRPCRequest { + method: "resources/unsubscribe"; + 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 { + /** + * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. + * + * @format uri + */ + uri: string; + } + + /** + * 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` + */ + export interface ResourceUpdatedNotification extends JSONRPCNotification { + method: "notifications/resources/updated"; + params: ResourceUpdatedNotificationParams; + } + + /** + * 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 { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + + /** + * A description of what this resource represents. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + /** + * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. + * + * This can be used by Hosts to display file sizes and estimate context window usage. + */ + size?: number; + + _meta?: MetaObject; + } + + /** + * A template description for resources available on the server. + * + * @category `resources/templates/list` + */ + export interface ResourceTemplate extends BaseMetadata, Icons { + /** + * A URI template (according to RFC 6570) that can be used to construct resource URIs. + * + * @format uri-template + */ + uriTemplate: string; + + /** + * A description of what this template is for. + * + * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. + */ + mimeType?: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _meta?: MetaObject; + } + + /** + * The contents of a specific resource or sub-resource. + * + * @internal + */ + export interface ResourceContents { + /** + * The URI of this resource. + * + * @format uri + */ + uri: string; + /** + * The MIME type of this resource, if known. + */ + mimeType?: string; + + _meta?: MetaObject; + } + + /** + * @example Text file contents + * {@includeCode ./examples/TextResourceContents/text-file-contents.json} + * + * @category Content + */ + export interface TextResourceContents extends ResourceContents { + /** + * The text of the item. This must only be set if the item can actually be represented as text (not binary data). + */ + text: string; + } + + /** + * @example Image file contents + * {@includeCode ./examples/BlobResourceContents/image-file-contents.json} + * + * @category Content + */ + export interface BlobResourceContents extends ResourceContents { + /** + * A base64-encoded string representing the binary data of the item. + * + * @format byte + */ + blob: string; + } + + /* Prompts */ + /** + * 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 { + method: "prompts/list"; + } + + /** + * 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` + */ + export interface ListPromptsResult extends PaginatedResult { + 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 { + /** + * The name of the prompt or prompt template. + */ + name: string; + /** + * Arguments to use for templating the prompt. + */ + arguments?: { [key: string]: string }; + } + + /** + * 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 { + method: "prompts/get"; + params: GetPromptRequestParams; + } + + /** + * 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` + */ + export interface GetPromptResult extends Result { + /** + * An optional description for the prompt. + */ + description?: string; + 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. + * + * @category `prompts/list` + */ + export interface Prompt extends BaseMetadata, Icons { + /** + * An optional description of what this prompt provides + */ + description?: string; + + /** + * A list of arguments to use for templating the prompt. + */ + arguments?: PromptArgument[]; + + _meta?: MetaObject; + } + + /** + * Describes an argument that a prompt can accept. + * + * @category `prompts/list` + */ + export interface PromptArgument extends BaseMetadata { + /** + * A human-readable description of the argument. + */ + description?: string; + /** + * Whether this argument must be provided. + */ + required?: boolean; + } + + /** + * The sender or recipient of messages and data in a conversation. + * + * @category Common Types + */ + export type Role = "user" | "assistant"; + + /** + * Describes a message returned as part of a prompt. + * + * This is similar to {@link SamplingMessage}, but also supports the embedding of + * resources from the MCP server. + * + * @category `prompts/get` + */ + export interface PromptMessage { + role: Role; + content: ContentBlock; + } + + /** + * 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 {@link ListResourcesRequest | resources/list} requests. + * + * @example File resource link + * {@includeCode ./examples/ResourceLink/file-resource-link.json} + * + * @category Content + */ + export interface ResourceLink extends Resource { + type: "resource_link"; + } + + /** + * The contents of a resource, embedded into a prompt or tool call result. + * + * 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 { + type: "resource"; + resource: TextResourceContents | BlobResourceContents; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _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 { + method: "notifications/prompts/list_changed"; + params?: NotificationParams; + } + + /* Tools */ + /** + * 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 { + method: "tools/list"; + } + + /** + * 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` + */ + export interface ListToolsResult extends PaginatedResult { + tools: Tool[]; + } + + /** + * 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` + */ + export interface CallToolResult extends Result { + /** + * A list of content objects that represent the unstructured result of the tool call. + */ + content: ContentBlock[]; + + /** + * An optional JSON object that represents the structured result of the tool call. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool call ended in an error. + * + * If not set, this is assumed to be false (the call was successful). + * + * Any errors that originate from the tool SHOULD be reported inside the result + * object, with `isError` set to true, _not_ as an MCP protocol-level error + * response. Otherwise, the LLM would not be able to see that an error occurred + * and self-correct. + * + * However, any errors in _finding_ the tool, an error indicating that the + * server does not support tool calls, or any other exceptional conditions, + * should be reported as an MCP error response. + */ + 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 { + /** + * The name of the tool. + */ + name: string; + /** + * Arguments to use for the tool call. + */ + arguments?: { [key: string]: unknown }; + } + + /** + * 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 { + method: "tools/call"; + params: CallToolRequestParams; + } + + /** + * 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 { + method: "notifications/tools/list_changed"; + params?: NotificationParams; + } + + /** + * Additional properties describing a {@link Tool} to clients. + * + * 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` + * received from untrusted servers. + * + * @category `tools/list` + */ + export interface ToolAnnotations { + /** + * A human-readable title for the tool. + */ + title?: string; + + /** + * If true, the tool does not modify its environment. + * + * Default: false + */ + readOnlyHint?: boolean; + + /** + * If true, the tool may perform destructive updates to its environment. + * If false, the tool performs only additive updates. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: true + */ + destructiveHint?: boolean; + + /** + * If true, calling the tool repeatedly with the same arguments + * will have no additional effect on its environment. + * + * (This property is meaningful only when `readOnlyHint == false`) + * + * Default: false + */ + idempotentHint?: boolean; + + /** + * If true, this tool may interact with an "open world" of external + * entities. If false, the tool's domain of interaction is closed. + * For example, the world of a web search tool is open, whereas that + * of a memory tool is not. + * + * Default: true + */ + openWorldHint?: boolean; + } + + /** + * Execution-related properties for a tool. + * + * @category `tools/list` + */ + export interface ToolExecution { + /** + * Indicates whether this tool supports task-augmented execution. + * 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 + * + * Default: `"forbidden"` + */ + taskSupport?: "forbidden" | "optional" | "required"; + } + + /** + * 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 { + /** + * A human-readable description of the tool. + * + * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. + */ + description?: string; + + /** + * A JSON Schema object defining the expected parameters for the tool. + */ + inputSchema: { + $schema?: string; + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Execution-related properties for this tool. + */ + execution?: ToolExecution; + + /** + * An optional JSON Schema object defining the structure of the tool's output returned in + * 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. + */ + outputSchema?: { + $schema?: string; + type: "object"; + properties?: { [key: string]: object }; + required?: string[]; + }; + + /** + * Optional additional tool information. + * + * Display name precedence order is: `title`, `annotations.title`, then `name`. + */ + annotations?: ToolAnnotations; + + _meta?: MetaObject; + } + + /* Tasks */ + + /** + * The status of a task. + * + * @category `tasks` + */ + export type TaskStatus = + | "working" // The request is currently being processed + | "input_required" // The task is waiting for input (e.g., elicitation or sampling) + | "completed" // The request completed successfully and results are available + | "failed" // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. + | "cancelled"; // The request was cancelled before completion + + /** + * Metadata for augmenting a request with task execution. + * Include this in the `task` field of the request parameters. + * + * @category `tasks` + */ + export interface TaskMetadata { + /** + * Requested duration in milliseconds to retain task from creation. + */ + ttl?: number; + } + + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @category `tasks` + */ + export interface RelatedTaskMetadata { + /** + * The task identifier this message is associated with. + */ + taskId: string; + } + + /** + * Data associated with a task. + * + * @category `tasks` + */ + export interface Task { + /** + * The task identifier. + */ + taskId: string; + + /** + * Current task state. + */ + status: TaskStatus; + + /** + * Optional human-readable message describing the current task state. + * This can provide context for any status, including: + * - Reasons for "cancelled" status + * - Summaries for "completed" status + * - Diagnostic information for "failed" status (e.g., error details, what went wrong) + */ + statusMessage?: string; + + /** + * ISO 8601 timestamp when the task was created. + */ + createdAt: string; + + /** + * ISO 8601 timestamp when the task was last updated. + */ + lastUpdatedAt: string; + + /** + * Actual retention duration from creation in milliseconds, null for unlimited. + */ + ttl: number | null; + + /** + * Suggested polling interval in milliseconds. + */ + pollInterval?: number; + } + + /** + * The result returned for a task-augmented request. + * + * @category `tasks` + */ + export interface CreateTaskResult extends Result { + 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. + * + * @category `tasks/get` + */ + export interface GetTaskRequest extends JSONRPCRequest { + method: "tasks/get"; + params: { + /** + * The task identifier to query. + */ + taskId: string; + }; + } + + /** + * 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. + * + * @category `tasks/result` + */ + export interface GetTaskPayloadRequest extends JSONRPCRequest { + method: "tasks/result"; + params: { + /** + * The task identifier to retrieve results for. + */ + taskId: string; + }; + } + + /** + * The result returned for a {@link GetTaskPayloadRequest | tasks/result} request. + * The structure matches the result type of the original request. + * For example, a {@link CallToolRequest | tools/call} task would return the {@link CallToolResult} structure. + * + * @category `tasks/result` + */ + export interface GetTaskPayloadResult extends Result { + [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. + * + * @category `tasks/cancel` + */ + export interface CancelTaskRequest extends JSONRPCRequest { + method: "tasks/cancel"; + params: { + /** + * The task identifier to cancel. + */ + taskId: string; + }; + } + + /** + * 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. + * + * @category `tasks/list` + */ + export interface ListTasksRequest extends PaginatedRequest { + method: "tasks/list"; + } + + /** + * The result returned for a {@link ListTasksRequest | tasks/list} request. + * + * @category `tasks/list` + */ + export interface ListTasksResult extends PaginatedResult { + 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. + * + * @category `notifications/tasks/status` + */ + export type TaskStatusNotificationParams = NotificationParams & Task; + + /** + * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. + * + * @category `notifications/tasks/status` + */ + export interface TaskStatusNotification extends JSONRPCNotification { + method: "notifications/tasks/status"; + params: TaskStatusNotificationParams; + } + + /* Logging */ + + /** + * 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 {@link LoggingMessageNotification | notifications/message}. + */ + level: LoggingLevel; + } + + /** + * 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 { + method: "logging/setLevel"; + 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 { + /** + * The severity of this log message. + */ + level: LoggingLevel; + /** + * An optional name of the logger issuing this message. + */ + logger?: string; + /** + * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. + */ + data: unknown; + } + + /** + * 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` + */ + export interface LoggingMessageNotification extends JSONRPCNotification { + method: "notifications/message"; + params: LoggingMessageNotificationParams; + } + + /** + * The severity of a log message. + * + * These map to syslog message severities, as specified in RFC-5424: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * + * @category Common Types + */ + export type LoggingLevel = + | "debug" + | "info" + | "notice" + | "warning" + | "error" + | "critical" + | "alert" + | "emergency"; + + /* Sampling */ + /** + * 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 { + messages: SamplingMessage[]; + /** + * The server's preferences for which model to select. The client MAY ignore these preferences. + */ + modelPreferences?: ModelPreferences; + /** + * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. + */ + systemPrompt?: string; + /** + * 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 {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases. + */ + includeContext?: "none" | "thisServer" | "allServers"; + /** + * @TJS-type number + */ + temperature?: number; + /** + * The requested maximum number of tokens to sample (to prevent runaway completions). + * + * The client MAY choose to sample fewer tokens than the requested maximum. + */ + maxTokens: number; + stopSequences?: string[]; + /** + * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. + */ + metadata?: object; + /** + * Tools that the model may use during generation. + * 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 {@link ClientCapabilities.sampling.tools} is not declared. + * Default is `{ mode: "auto" }`. + */ + toolChoice?: ToolChoice; + } + + /** + * Controls tool selection behavior for sampling requests. + * + * @category `sampling/createMessage` + */ + 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 + */ + mode?: "auto" | "required" | "none"; + } + + /** + * 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 { + method: "sampling/createMessage"; + params: CreateMessageRequestParams; + } + + /** + * 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 { + /** + * The name of the model that generated the message. + */ + model: string; + + /** + * 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 + * + * 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[]; + _meta?: MetaObject; + } + + /** + * @category `sampling/createMessage` + */ + export type SamplingMessageContentBlock = + | TextContent + | ImageContent + | AudioContent + | ToolUseContent + | ToolResultContent; + + /** + * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed + * + * @category Common Types + */ + export interface Annotations { + /** + * Describes who the intended audience of this object or data is. + * + * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). + */ + audience?: Role[]; + + /** + * Describes how important this data is for operating the server. + * + * A value of 1 means "most important," and indicates that the data is + * effectively required, while 0 means "least important," and indicates that + * the data is entirely optional. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + priority?: number; + + /** + * The moment the resource was last modified, as an ISO 8601 formatted string. + * + * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). + * + * Examples: last activity timestamp in an open file, timestamp when the resource + * was attached, etc. + */ + lastModified?: string; + } + + /** + * @category Content + */ + export type ContentBlock = + | TextContent + | ImageContent + | AudioContent + | ResourceLink + | EmbeddedResource; + + /** + * Text provided to or from an LLM. + * + * @example Text content + * {@includeCode ./examples/TextContent/text-content.json} + * + * @category Content + */ + export interface TextContent { + type: "text"; + + /** + * The text content of the message. + */ + text: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _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 { + type: "image"; + + /** + * The base64-encoded image data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the image. Different providers may support different image types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _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 { + type: "audio"; + + /** + * The base64-encoded audio data. + * + * @format byte + */ + data: string; + + /** + * The MIME type of the audio. Different providers may support different audio types. + */ + mimeType: string; + + /** + * Optional annotations for the client. + */ + annotations?: Annotations; + + _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 { + type: "tool_use"; + + /** + * A unique identifier for this tool use. + * + * This ID is used to match tool results to their corresponding tool uses. + */ + id: string; + + /** + * The name of the tool to call. + */ + name: string; + + /** + * The arguments to pass to the tool, conforming to the tool's input schema. + */ + input: { [key: string]: unknown }; + + /** + * Optional metadata about the tool use. Clients SHOULD preserve this field when + * including tool uses in subsequent sampling requests to enable caching optimizations. + */ + _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 { + type: "tool_result"; + + /** + * The ID of the tool use this result corresponds to. + * + * 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 {@link CallToolResult.content} and can include text, images, + * audio, resource links, and embedded resources. + */ + content: ContentBlock[]; + + /** + * An optional structured result object. + * + * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema. + */ + structuredContent?: { [key: string]: unknown }; + + /** + * Whether the tool use resulted in an error. + * + * If true, the content typically describes the error that occurred. + * Default: false + */ + isError?: boolean; + + /** + * Optional metadata about the tool result. Clients SHOULD preserve this field when + * including tool results in subsequent sampling requests to enable caching optimizations. + */ + _meta?: MetaObject; + } + + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * Because LLMs can vary along multiple dimensions, choosing the "best" model is + * rarely straightforward. Different models excel in different areas-some are + * faster but less capable, others are more capable but more expensive, and so + * on. This interface allows servers to express their priorities across multiple + * dimensions to help clients make an appropriate selection for their use case. + * + * These preferences are always advisory. The client MAY ignore them. It is also + * 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 { + /** + * Optional hints to use for model selection. + * + * If multiple hints are specified, the client MUST evaluate them in order + * (such that the first match is taken). + * + * The client SHOULD prioritize these hints over the numeric priorities, but + * MAY still use the priorities to select from ambiguous matches. + */ + hints?: ModelHint[]; + + /** + * How much to prioritize cost when selecting a model. A value of 0 means cost + * is not important, while a value of 1 means cost is the most important + * factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + costPriority?: number; + + /** + * How much to prioritize sampling speed (latency) when selecting a model. A + * value of 0 means speed is not important, while a value of 1 means speed is + * the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + speedPriority?: number; + + /** + * How much to prioritize intelligence and capabilities when selecting a + * model. A value of 0 means intelligence is not important, while a value of 1 + * means intelligence is the most important factor. + * + * @TJS-type number + * @minimum 0 + * @maximum 1 + */ + intelligencePriority?: number; + } + + /** + * Hints to use for model selection. + * + * Keys not declared here are currently left unspecified by the spec and are up + * to the client to interpret. + * + * @category `sampling/createMessage` + */ + export interface ModelHint { + /** + * A hint for a model name. + * + * The client SHOULD treat this as a substring of a model name; for example: + * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` + * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. + * - `claude` should match any Claude model + * + * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: + * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` + */ + name?: string; + } + + /* Autocomplete */ + /** + * 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; + /** + * The argument's information + */ + argument: { + /** + * The name of the argument + */ + name: string; + /** + * The value of the argument to use for completion matching. + */ + value: string; + }; + + /** + * Additional, optional context for completions + */ + context?: { + /** + * Previously-resolved variables in a URI template or prompt. + */ + arguments?: { [key: string]: string }; + }; + } + + /** + * 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 { + method: "completion/complete"; + params: CompleteRequestParams; + } + + /** + * 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: { + /** + * An array of completion values. Must not exceed 100 items. + */ + values: string[]; + /** + * The total number of completion options available. This can exceed the number of values actually sent in the response. + */ + total?: number; + /** + * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. + */ + hasMore?: boolean; + }; + } + + /** + * 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. + * + * @category `completion/complete` + */ + export interface ResourceTemplateReference { + type: "ref/resource"; + /** + * The URI or URI template of the resource. + * + * @format uri-template + */ + uri: string; + } + + /** + * Identifies a prompt. + * + * @category `completion/complete` + */ + export interface PromptReference extends BaseMetadata { + type: "ref/prompt"; + } + + /* Roots */ + /** + * Sent from the server to request a list of root URIs from the client. Roots allow + * servers to ask for specific directories or files to operate on. A common example + * for roots is providing a set of repositories or directories a server should operate + * on. + * + * 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 { + method: "roots/list"; + params?: RequestParams; + } + + /** + * 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. + * This restriction may be relaxed in future versions of the protocol to allow + * other URI schemes. + * + * @format uri + */ + uri: string; + /** + * An optional name for the root. This can be used to provide a human-readable + * identifier for the root, which may be useful for display purposes or for + * referencing the root in other parts of the application. + */ + name?: string; + + _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 {@link ListRootsRequest}. + * + * @example Roots list changed + * {@includeCode ./examples/RootsListChangedNotification/roots-list-changed.json} + * + * @category `notifications/roots/list_changed` + */ + export interface RootsListChangedNotification extends JSONRPCNotification { + method: "notifications/roots/list_changed"; + params?: NotificationParams; + } + + /** + * 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 { + /** + * The elicitation mode. + */ + mode?: "form"; + + /** + * The message to present to the user describing what information is being requested. + */ + message: string; + + /** + * A restricted subset of JSON Schema. + * Only top-level properties are allowed, without nesting. + */ + requestedSchema: { + $schema?: string; + type: "object"; + properties: { + [key: string]: PrimitiveSchemaDefinition; + }; + required?: string[]; + }; + } + + /** + * 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 { + /** + * The elicitation mode. + */ + mode: "url"; + + /** + * The message to present to the user explaining why the interaction is needed. + */ + message: string; + + /** + * The ID of the elicitation, which must be unique within the context of the server. + * The client MUST treat this ID as an opaque value. + */ + elicitationId: string; + + /** + * The URL that the user should navigate to. + * + * @format uri + */ + url: string; + } + + /** + * The parameters for a request to elicit additional information from the user via the client. + * + * @category `elicitation/create` + */ + export type ElicitRequestParams = + | ElicitRequestFormParams + | ElicitRequestURLParams; + + /** + * 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 { + method: "elicitation/create"; + params: ElicitRequestParams; + } + + /** + * Restricted schema definitions that only allow primitive types + * without nested objects or arrays. + * + * @category `elicitation/create` + */ + export type PrimitiveSchemaDefinition = + | StringSchema + | NumberSchema + | BooleanSchema + | EnumSchema; + + /** + * @example Email input schema + * {@includeCode ./examples/StringSchema/email-input-schema.json} + * + * @category `elicitation/create` + */ + export interface StringSchema { + type: "string"; + title?: string; + description?: string; + minLength?: number; + maxLength?: number; + format?: "email" | "uri" | "date" | "date-time"; + default?: string; + } + + /** + * @example Number input schema + * {@includeCode ./examples/NumberSchema/number-input-schema.json} + * + * @category `elicitation/create` + */ + export interface NumberSchema { + type: "number" | "integer"; + title?: string; + description?: string; + minimum?: number; + maximum?: number; + default?: number; + } + + /** + * @example Boolean input schema + * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json} + * + * @category `elicitation/create` + */ + export interface BooleanSchema { + type: "boolean"; + title?: string; + description?: string; + default?: boolean; + } + + /** + * 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 { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum values to choose from. + */ + enum: string[]; + /** + * Optional default value. + */ + default?: string; + } + + /** + * 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 { + type: "string"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Array of enum options with values and display labels. + */ + oneOf: Array<{ + /** + * The enum value. + */ + const: string; + /** + * Display label for this option. + */ + title: string; + }>; + /** + * Optional default value. + */ + default?: string; + } + + /** + * @category `elicitation/create` + */ + // Combined single selection enumeration + export type SingleSelectEnumSchema = + | UntitledSingleSelectEnumSchema + | TitledSingleSelectEnumSchema; + + /** + * 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 { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for the array items. + */ + items: { + type: "string"; + /** + * Array of enum values to choose from. + */ + enum: string[]; + }; + /** + * Optional default value. + */ + default?: string[]; + } + + /** + * 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 { + type: "array"; + /** + * Optional title for the enum field. + */ + title?: string; + /** + * Optional description for the enum field. + */ + description?: string; + /** + * Minimum number of items to select. + */ + minItems?: number; + /** + * Maximum number of items to select. + */ + maxItems?: number; + /** + * Schema for array items with enum options and display labels. + */ + items: { + /** + * Array of enum options with values and display labels. + */ + anyOf: Array<{ + /** + * The constant enum value. + */ + const: string; + /** + * Display title for this option. + */ + title: string; + }>; + }; + /** + * Optional default value. + */ + default?: string[]; + } + + /** + * @category `elicitation/create` + */ + // Combined multiple selection enumeration + export type MultiSelectEnumSchema = + | UntitledMultiSelectEnumSchema + | TitledMultiSelectEnumSchema; + + /** + * Use {@link TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + * + * @category `elicitation/create` + */ + export interface LegacyTitledEnumSchema { + type: "string"; + title?: string; + description?: string; + enum: string[]; + /** + * (Legacy) Display names for enum values. + * Non-standard according to JSON schema 2020-12. + */ + enumNames?: string[]; + default?: string; + } + + /** + * @category `elicitation/create` + */ + // Union type for all enum schemas + export type EnumSchema = + | SingleSelectEnumSchema + | MultiSelectEnumSchema + | LegacyTitledEnumSchema; + + /** + * 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 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"`. + * 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 { + method: "notifications/elicitation/complete"; + params: { + /** + * The ID of the elicitation that completed. + */ + elicitationId: string; + }; + } + + /* Client messages */ + /** @internal */ + export type ClientRequest = + | PingRequest + | InitializeRequest + | CompleteRequest + | SetLevelRequest + | GetPromptRequest + | ListPromptsRequest + | ListResourcesRequest + | ListResourceTemplatesRequest + | ReadResourceRequest + | SubscribeRequest + | UnsubscribeRequest + | CallToolRequest + | ListToolsRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + + /** @internal */ + export type ClientNotification = + | CancelledNotification + | ProgressNotification + | InitializedNotification + | RootsListChangedNotification + | TaskStatusNotification; + + /** @internal */ + export type ClientResult = + | EmptyResult + | CreateMessageResult + | ListRootsResult + | ElicitResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; + + /* Server messages */ + /** @internal */ + export type ServerRequest = + | PingRequest + | CreateMessageRequest + | ListRootsRequest + | ElicitRequest + | GetTaskRequest + | GetTaskPayloadRequest + | ListTasksRequest + | CancelTaskRequest; + + /** @internal */ + export type ServerNotification = + | CancelledNotification + | ProgressNotification + | LoggingMessageNotification + | ResourceUpdatedNotification + | ResourceListChangedNotification + | ToolListChangedNotification + | PromptListChangedNotification + | ElicitationCompleteNotification + | TaskStatusNotification; + + /** @internal */ + export type ServerResult = + | EmptyResult + | InitializeResult + | CompleteResult + | GetPromptResult + | ListPromptsResult + | ListResourceTemplatesResult + | ListResourcesResult + | ReadResourceResult + | CallToolResult + | CreateTaskResult + | ListToolsResult + | GetTaskResult + | GetTaskPayloadResult + | ListTasksResult + | CancelTaskResult; +} diff --git a/src/vs/platform/mcp/common/modelContextProtocolApps.ts b/src/vs/platform/mcp/common/modelContextProtocolApps.ts new file mode 100644 index 0000000000000..4569e8f25ac8d --- /dev/null +++ b/src/vs/platform/mcp/common/modelContextProtocolApps.ts @@ -0,0 +1,737 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { MCP } from './modelContextProtocol.js'; + +type CallToolResult = MCP.CallToolResult; +type ContentBlock = MCP.ContentBlock; +type Implementation = MCP.Implementation; +type RequestId = MCP.RequestId; +type Tool = MCP.Tool; + +export namespace McpApps { + export type AppRequest = + | MCP.CallToolRequest + | MCP.ReadResourceRequest + | MCP.PingRequest + | (McpUiOpenLinkRequest & MCP.JSONRPCRequest) + | (McpUiUpdateModelContextRequest & MCP.JSONRPCRequest) + | (McpUiMessageRequest & MCP.JSONRPCRequest) + | (McpUiRequestDisplayModeRequest & MCP.JSONRPCRequest) + | (McpApps.McpUiInitializeRequest & MCP.JSONRPCRequest); + + export type AppNotification = + | McpUiInitializedNotification + | McpUiSizeChangedNotification + | MCP.LoggingMessageNotification + | CustomSandboxWheelNotification; + + export type AppMessage = AppRequest | AppNotification; + + export type HostResult = + | MCP.CallToolResult + | MCP.ReadResourceResult + | MCP.EmptyResult + | McpApps.McpUiInitializeResult + | McpUiMessageResult + | McpUiOpenLinkResult + | McpUiRequestDisplayModeResult; + + export type HostNotification = + | McpUiHostContextChangedNotification + | McpUiResourceTeardownRequest + | McpUiToolInputNotification + | McpUiToolInputPartialNotification + | McpUiToolResultNotification + | McpUiToolCancelledNotification + | McpUiSizeChangedNotification; + + export type HostMessage = HostResult | HostNotification; + + + /** Custom notification used for bubbling up sandbox wheel events. */ + export interface CustomSandboxWheelNotification { + method: 'ui/notifications/sandbox-wheel'; + params: { + deltaMode: number; + deltaX: number; + deltaY: number; + deltaZ: number; + }; + } +} + +/* eslint-disable local/code-no-unexternalized-strings */ + + +/** + * Schema updated from the Model Context Protocol Apps repository at + * https://github.com/modelcontextprotocol/ext-apps/blob/main/src/spec.types.ts + * + * ⚠️ Do not edit within `namespace` manually except to update schema versions ⚠️ + */ +export namespace McpApps { + /** + * Current protocol version supported by this SDK. + * + * The SDK automatically handles version negotiation during initialization. + * Apps and hosts don't need to manage protocol versions manually. + */ + export const LATEST_PROTOCOL_VERSION = "2026-01-26"; + + /** + * @description Color theme preference for the host environment. + */ + export type McpUiTheme = "light" | "dark"; + + /** + * @description Display mode for UI presentation. + */ + export type McpUiDisplayMode = "inline" | "fullscreen" | "pip"; + + /** + * @description CSS variable keys available to MCP apps for theming. + */ + export type McpUiStyleVariableKey = + // Background colors + | "--color-background-primary" + | "--color-background-secondary" + | "--color-background-tertiary" + | "--color-background-inverse" + | "--color-background-ghost" + | "--color-background-info" + | "--color-background-danger" + | "--color-background-success" + | "--color-background-warning" + | "--color-background-disabled" + // Text colors + | "--color-text-primary" + | "--color-text-secondary" + | "--color-text-tertiary" + | "--color-text-inverse" + | "--color-text-ghost" + | "--color-text-info" + | "--color-text-danger" + | "--color-text-success" + | "--color-text-warning" + | "--color-text-disabled" + | "--color-text-ghost" + // Border colors + | "--color-border-primary" + | "--color-border-secondary" + | "--color-border-tertiary" + | "--color-border-inverse" + | "--color-border-ghost" + | "--color-border-info" + | "--color-border-danger" + | "--color-border-success" + | "--color-border-warning" + | "--color-border-disabled" + // Ring colors + | "--color-ring-primary" + | "--color-ring-secondary" + | "--color-ring-inverse" + | "--color-ring-info" + | "--color-ring-danger" + | "--color-ring-success" + | "--color-ring-warning" + // Typography - Family + | "--font-sans" + | "--font-mono" + // Typography - Weight + | "--font-weight-normal" + | "--font-weight-medium" + | "--font-weight-semibold" + | "--font-weight-bold" + // Typography - Text Size + | "--font-text-xs-size" + | "--font-text-sm-size" + | "--font-text-md-size" + | "--font-text-lg-size" + // Typography - Heading Size + | "--font-heading-xs-size" + | "--font-heading-sm-size" + | "--font-heading-md-size" + | "--font-heading-lg-size" + | "--font-heading-xl-size" + | "--font-heading-2xl-size" + | "--font-heading-3xl-size" + // Typography - Text Line Height + | "--font-text-xs-line-height" + | "--font-text-sm-line-height" + | "--font-text-md-line-height" + | "--font-text-lg-line-height" + // Typography - Heading Line Height + | "--font-heading-xs-line-height" + | "--font-heading-sm-line-height" + | "--font-heading-md-line-height" + | "--font-heading-lg-line-height" + | "--font-heading-xl-line-height" + | "--font-heading-2xl-line-height" + | "--font-heading-3xl-line-height" + // Border radius + | "--border-radius-xs" + | "--border-radius-sm" + | "--border-radius-md" + | "--border-radius-lg" + | "--border-radius-xl" + | "--border-radius-full" + // Border width + | "--border-width-regular" + // Shadows + | "--shadow-hairline" + | "--shadow-sm" + | "--shadow-md" + | "--shadow-lg"; + + /** + * @description Style variables for theming MCP apps. + * + * Individual style keys are optional - hosts may provide any subset of these values. + * Values are strings containing CSS values (colors, sizes, font stacks, etc.). + * + * Note: This type uses `Record` rather than `Partial>` + * for compatibility with Zod schema generation. Both are functionally equivalent for validation. + */ + export type McpUiStyles = Record; + + /** + * @description Request to open an external URL in the host's default browser. + * @see {@link app.App.sendOpenLink} for the method that sends this request + */ + export interface McpUiOpenLinkRequest { + method: "ui/open-link"; + params: { + /** @description URL to open in the host's browser */ + url: string; + }; + } + + /** + * @description Result from opening a URL. + * @see {@link McpUiOpenLinkRequest} + */ + export interface McpUiOpenLinkResult { + /** @description True if the host failed to open the URL (e.g., due to security policy). */ + isError?: boolean; + /** + * Index signature required for MCP SDK `Protocol` class compatibility. + * Note: The schema intentionally omits this to enforce strict validation. + */ + [key: string]: unknown; + } + + /** + * @description Request to send a message to the host's chat interface. + * @see {@link app.App.sendMessage} for the method that sends this request + */ + export interface McpUiMessageRequest { + method: "ui/message"; + params: { + /** @description Message role, currently only "user" is supported. */ + role: "user"; + /** @description Message content blocks (text, image, etc.). */ + content: ContentBlock[]; + }; + } + + /** + * @description Result from sending a message. + * @see {@link McpUiMessageRequest} + */ + export interface McpUiMessageResult { + /** @description True if the host rejected or failed to deliver the message. */ + isError?: boolean; + /** + * Index signature required for MCP SDK `Protocol` class compatibility. + * Note: The schema intentionally omits this to enforce strict validation. + */ + [key: string]: unknown; + } + + /** + * @description Notification that the sandbox proxy iframe is ready to receive content. + * @internal + * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#sandbox-proxy + */ + export interface McpUiSandboxProxyReadyNotification { + method: "ui/notifications/sandbox-proxy-ready"; + params: {}; + } + + /** + * @description Notification containing HTML resource for the sandbox proxy to load. + * @internal + * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#sandbox-proxy + */ + export interface McpUiSandboxResourceReadyNotification { + method: "ui/notifications/sandbox-resource-ready"; + params: { + /** @description HTML content to load into the inner iframe. */ + html: string; + /** @description Optional override for the inner iframe's sandbox attribute. */ + sandbox?: string; + /** @description CSP configuration from resource metadata. */ + csp?: McpUiResourceCsp; + /** @description Sandbox permissions from resource metadata. */ + permissions?: McpUiResourcePermissions; + }; + } + + /** + * @description Notification of UI size changes (bidirectional: Guest <-> Host). + * @see {@link app.App.sendSizeChanged} for the method to send this from Guest UI + */ + export interface McpUiSizeChangedNotification { + method: "ui/notifications/size-changed"; + params: { + /** @description New width in pixels. */ + width?: number; + /** @description New height in pixels. */ + height?: number; + }; + } + + /** + * @description Notification containing complete tool arguments (Host -> Guest UI). + */ + export interface McpUiToolInputNotification { + method: "ui/notifications/tool-input"; + params: { + /** @description Complete tool call arguments as key-value pairs. */ + arguments?: Record; + }; + } + + /** + * @description Notification containing partial/streaming tool arguments (Host -> Guest UI). + */ + export interface McpUiToolInputPartialNotification { + method: "ui/notifications/tool-input-partial"; + params: { + /** @description Partial tool call arguments (incomplete, may change). */ + arguments?: Record; + }; + } + + /** + * @description Notification containing tool execution result (Host -> Guest UI). + */ + export interface McpUiToolResultNotification { + method: "ui/notifications/tool-result"; + /** @description Standard MCP tool execution result. */ + params: CallToolResult; + } + + /** + * @description Notification that tool execution was cancelled (Host -> Guest UI). + * Host MUST send this if tool execution was cancelled for any reason (user action, + * sampling error, classifier intervention, etc.). + */ + export interface McpUiToolCancelledNotification { + method: "ui/notifications/tool-cancelled"; + params: { + /** @description Optional reason for the cancellation (e.g., "user action", "timeout"). */ + reason?: string; + }; + } + + /** + * @description CSS blocks that can be injected by apps. + */ + export interface McpUiHostCss { + /** @description CSS for font loading (@font-face rules or @import statements). Apps must apply using applyHostFonts(). */ + fonts?: string; + } + + /** + * @description Style configuration for theming MCP apps. + */ + export interface McpUiHostStyles { + /** @description CSS variables for theming the app. */ + variables?: McpUiStyles; + /** @description CSS blocks that apps can inject. */ + css?: McpUiHostCss; + } + + /** + * @description Rich context about the host environment provided to Guest UIs. + */ + export interface McpUiHostContext { + /** @description Allow additional properties for forward compatibility. */ + [key: string]: unknown; + /** @description Metadata of the tool call that instantiated this App. */ + toolInfo?: { + /** @description JSON-RPC id of the tools/call request. */ + id?: RequestId; + /** @description Tool definition including name, inputSchema, etc. */ + tool: Tool; + }; + /** @description Current color theme preference. */ + theme?: McpUiTheme; + /** @description Style configuration for theming the app. */ + styles?: McpUiHostStyles; + /** @description How the UI is currently displayed. */ + displayMode?: McpUiDisplayMode; + /** @description Display modes the host supports. */ + availableDisplayModes?: string[]; + /** + * @description Container dimensions. Represents the dimensions of the iframe or other + * container holding the app. Specify either width or maxWidth, and either height or maxHeight. + */ + containerDimensions?: ( + | { + /** @description Fixed container height in pixels. */ + height: number; + } + | { + /** @description Maximum container height in pixels. */ + maxHeight?: number | undefined; + } + ) & + ( + | { + /** @description Fixed container width in pixels. */ + width: number; + } + | { + /** @description Maximum container width in pixels. */ + maxWidth?: number | undefined; + } + ); + /** @description User's language and region preference in BCP 47 format. */ + locale?: string; + /** @description User's timezone in IANA format. */ + timeZone?: string; + /** @description Host application identifier. */ + userAgent?: string; + /** @description Platform type for responsive design decisions. */ + platform?: "web" | "desktop" | "mobile"; + /** @description Device input capabilities. */ + deviceCapabilities?: { + /** @description Whether the device supports touch input. */ + touch?: boolean; + /** @description Whether the device supports hover interactions. */ + hover?: boolean; + }; + /** @description Mobile safe area boundaries in pixels. */ + safeAreaInsets?: { + /** @description Top safe area inset in pixels. */ + top: number; + /** @description Right safe area inset in pixels. */ + right: number; + /** @description Bottom safe area inset in pixels. */ + bottom: number; + /** @description Left safe area inset in pixels. */ + left: number; + }; + } + + /** + * @description Notification that host context has changed (Host -> Guest UI). + * @see {@link McpUiHostContext} for the full context structure + */ + export interface McpUiHostContextChangedNotification { + method: "ui/notifications/host-context-changed"; + /** @description Partial context update containing only changed fields. */ + params: McpUiHostContext; + } + + /** + * @description Request to update the agent's context without requiring a follow-up action (Guest UI -> Host). + * + * Unlike `notifications/message` which is for debugging/logging, this request is intended + * to update the Host's model context. Each request overwrites the previous context sent by the Guest UI. + * Unlike messages, context updates do not trigger follow-ups. + * + * The host will typically defer sending the context to the model until the next user message + * (including `ui/message`), and will only send the last update received. + * + * @see {@link app.App.updateModelContext} for the method that sends this request + */ + export interface McpUiUpdateModelContextRequest { + method: "ui/update-model-context"; + params: { + /** @description Context content blocks (text, image, etc.). */ + content?: ContentBlock[]; + /** @description Structured content for machine-readable context data. */ + structuredContent?: Record; + }; + } + + /** + * @description Request for graceful shutdown of the Guest UI (Host -> Guest UI). + * @see {@link app-bridge.AppBridge.teardownResource} for the host method that sends this + */ + export interface McpUiResourceTeardownRequest { + method: "ui/resource-teardown"; + params: {}; + } + + /** + * @description Result from graceful shutdown request. + * @see {@link McpUiResourceTeardownRequest} + */ + export interface McpUiResourceTeardownResult { + /** + * Index signature required for MCP SDK `Protocol` class compatibility. + */ + [key: string]: unknown; + } + + export interface McpUiSupportedContentBlockModalities { + /** @description Host supports text content blocks. */ + text?: {}; + /** @description Host supports image content blocks. */ + image?: {}; + /** @description Host supports audio content blocks. */ + audio?: {}; + /** @description Host supports resource content blocks. */ + resource?: {}; + /** @description Host supports resource link content blocks. */ + resourceLink?: {}; + /** @description Host supports structured content. */ + structuredContent?: {}; + } + + /** + * @description Capabilities supported by the host application. + * @see {@link McpUiInitializeResult} for the initialization result that includes these capabilities + */ + export interface McpUiHostCapabilities { + /** @description Experimental features (structure TBD). */ + experimental?: {}; + /** @description Host supports opening external URLs. */ + openLinks?: {}; + /** @description Host can proxy tool calls to the MCP server. */ + serverTools?: { + /** @description Host supports tools/list_changed notifications. */ + listChanged?: boolean; + }; + /** @description Host can proxy resource reads to the MCP server. */ + serverResources?: { + /** @description Host supports resources/list_changed notifications. */ + listChanged?: boolean; + }; + /** @description Host accepts log messages. */ + logging?: {}; + /** @description Sandbox configuration applied by the host. */ + sandbox?: { + /** @description Permissions granted by the host (camera, microphone, geolocation). */ + permissions?: McpUiResourcePermissions; + /** @description CSP domains approved by the host. */ + csp?: McpUiResourceCsp; + }; + /** @description Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns. */ + updateModelContext?: McpUiSupportedContentBlockModalities; + /** @description Host supports receiving content messages (ui/message) from the View. */ + message?: McpUiSupportedContentBlockModalities; + } + + /** + * @description Capabilities provided by the View (App). + * @see {@link McpUiInitializeRequest} for the initialization request that includes these capabilities + */ + export interface McpUiAppCapabilities { + /** @description Experimental features (structure TBD). */ + experimental?: {}; + /** @description App exposes MCP-style tools that the host can call. */ + tools?: { + /** @description App supports tools/list_changed notifications. */ + listChanged?: boolean; + }; + /** + * @description Display modes the app supports. See Display Modes section of the spec for details. + * @example ["inline", "fullscreen"] + */ + availableDisplayModes?: McpUiDisplayMode[]; + } + + /** + * @description Initialization request sent from Guest UI to Host. + * @see {@link app.App.connect} for the method that sends this request + */ + export interface McpUiInitializeRequest { + method: "ui/initialize"; + params: { + /** @description App identification (name and version). */ + appInfo: Implementation; + /** @description Features and capabilities this app provides. */ + appCapabilities: McpUiAppCapabilities; + /** @description Protocol version this app supports. */ + protocolVersion: string; + }; + } + + /** + * @description Initialization result returned from Host to Guest UI. + * @see {@link McpUiInitializeRequest} + */ + export interface McpUiInitializeResult { + /** @description Negotiated protocol version string (e.g., "2025-11-21"). */ + protocolVersion: string; + /** @description Host application identification and version. */ + hostInfo: Implementation; + /** @description Features and capabilities provided by the host. */ + hostCapabilities: McpUiHostCapabilities; + /** @description Rich context about the host environment. */ + hostContext: McpUiHostContext; + /** + * Index signature required for MCP SDK `Protocol` class compatibility. + * Note: The schema intentionally omits this to enforce strict validation. + */ + [key: string]: unknown; + } + + /** + * @description Notification that Guest UI has completed initialization (Guest UI -> Host). + * @see {@link app.App.connect} for the method that sends this notification + */ + export interface McpUiInitializedNotification { + method: "ui/notifications/initialized"; + params?: {}; + } + + /** + * @description Content Security Policy configuration for UI resources. + */ + export interface McpUiResourceCsp { + /** @description Origins for network requests (fetch/XHR/WebSocket). */ + connectDomains?: string[]; + /** @description Origins for static resources (scripts, images, styles, fonts). */ + resourceDomains?: string[]; + /** @description Origins for nested iframes (frame-src directive). */ + frameDomains?: string[]; + /** @description Allowed base URIs for the document (base-uri directive). */ + baseUriDomains?: string[]; + } + + /** + * @description Sandbox permissions requested by the UI resource. + * Hosts MAY honor these by setting appropriate iframe `allow` attributes. + * Apps SHOULD NOT assume permissions are granted; use JS feature detection as fallback. + */ + export interface McpUiResourcePermissions { + /** @description Request camera access (Permission Policy `camera` feature). */ + camera?: {}; + /** @description Request microphone access (Permission Policy `microphone` feature). */ + microphone?: {}; + /** @description Request geolocation access (Permission Policy `geolocation` feature). */ + geolocation?: {}; + /** @description Request clipboard write access (Permission Policy `clipboard-write` feature). */ + clipboardWrite?: {}; + } + + /** + * @description UI Resource metadata for security and rendering configuration. + */ + export interface McpUiResourceMeta { + /** @description Content Security Policy configuration. */ + csp?: McpUiResourceCsp; + /** @description Sandbox permissions requested by the UI. */ + permissions?: McpUiResourcePermissions; + /** @description Dedicated origin for widget sandbox. */ + domain?: string; + /** @description Visual boundary preference - true if UI prefers a visible border. */ + prefersBorder?: boolean; + } + + /** + * @description Request to change the display mode of the UI. + * The host will respond with the actual display mode that was set, + * which may differ from the requested mode if not supported. + * @see {@link app.App.requestDisplayMode} for the method that sends this request + */ + export interface McpUiRequestDisplayModeRequest { + method: "ui/request-display-mode"; + params: { + /** @description The display mode being requested. */ + mode: McpUiDisplayMode; + }; + } + + /** + * @description Result from requesting a display mode change. + * @see {@link McpUiRequestDisplayModeRequest} + */ + export interface McpUiRequestDisplayModeResult { + /** @description The display mode that was actually set. May differ from requested if not supported. */ + mode: McpUiDisplayMode; + /** + * Index signature required for MCP SDK `Protocol` class compatibility. + * Note: The schema intentionally omits this to enforce strict validation. + */ + [key: string]: unknown; + } + + /** + * @description Tool visibility scope - who can access the tool. + */ + export type McpUiToolVisibility = "model" | "app"; + + /** + * @description UI-related metadata for tools. + */ + export interface McpUiToolMeta { + /** + * URI of the UI resource to display for this tool, if any. + * This is converted to `_meta["ui/resourceUri"]`. + * + * @example "ui://weather/widget.html" + */ + resourceUri?: string; + /** + * @description Who can access this tool. Default: ["model", "app"] + * - "model": Tool visible to and callable by the agent + * - "app": Tool callable by the app from this server only + */ + visibility?: McpUiToolVisibility[]; + } + + /** + * Method string constants for MCP Apps protocol messages. + * + * These constants provide a type-safe way to check message methods without + * accessing internal Zod schema properties. External libraries should use + * these constants instead of accessing `schema.shape.method._def.values[0]`. + * + * @example + * ```typescript + * import { SANDBOX_PROXY_READY_METHOD } from '@modelcontextprotocol/ext-apps'; + * + * if (event.data.method === SANDBOX_PROXY_READY_METHOD) { + * // Handle sandbox proxy ready notification + * } + * ``` + */ + export const OPEN_LINK_METHOD: McpUiOpenLinkRequest["method"] = "ui/open-link"; + export const MESSAGE_METHOD: McpUiMessageRequest["method"] = "ui/message"; + export const SANDBOX_PROXY_READY_METHOD: McpUiSandboxProxyReadyNotification["method"] = + "ui/notifications/sandbox-proxy-ready"; + export const SANDBOX_RESOURCE_READY_METHOD: McpUiSandboxResourceReadyNotification["method"] = + "ui/notifications/sandbox-resource-ready"; + export const SIZE_CHANGED_METHOD: McpUiSizeChangedNotification["method"] = + "ui/notifications/size-changed"; + export const TOOL_INPUT_METHOD: McpUiToolInputNotification["method"] = + "ui/notifications/tool-input"; + export const TOOL_INPUT_PARTIAL_METHOD: McpUiToolInputPartialNotification["method"] = + "ui/notifications/tool-input-partial"; + export const TOOL_RESULT_METHOD: McpUiToolResultNotification["method"] = + "ui/notifications/tool-result"; + export const TOOL_CANCELLED_METHOD: McpUiToolCancelledNotification["method"] = + "ui/notifications/tool-cancelled"; + export const HOST_CONTEXT_CHANGED_METHOD: McpUiHostContextChangedNotification["method"] = + "ui/notifications/host-context-changed"; + export const RESOURCE_TEARDOWN_METHOD: McpUiResourceTeardownRequest["method"] = + "ui/resource-teardown"; + export const INITIALIZE_METHOD: McpUiInitializeRequest["method"] = + "ui/initialize"; + export const INITIALIZED_METHOD: McpUiInitializedNotification["method"] = + "ui/notifications/initialized"; + export const REQUEST_DISPLAY_MODE_METHOD: McpUiRequestDisplayModeRequest["method"] = + "ui/request-display-mode"; + export const UPDATE_MODEL_CONTEXT_METHOD: McpUiUpdateModelContextRequest["method"] = + "ui/update-model-context"; +} diff --git a/src/vs/platform/mcp/electron-main/mcpGatewayMainChannel.ts b/src/vs/platform/mcp/electron-main/mcpGatewayMainChannel.ts deleted file mode 100644 index 8c6c30ed144d7..0000000000000 --- a/src/vs/platform/mcp/electron-main/mcpGatewayMainChannel.ts +++ /dev/null @@ -1,45 +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 { Event } from '../../../base/common/event.js'; -import { Disposable } from '../../../base/common/lifecycle.js'; -import { IPCServer, IServerChannel } from '../../../base/parts/ipc/common/ipc.js'; -import { IMcpGatewayService } from '../common/mcpGateway.js'; - -/** - * IPC channel for the MCP Gateway service in the electron-main process. - * - * This channel tracks which client (identified by ctx) creates gateways, - * enabling cleanup when a client disconnects (e.g., window crash). - */ -export class McpGatewayMainChannel extends Disposable implements IServerChannel { - - constructor( - ipcServer: IPCServer, - @IMcpGatewayService private readonly mcpGatewayService: IMcpGatewayService - ) { - super(); - this._register(ipcServer.onDidRemoveConnection(c => mcpGatewayService.disposeGatewaysForClient(c.ctx))); - } - - listen(_ctx: string, _event: string): Event { - throw new Error('Invalid listen'); - } - - async call(ctx: string, command: string, args?: unknown): Promise { - switch (command) { - case 'createGateway': { - // Use the context (client ID) to track gateway ownership - const result = await this.mcpGatewayService.createGateway(ctx); - return result as T; - } - case 'disposeGateway': { - await this.mcpGatewayService.disposeGateway(args as string); - return undefined as T; - } - } - throw new Error(`Invalid call: ${command}`); - } -} diff --git a/src/vs/platform/mcp/node/mcpGatewayChannel.ts b/src/vs/platform/mcp/node/mcpGatewayChannel.ts index 5c0fefefe33a8..d8a976f3308a2 100644 --- a/src/vs/platform/mcp/node/mcpGatewayChannel.ts +++ b/src/vs/platform/mcp/node/mcpGatewayChannel.ts @@ -6,7 +6,8 @@ import { Event } from '../../../base/common/event.js'; import { Disposable } from '../../../base/common/lifecycle.js'; import { IPCServer, IServerChannel } from '../../../base/parts/ipc/common/ipc.js'; -import { IMcpGatewayService } from '../common/mcpGateway.js'; +import { IMcpGatewayService, McpGatewayToolBrokerChannelName } from '../common/mcpGateway.js'; +import { MCP } from '../common/modelContextProtocol.js'; /** * IPC channel for the MCP Gateway service, used by the remote server. @@ -17,11 +18,11 @@ import { IMcpGatewayService } from '../common/mcpGateway.js'; export class McpGatewayChannel extends Disposable implements IServerChannel { constructor( - ipcServer: IPCServer, + private readonly _ipcServer: IPCServer, @IMcpGatewayService private readonly mcpGatewayService: IMcpGatewayService ) { super(); - this._register(ipcServer.onDidRemoveConnection(c => mcpGatewayService.disposeGatewaysForClient(c.ctx))); + this._register(_ipcServer.onDidRemoveConnection(c => mcpGatewayService.disposeGatewaysForClient(c.ctx))); } listen(_ctx: TContext, _event: string): Event { @@ -31,7 +32,12 @@ export class McpGatewayChannel extends Disposable implements IServerCh async call(ctx: TContext, command: string, args?: unknown): Promise { switch (command) { case 'createGateway': { - const result = await this.mcpGatewayService.createGateway(ctx); + const brokerChannel = ipcChannelForContext(this._ipcServer, ctx); + const result = await this.mcpGatewayService.createGateway(ctx, { + onDidChangeTools: brokerChannel.listen('onDidChangeTools'), + listTools: () => brokerChannel.call('listTools'), + callTool: (name, callArgs) => brokerChannel.call('callTool', { name, args: callArgs }), + }); return result as T; } case 'disposeGateway': { @@ -43,3 +49,7 @@ export class McpGatewayChannel extends Disposable implements IServerCh throw new Error(`Invalid call: ${command}`); } } + +function ipcChannelForContext(ipcServer: IPCServer, ctx: TContext) { + return ipcServer.getChannel(McpGatewayToolBrokerChannelName, client => client.ctx === ctx); +} diff --git a/src/vs/platform/mcp/node/mcpGatewayService.ts b/src/vs/platform/mcp/node/mcpGatewayService.ts index f82cac22a63cb..8225b3fffe8c3 100644 --- a/src/vs/platform/mcp/node/mcpGatewayService.ts +++ b/src/vs/platform/mcp/node/mcpGatewayService.ts @@ -5,11 +5,13 @@ import type * as http from 'http'; import { DeferredPromise } from '../../../base/common/async.js'; +import { JsonRpcMessage, JsonRpcProtocol } from '../../../base/common/jsonRpcProtocol.js'; import { Disposable } from '../../../base/common/lifecycle.js'; import { URI } from '../../../base/common/uri.js'; import { generateUuid } from '../../../base/common/uuid.js'; import { ILogService } from '../../log/common/log.js'; -import { IMcpGatewayInfo, IMcpGatewayService } from '../common/mcpGateway.js'; +import { IMcpGatewayInfo, IMcpGatewayService, IMcpGatewayToolInvoker } from '../common/mcpGateway.js'; +import { isInitializeMessage, McpGatewaySession } from './mcpGatewaySession.js'; /** * Node.js implementation of the MCP Gateway Service. @@ -33,7 +35,7 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService super(); } - async createGateway(clientId: unknown): Promise { + async createGateway(clientId: unknown, toolInvoker?: IMcpGatewayToolInvoker): Promise { // Ensure server is running await this._ensureServer(); @@ -45,7 +47,11 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService const gatewayId = generateUuid(); // Create the gateway route - const gateway = new McpGatewayRoute(gatewayId); + if (!toolInvoker) { + throw new Error('[McpGatewayService] Tool invoker is required to create gateway'); + } + + const gateway = new McpGatewayRoute(gatewayId, this._logService, toolInvoker); this._gateways.set(gatewayId, gateway); // Track client ownership if clientId provided (for cleanup on disconnect) @@ -71,6 +77,7 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService return; } + gateway.dispose(); this._gateways.delete(gatewayId); this._gatewayToClient.delete(gatewayId); this._logService.info(`[McpGatewayService] Disposed gateway: ${gatewayId}`); @@ -94,6 +101,7 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService this._logService.info(`[McpGatewayService] Disposing ${gatewaysToDispose.length} gateway(s) for disconnected client ${clientId}`); for (const gatewayId of gatewaysToDispose) { + this._gateways.get(gatewayId)?.dispose(); this._gateways.delete(gatewayId); this._gatewayToClient.delete(gatewayId); } @@ -211,6 +219,9 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService override dispose(): void { this._stopServer(); + for (const gateway of this._gateways.values()) { + gateway.dispose(); + } this._gateways.clear(); super.dispose(); } @@ -218,22 +229,178 @@ export class McpGatewayService extends Disposable implements IMcpGatewayService /** * Represents a single MCP gateway route. - * This is a stub implementation that will be expanded later. */ -class McpGatewayRoute { +class McpGatewayRoute extends Disposable { + private readonly _sessions = new Map(); + + private static readonly SessionHeaderName = 'mcp-session-id'; + constructor( public readonly gatewayId: string, - ) { } - - handleRequest(_req: http.IncomingMessage, res: http.ServerResponse): void { - // Stub implementation - return 501 Not Implemented - res.writeHead(501, { 'Content-Type': 'application/json' }); - res.end(JSON.stringify({ - jsonrpc: '2.0', - error: { - code: -32601, - message: 'MCP Gateway not yet implemented', - }, - })); + private readonly _logService: ILogService, + private readonly _toolInvoker: IMcpGatewayToolInvoker, + ) { + super(); + } + + handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void { + if (req.method === 'POST') { + void this._handlePost(req, res); + return; + } + + if (req.method === 'GET') { + this._handleGet(req, res); + return; + } + + if (req.method === 'DELETE') { + this._handleDelete(req, res); + return; + } + + this._respondHttpError(res, 405, 'Method not allowed'); + } + + public override dispose(): void { + for (const session of this._sessions.values()) { + session.dispose(); + } + this._sessions.clear(); + super.dispose(); + } + + private _handleDelete(req: http.IncomingMessage, res: http.ServerResponse): void { + const sessionId = this._getSessionId(req); + if (!sessionId) { + this._respondHttpError(res, 400, 'Missing Mcp-Session-Id header'); + return; + } + + const session = this._sessions.get(sessionId); + if (!session) { + this._respondHttpError(res, 404, 'Session not found'); + return; + } + + session.dispose(); + this._sessions.delete(sessionId); + res.writeHead(204); + res.end(); + } + + private _handleGet(req: http.IncomingMessage, res: http.ServerResponse): void { + const sessionId = this._getSessionId(req); + if (!sessionId) { + this._respondHttpError(res, 400, 'Missing Mcp-Session-Id header'); + return; + } + + const session = this._sessions.get(sessionId); + if (!session) { + this._respondHttpError(res, 404, 'Session not found'); + return; + } + + session.attachSseClient(req, res); + } + + private async _handlePost(req: http.IncomingMessage, res: http.ServerResponse): Promise { + const body = await this._readRequestBody(req); + if (body === undefined) { + this._respondHttpError(res, 413, 'Payload too large'); + return; + } + + let message: JsonRpcMessage | JsonRpcMessage[]; + try { + message = JSON.parse(body) as JsonRpcMessage | JsonRpcMessage[]; + } catch (error) { + res.writeHead(400, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(JsonRpcProtocol.createParseError('Parse error', error instanceof Error ? error.message : String(error)))); + return; + } + + const headerSessionId = this._getSessionId(req); + const session = this._resolveSessionForPost(headerSessionId, message, res); + if (!session) { + return; + } + + try { + const responses = await session.handleIncoming(message); + + const headers: Record = { + 'Content-Type': 'application/json', + 'Mcp-Session-Id': session.id, + }; + + if (responses.length === 0) { + res.writeHead(202, headers); + res.end(); + return; + } + + res.writeHead(200, headers); + res.end(JSON.stringify(Array.isArray(message) ? responses : responses[0])); + } catch (error) { + this._logService.error('[McpGatewayService] Failed handling gateway request', error); + this._respondHttpError(res, 500, 'Internal server error'); + } + } + + private _resolveSessionForPost(headerSessionId: string | undefined, message: JsonRpcMessage | JsonRpcMessage[], res: http.ServerResponse): McpGatewaySession | undefined { + if (headerSessionId) { + const existing = this._sessions.get(headerSessionId); + if (!existing) { + this._respondHttpError(res, 404, 'Session not found'); + return undefined; + } + + return existing; + } + + if (!isInitializeMessage(message)) { + this._respondHttpError(res, 400, 'Missing Mcp-Session-Id header'); + return undefined; + } + + const sessionId = generateUuid(); + const session = new McpGatewaySession(sessionId, this._logService, () => { + this._sessions.delete(sessionId); + }, this._toolInvoker); + this._sessions.set(sessionId, session); + return session; + } + + private _respondHttpError(res: http.ServerResponse, statusCode: number, error: string): void { + res.writeHead(statusCode, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: statusCode, message: error } } satisfies JsonRpcMessage)); + } + + private _getSessionId(req: http.IncomingMessage): string | undefined { + const value = req.headers[McpGatewayRoute.SessionHeaderName]; + if (Array.isArray(value)) { + return value[0]; + } + + return value; + } + + private async _readRequestBody(req: http.IncomingMessage): Promise { + const chunks: Buffer[] = []; + let size = 0; + const maxBytes = 1024 * 1024; + + for await (const chunk of req) { + const asBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + size += asBuffer.byteLength; + if (size > maxBytes) { + return undefined; + } + chunks.push(asBuffer); + } + + return Buffer.concat(chunks).toString('utf8'); } } diff --git a/src/vs/platform/mcp/node/mcpGatewaySession.ts b/src/vs/platform/mcp/node/mcpGatewaySession.ts new file mode 100644 index 0000000000000..691453ec05932 --- /dev/null +++ b/src/vs/platform/mcp/node/mcpGatewaySession.ts @@ -0,0 +1,211 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import type * as http from 'http'; +import { + IJsonRpcNotification, IJsonRpcRequest, + isJsonRpcNotification, isJsonRpcResponse, JsonRpcError, JsonRpcMessage, JsonRpcProtocol +} from '../../../base/common/jsonRpcProtocol.js'; +import { Disposable } from '../../../base/common/lifecycle.js'; +import { hasKey } from '../../../base/common/types.js'; +import { ILogService } from '../../log/common/log.js'; +import { IMcpGatewayToolInvoker } from '../common/mcpGateway.js'; +import { MCP } from '../common/modelContextProtocol.js'; + +const MCP_LATEST_PROTOCOL_VERSION = '2025-11-25'; +const MCP_INVALID_REQUEST = -32600; +const MCP_METHOD_NOT_FOUND = -32601; +const MCP_INVALID_PARAMS = -32602; + +export class McpGatewaySession extends Disposable { + private readonly _rpc: JsonRpcProtocol; + private readonly _sseClients = new Set(); + private readonly _pendingResponses: JsonRpcMessage[] = []; + private _isCollectingPostResponses = false; + private _lastEventId = 0; + private _isInitialized = false; + + constructor( + public readonly id: string, + private readonly _logService: ILogService, + private readonly _onDidDispose: () => void, + private readonly _toolInvoker: IMcpGatewayToolInvoker, + ) { + super(); + + this._rpc = this._register(new JsonRpcProtocol( + message => this._handleOutgoingMessage(message), + { + handleRequest: request => this._handleRequest(request), + handleNotification: notification => this._handleNotification(notification), + } + )); + + this._register(this._toolInvoker.onDidChangeTools(() => { + if (!this._isInitialized) { + return; + } + + this._rpc.sendNotification({ method: 'notifications/tools/list_changed' }); + })); + } + + public attachSseClient(_req: http.IncomingMessage, res: http.ServerResponse): void { + res.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache, no-transform', + 'Connection': 'keep-alive', + }); + + res.write(': connected\n\n'); + this._sseClients.add(res); + + res.on('close', () => { + this._sseClients.delete(res); + }); + } + + public async handleIncoming(message: JsonRpcMessage | JsonRpcMessage[]): Promise { + this._pendingResponses.length = 0; + this._isCollectingPostResponses = true; + try { + await this._rpc.handleMessage(message); + return [...this._pendingResponses]; + } finally { + this._isCollectingPostResponses = false; + this._pendingResponses.length = 0; + } + } + + public override dispose(): void { + for (const client of this._sseClients) { + if (!client.destroyed) { + client.end(); + } + } + this._sseClients.clear(); + this._onDidDispose(); + super.dispose(); + } + + private _handleOutgoingMessage(message: JsonRpcMessage): void { + if (isJsonRpcResponse(message)) { + if (this._isCollectingPostResponses) { + this._pendingResponses.push(message); + } + return; + } + + if (isJsonRpcNotification(message)) { + this._broadcastSse(message); + return; + } + + this._logService.warn('[McpGatewayService] Ignored unsupported outgoing gateway message'); + } + + private _broadcastSse(message: JsonRpcMessage): void { + if (this._sseClients.size === 0) { + return; + } + + const payload = JSON.stringify(message); + const eventId = String(++this._lastEventId); + const lines = payload.split(/\r?\n/g); + const data = [ + `id: ${eventId}`, + 'event: message', + ...lines.map(line => `data: ${line}`), + '', + '' + ].join('\n'); + + for (const client of [...this._sseClients]) { + if (client.destroyed || client.writableEnded) { + this._sseClients.delete(client); + continue; + } + + client.write(data); + } + } + + private async _handleRequest(request: IJsonRpcRequest): Promise { + if (request.method === 'initialize') { + return this._handleInitialize(); + } + + if (!this._isInitialized) { + throw new JsonRpcError(MCP_INVALID_REQUEST, 'Session is not initialized'); + } + + switch (request.method) { + case 'ping': + return {}; + case 'tools/list': + return this._handleListTools(); + case 'tools/call': + return this._handleCallTool(request); + default: + throw new JsonRpcError(MCP_METHOD_NOT_FOUND, `Method not found: ${request.method}`); + } + } + + private _handleNotification(notification: IJsonRpcNotification): void { + if (notification.method === 'notifications/initialized') { + this._isInitialized = true; + this._rpc.sendNotification({ method: 'notifications/tools/list_changed' }); + } + } + + private _handleInitialize(): MCP.InitializeResult { + return { + protocolVersion: MCP_LATEST_PROTOCOL_VERSION, + capabilities: { + tools: { + listChanged: true, + }, + }, + serverInfo: { + name: 'VS Code MCP Gateway', + version: '1.0.0', + } + }; + } + + private _handleCallTool(request: IJsonRpcRequest): unknown { + const params = typeof request.params === 'object' && request.params ? request.params as Record : undefined; + if (!params || typeof params.name !== 'string') { + throw new JsonRpcError(MCP_INVALID_PARAMS, 'Missing tool call params'); + } + + if (params.arguments && typeof params.arguments !== 'object') { + throw new JsonRpcError(MCP_INVALID_PARAMS, 'Invalid tool call arguments'); + } + + const argumentsValue = (params.arguments && typeof params.arguments === 'object') + ? params.arguments as Record + : {}; + + return this._toolInvoker.callTool(params.name, argumentsValue).catch(error => { + this._logService.error('[McpGatewayService] Tool call invocation failed', error); + throw new JsonRpcError(MCP_INVALID_PARAMS, String(error)); + }); + } + + private _handleListTools(): unknown { + return this._toolInvoker.listTools() + .then(tools => ({ tools })); + } +} + +export function isInitializeMessage(message: JsonRpcMessage | JsonRpcMessage[]): boolean { + const first = Array.isArray(message) ? message[0] : message; + if (!first || !hasKey(first, { method: true })) { + return false; + } + + return first.method === 'initialize'; +} diff --git a/src/vs/platform/mcp/test/node/mcpGatewaySession.test.ts b/src/vs/platform/mcp/test/node/mcpGatewaySession.test.ts new file mode 100644 index 0000000000000..945b2877ca348 --- /dev/null +++ b/src/vs/platform/mcp/test/node/mcpGatewaySession.test.ts @@ -0,0 +1,201 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import type * as http from 'http'; +import { EventEmitter } from 'events'; +import { Emitter } from '../../../../base/common/event.js'; +import { IJsonRpcErrorResponse, IJsonRpcSuccessResponse } from '../../../../base/common/jsonRpcProtocol.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; +import { NullLogService } from '../../../log/common/log.js'; +import { MCP } from '../../common/modelContextProtocol.js'; +import { McpGatewaySession } from '../../node/mcpGatewaySession.js'; + +class TestServerResponse extends EventEmitter { + public statusCode: number | undefined; + public headers: Record | undefined; + public readonly writes: string[] = []; + public destroyed = false; + public writableEnded = false; + + writeHead(statusCode: number, headers?: Record) { + this.statusCode = statusCode; + this.headers = headers; + return this; + } + + write(chunk: string): boolean { + this.writes.push(chunk); + return true; + } + + end(chunk?: string): this { + if (chunk) { + this.writes.push(chunk); + } + + this.writableEnded = true; + this.destroyed = true; + this.emit('close'); + return this; + } +} + +suite('McpGatewaySession', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + function createInvoker() { + const onDidChangeTools = new Emitter(); + const tools: readonly MCP.Tool[] = [{ + name: 'test_tool', + description: 'Test tool', + inputSchema: { + type: 'object', + properties: { + name: { type: 'string' } + } + } + }]; + + return { + onDidChangeTools, + invoker: { + onDidChangeTools: onDidChangeTools.event, + listTools: async () => tools, + callTool: async (_name: string, args: Record): Promise => ({ + content: [{ type: 'text', text: `Hello, ${typeof args.name === 'string' ? args.name : 'World'}!` }] + }) + } + }; + } + + test('returns initialize result', async () => { + const { invoker, onDidChangeTools } = createInvoker(); + const session = new McpGatewaySession('session-1', new NullLogService(), () => { }, invoker); + + const responses = await session.handleIncoming({ + jsonrpc: '2.0', + id: 1, + method: 'initialize', + params: { + protocolVersion: '2025-11-25', + capabilities: {}, + clientInfo: { name: 'test-client', version: '1.0.0' }, + }, + }); + + assert.strictEqual(responses.length, 1); + const response = responses[0] as IJsonRpcSuccessResponse; + assert.strictEqual(response.jsonrpc, '2.0'); + assert.strictEqual(response.id, 1); + assert.strictEqual((response.result as { protocolVersion: string }).protocolVersion, '2025-11-25'); + session.dispose(); + onDidChangeTools.dispose(); + }); + + test('rejects non-initialize requests before initialized notification', async () => { + const { invoker, onDidChangeTools } = createInvoker(); + const session = new McpGatewaySession('session-2', new NullLogService(), () => { }, invoker); + + const responses = await session.handleIncoming({ + jsonrpc: '2.0', + id: 2, + method: 'tools/list', + }); + + assert.strictEqual(responses.length, 1); + const response = responses[0] as IJsonRpcErrorResponse; + assert.strictEqual(response.jsonrpc, '2.0'); + assert.strictEqual(response.id, 2); + assert.strictEqual(response.error.code, -32600); + session.dispose(); + onDidChangeTools.dispose(); + }); + + test('serves tools/list and tools/call after initialized notification', async () => { + const { invoker, onDidChangeTools } = createInvoker(); + const session = new McpGatewaySession('session-3', new NullLogService(), () => { }, invoker); + + await session.handleIncoming({ jsonrpc: '2.0', id: 1, method: 'initialize' }); + const notificationResponses = await session.handleIncoming({ jsonrpc: '2.0', method: 'notifications/initialized' }); + assert.strictEqual(notificationResponses.length, 0); + + const listResponses = await session.handleIncoming({ jsonrpc: '2.0', id: 3, method: 'tools/list' }); + const listResponse = listResponses[0] as IJsonRpcSuccessResponse; + const tools = (listResponse.result as { tools: Array<{ name: string }> }).tools; + assert.strictEqual(tools.length, 1); + assert.strictEqual(tools[0].name, 'test_tool'); + + const callResponses = await session.handleIncoming({ + jsonrpc: '2.0', + id: 4, + method: 'tools/call', + params: { + name: 'test_tool', + arguments: { + name: 'VS Code', + }, + }, + }); + + const callResponse = callResponses[0] as IJsonRpcSuccessResponse; + const text = ((callResponse.result as { content: Array<{ text: string }> }).content[0].text); + assert.strictEqual(text, 'Hello, VS Code!'); + session.dispose(); + onDidChangeTools.dispose(); + }); + + test('broadcasts notifications to attached SSE clients', async () => { + const { invoker, onDidChangeTools } = createInvoker(); + const session = new McpGatewaySession('session-4', new NullLogService(), () => { }, invoker); + const response = new TestServerResponse(); + + session.attachSseClient({} as http.IncomingMessage, response as unknown as http.ServerResponse); + await session.handleIncoming({ jsonrpc: '2.0', id: 1, method: 'initialize' }); + await session.handleIncoming({ jsonrpc: '2.0', method: 'notifications/initialized' }); + + assert.strictEqual(response.statusCode, 200); + assert.strictEqual(response.headers?.['Content-Type'], 'text/event-stream'); + assert.ok(response.writes.some(chunk => chunk.includes(': connected'))); + assert.ok(response.writes.some(chunk => chunk.includes('event: message'))); + assert.ok(response.writes.some(chunk => chunk.includes('notifications/tools/list_changed'))); + session.dispose(); + onDidChangeTools.dispose(); + }); + + test('emits list changed on tool invoker changes', async () => { + const { invoker, onDidChangeTools } = createInvoker(); + const session = new McpGatewaySession('session-5', new NullLogService(), () => { }, invoker); + const response = new TestServerResponse(); + + session.attachSseClient({} as http.IncomingMessage, response as unknown as http.ServerResponse); + await session.handleIncoming({ jsonrpc: '2.0', id: 1, method: 'initialize' }); + await session.handleIncoming({ jsonrpc: '2.0', method: 'notifications/initialized' }); + + const writesBefore = response.writes.length; + onDidChangeTools.fire(); + + assert.ok(response.writes.length > writesBefore); + assert.ok(response.writes.slice(writesBefore).some(chunk => chunk.includes('notifications/tools/list_changed'))); + session.dispose(); + onDidChangeTools.dispose(); + }); + + test('disposes attached SSE clients and callback', () => { + const { invoker, onDidChangeTools } = createInvoker(); + let disposed = false; + const session = new McpGatewaySession('session-6', new NullLogService(), () => { + disposed = true; + }, invoker); + const response = new TestServerResponse(); + + session.attachSseClient({} as http.IncomingMessage, response as unknown as http.ServerResponse); + session.dispose(); + + assert.strictEqual(response.writableEnded, true); + assert.strictEqual(disposed, true); + onDidChangeTools.dispose(); + }); +}); diff --git a/src/vs/sessions/browser/menus.ts b/src/vs/sessions/browser/menus.ts index a6f273f3aeb88..ed06a0221d951 100644 --- a/src/vs/sessions/browser/menus.ts +++ b/src/vs/sessions/browser/menus.ts @@ -24,4 +24,5 @@ export const Menus = { AuxiliaryBarTitleLeft: new MenuId('SessionsAuxiliaryBarTitleLeft'), SidebarFooter: new MenuId('SessionsSidebarFooter'), SidebarCustomizations: new MenuId('SessionsSidebarCustomizations'), + AgentFeedbackEditorContent: new MenuId('AgentFeedbackEditorContent'), } as const; diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedback.contribution.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedback.contribution.ts new file mode 100644 index 0000000000000..5b4028dda8e7b --- /dev/null +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedback.contribution.ts @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './agentFeedbackEditorInputContribution.js'; +import { InstantiationType, registerSingleton } from '../../../../platform/instantiation/common/extensions.js'; +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; +import { AgentFeedbackService, IAgentFeedbackService } from './agentFeedbackService.js'; +import { AgentFeedbackAttachmentContribution } from './agentFeedbackAttachment.js'; +import { AgentFeedbackEditorOverlay } from './agentFeedbackEditorOverlay.js'; +import { registerAgentFeedbackEditorActions } from './agentFeedbackEditorActions.js'; + +registerWorkbenchContribution2(AgentFeedbackEditorOverlay.ID, AgentFeedbackEditorOverlay, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(AgentFeedbackAttachmentContribution.ID, AgentFeedbackAttachmentContribution, WorkbenchPhase.AfterRestored); + +registerAgentFeedbackEditorActions(); + +registerSingleton(IAgentFeedbackService, AgentFeedbackService, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachment.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachment.ts similarity index 88% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachment.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachment.ts index b942e505b6c92..720eb60b9e2ca 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachment.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachment.ts @@ -3,16 +3,16 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Disposable, DisposableMap } from '../../../../../base/common/lifecycle.js'; -import { Codicon } from '../../../../../base/common/codicons.js'; -import { basename } from '../../../../../base/common/resources.js'; -import { URI } from '../../../../../base/common/uri.js'; -import { IRange } from '../../../../../editor/common/core/range.js'; -import { ITextModelService } from '../../../../../editor/common/services/resolverService.js'; -import { localize } from '../../../../../nls.js'; +import { Disposable, DisposableMap } from '../../../../base/common/lifecycle.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { basename } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IRange } from '../../../../editor/common/core/range.js'; +import { ITextModelService } from '../../../../editor/common/services/resolverService.js'; +import { localize } from '../../../../nls.js'; import { IAgentFeedbackService, IAgentFeedback } from './agentFeedbackService.js'; -import { IChatWidgetService } from '../chat.js'; -import { IAgentFeedbackVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import { IChatWidgetService } from '../../../../workbench/contrib/chat/browser/chat.js'; +import { IAgentFeedbackVariableEntry } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; const ATTACHMENT_ID_PREFIX = 'agentFeedback:'; diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachmentWidget.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachmentWidget.ts similarity index 82% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachmentWidget.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachmentWidget.ts index 290e3f2637b11..0a420da416111 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackAttachmentWidget.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackAttachmentWidget.ts @@ -4,14 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import './media/agentFeedbackAttachment.css'; -import * as dom from '../../../../../base/browser/dom.js'; -import { Codicon } from '../../../../../base/common/codicons.js'; -import { ThemeIcon } from '../../../../../base/common/themables.js'; -import { Disposable } from '../../../../../base/common/lifecycle.js'; -import * as event from '../../../../../base/common/event.js'; -import { localize } from '../../../../../nls.js'; -import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; -import { IAgentFeedbackVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import * as dom from '../../../../base/browser/dom.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import * as event from '../../../../base/common/event.js'; +import { localize } from '../../../../nls.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IAgentFeedbackVariableEntry } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; import { AgentFeedbackHover } from './agentFeedbackHover.js'; /** diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorActions.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts similarity index 81% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorActions.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts index e64ffc5658e66..a1258d70b5cc7 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorActions.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorActions.ts @@ -3,20 +3,21 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Codicon } from '../../../../../base/common/codicons.js'; -import { localize, localize2 } from '../../../../../nls.js'; -import { Action2, MenuId, MenuRegistry, registerAction2 } from '../../../../../platform/actions/common/actions.js'; -import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; -import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; -import { URI } from '../../../../../base/common/uri.js'; -import { isEqual } from '../../../../../base/common/resources.js'; -import { EditorsOrder, IEditorIdentifier } from '../../../../common/editor.js'; -import { IEditorService } from '../../../../services/editor/common/editorService.js'; -import { IChatWidgetService } from '../chat.js'; -import { ChatContextKeys } from '../../common/actions/chatContextKeys.js'; -import { CHAT_CATEGORY } from '../actions/chatActions.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Action2, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { URI } from '../../../../base/common/uri.js'; +import { isEqual } from '../../../../base/common/resources.js'; +import { EditorsOrder, IEditorIdentifier } from '../../../../workbench/common/editor.js'; +import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; +import { IChatWidgetService } from '../../../../workbench/contrib/chat/browser/chat.js'; +import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { CHAT_CATEGORY } from '../../../../workbench/contrib/chat/browser/actions/chatActions.js'; import { IAgentFeedbackService } from './agentFeedbackService.js'; import { getActiveResourceCandidates } from './agentFeedbackEditorUtils.js'; +import { Menus } from '../../../browser/menus.js'; export const submitFeedbackActionId = 'agentFeedbackEditor.action.submit'; export const navigatePreviousFeedbackActionId = 'agentFeedbackEditor.action.navigatePrevious'; @@ -61,7 +62,7 @@ class SubmitFeedbackAction extends AgentFeedbackEditorAction { icon: Codicon.send, precondition: ChatContextKeys.enabled, menu: { - id: MenuId.AgentFeedbackEditorContent, + id: Menus.AgentFeedbackEditorContent, group: 'a_submit', order: 0, when: ChatContextKeys.enabled, @@ -110,7 +111,7 @@ class NavigateFeedbackAction extends AgentFeedbackEditorAction { f1: true, precondition: ChatContextKeys.enabled, menu: { - id: MenuId.AgentFeedbackEditorContent, + id: Menus.AgentFeedbackEditorContent, group: 'navigate', order: _next ? 2 : 1, when: ChatContextKeys.enabled, @@ -149,7 +150,7 @@ class ClearAllFeedbackAction extends AgentFeedbackEditorAction { f1: true, precondition: ContextKeyExpr.and(ChatContextKeys.enabled), menu: { - id: MenuId.AgentFeedbackEditorContent, + id: Menus.AgentFeedbackEditorContent, group: 'a_submit', order: 1, when: ChatContextKeys.enabled, @@ -169,7 +170,7 @@ export function registerAgentFeedbackEditorActions(): void { registerAction2(class extends NavigateFeedbackAction { constructor() { super(true); } }); registerAction2(ClearAllFeedbackAction); - MenuRegistry.appendMenuItem(MenuId.AgentFeedbackEditorContent, { + MenuRegistry.appendMenuItem(Menus.AgentFeedbackEditorContent, { command: { id: navigationBearingFakeActionId, title: localize('label', 'Navigation Status'), diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorInputContribution.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorInputContribution.ts new file mode 100644 index 0000000000000..bcb3a079ad4be --- /dev/null +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorInputContribution.ts @@ -0,0 +1,308 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/agentFeedbackEditorInput.css'; +import { Disposable, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { ICodeEditor, IOverlayWidget, IOverlayWidgetPosition } from '../../../../editor/browser/editorBrowser.js'; +import { IEditorContribution } from '../../../../editor/common/editorCommon.js'; +import { EditorContributionInstantiation, registerEditorContribution } from '../../../../editor/browser/editorExtensions.js'; +import { EditorOption } from '../../../../editor/common/config/editorOptions.js'; +import { SelectionDirection } from '../../../../editor/common/core/selection.js'; +import { URI } from '../../../../base/common/uri.js'; +import { addStandardDisposableListener, getWindow } from '../../../../base/browser/dom.js'; +import { KeyCode } from '../../../../base/common/keyCodes.js'; +import { IAgentFeedbackService } from './agentFeedbackService.js'; +import { IChatEditingService } from '../../../../workbench/contrib/chat/common/editing/chatEditingService.js'; +import { IAgentSessionsService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentSessionsService.js'; +import { getSessionForResource } from './agentFeedbackEditorUtils.js'; +import { localize } from '../../../../nls.js'; + +class AgentFeedbackInputWidget implements IOverlayWidget { + + private static readonly _ID = 'agentFeedback.inputWidget'; + + readonly allowEditorOverflow = false; + + private readonly _domNode: HTMLElement; + private readonly _inputElement: HTMLInputElement; + private _position: IOverlayWidgetPosition | null = null; + + constructor( + private readonly _editor: ICodeEditor, + ) { + this._domNode = document.createElement('div'); + this._domNode.classList.add('agent-feedback-input-widget'); + this._domNode.style.display = 'none'; + + this._inputElement = document.createElement('input'); + this._inputElement.type = 'text'; + this._inputElement.placeholder = localize('agentFeedback.addFeedback', "Add Feedback"); + this._domNode.appendChild(this._inputElement); + + this._editor.applyFontInfo(this._inputElement); + } + + getId(): string { + return AgentFeedbackInputWidget._ID; + } + + getDomNode(): HTMLElement { + return this._domNode; + } + + getPosition(): IOverlayWidgetPosition | null { + return this._position; + } + + get inputElement(): HTMLInputElement { + return this._inputElement; + } + + setPosition(position: IOverlayWidgetPosition | null): void { + this._position = position; + this._editor.layoutOverlayWidget(this); + } + + show(): void { + this._domNode.style.display = ''; + } + + hide(): void { + this._domNode.style.display = 'none'; + } + + clearInput(): void { + this._inputElement.value = ''; + } +} + +export class AgentFeedbackEditorInputContribution extends Disposable implements IEditorContribution { + + static readonly ID = 'agentFeedback.editorInputContribution'; + + private _widget: AgentFeedbackInputWidget | undefined; + private _visible = false; + private _mouseDown = false; + private _sessionResource: URI | undefined; + private readonly _widgetListeners = this._store.add(new DisposableStore()); + + constructor( + private readonly _editor: ICodeEditor, + @IAgentFeedbackService private readonly _agentFeedbackService: IAgentFeedbackService, + @IChatEditingService private readonly _chatEditingService: IChatEditingService, + @IAgentSessionsService private readonly _agentSessionsService: IAgentSessionsService, + ) { + super(); + + this._store.add(this._editor.onDidChangeCursorSelection(() => this._onSelectionChanged())); + this._store.add(this._editor.onDidChangeModel(() => this._onModelChanged())); + this._store.add(this._editor.onDidScrollChange(() => { + if (this._visible) { + this._updatePosition(); + } + })); + this._store.add(this._editor.onMouseDown(() => { + this._mouseDown = true; + this._hide(); + })); + this._store.add(this._editor.onMouseUp(() => { + this._mouseDown = false; + this._onSelectionChanged(); + })); + this._store.add(this._editor.onDidBlurEditorWidget(() => this._hide())); + this._store.add(this._editor.onDidFocusEditorWidget(() => this._onSelectionChanged())); + } + + private _ensureWidget(): AgentFeedbackInputWidget { + if (!this._widget) { + this._widget = new AgentFeedbackInputWidget(this._editor); + this._editor.addOverlayWidget(this._widget); + } + return this._widget; + } + + private _onModelChanged(): void { + this._hide(); + this._sessionResource = undefined; + } + + private _onSelectionChanged(): void { + if (this._mouseDown || !this._editor.hasWidgetFocus()) { + return; + } + + const selection = this._editor.getSelection(); + if (!selection || selection.isEmpty()) { + this._hide(); + return; + } + + const model = this._editor.getModel(); + if (!model) { + this._hide(); + return; + } + + const match = getSessionForResource(model.uri, this._chatEditingService, this._agentSessionsService); + if (!match) { + this._hide(); + return; + } + + this._sessionResource = match.sessionResource; + this._show(); + } + + private _show(): void { + const widget = this._ensureWidget(); + + if (!this._visible) { + this._visible = true; + this._registerWidgetListeners(widget); + } + + widget.clearInput(); + widget.show(); + this._updatePosition(); + } + + private _hide(): void { + if (!this._visible) { + return; + } + + this._visible = false; + this._widgetListeners.clear(); + + if (this._widget) { + this._widget.hide(); + this._widget.setPosition(null); + this._widget.clearInput(); + } + } + + private _registerWidgetListeners(widget: AgentFeedbackInputWidget): void { + this._widgetListeners.clear(); + + // Listen for keydown on the editor dom node to detect when the user starts typing + const editorDomNode = this._editor.getDomNode(); + if (editorDomNode) { + this._widgetListeners.add(addStandardDisposableListener(editorDomNode, 'keydown', e => { + if (!this._visible) { + return; + } + + // Don't focus if a modifier key is pressed alone + if (e.keyCode === KeyCode.Ctrl || e.keyCode === KeyCode.Shift || e.keyCode === KeyCode.Alt || e.keyCode === KeyCode.Meta) { + return; + } + + // Don't focus if any modifier is held (keyboard shortcuts) + if (e.ctrlKey || e.altKey || e.metaKey) { + return; + } + + // Don't capture Escape at this level - let it fall through to the input handler if focused + if (e.keyCode === KeyCode.Escape) { + this._hide(); + this._editor.focus(); + return; + } + + // If the input is not focused, focus it and let the keystroke go through + if (getWindow(widget.inputElement).document.activeElement !== widget.inputElement) { + widget.inputElement.focus(); + } + })); + } + + // Listen for keydown on the input element + this._widgetListeners.add(addStandardDisposableListener(widget.inputElement, 'keydown', e => { + if (e.keyCode === KeyCode.Escape) { + e.preventDefault(); + e.stopPropagation(); + this._hide(); + this._editor.focus(); + return; + } + + if (e.keyCode === KeyCode.Enter) { + e.preventDefault(); + e.stopPropagation(); + this._submit(widget); + return; + } + })); + + // Stop propagation of input events so the editor doesn't handle them + this._widgetListeners.add(addStandardDisposableListener(widget.inputElement, 'keypress', e => { + e.stopPropagation(); + })); + } + + private _submit(widget: AgentFeedbackInputWidget): void { + const text = widget.inputElement.value.trim(); + if (!text) { + return; + } + + const selection = this._editor.getSelection(); + const model = this._editor.getModel(); + if (!selection || !model || !this._sessionResource) { + return; + } + + this._agentFeedbackService.addFeedback(this._sessionResource, model.uri, selection, text); + this._hide(); + this._editor.focus(); + } + + private _updatePosition(): void { + if (!this._widget || !this._visible) { + return; + } + + const selection = this._editor.getSelection(); + if (!selection || selection.isEmpty()) { + this._hide(); + return; + } + + const cursorPosition = selection.getDirection() === SelectionDirection.LTR + ? selection.getEndPosition() + : selection.getStartPosition(); + + const scrolledPosition = this._editor.getScrolledVisiblePosition(cursorPosition); + if (!scrolledPosition) { + this._widget.setPosition(null); + return; + } + + const lineHeight = this._editor.getOption(EditorOption.lineHeight); + const left = scrolledPosition.left; + + let top: number; + if (selection.getDirection() === SelectionDirection.LTR) { + // Cursor at end (bottom) of selection → place widget below the cursor line + top = scrolledPosition.top + lineHeight; + } else { + // Cursor at start (top) of selection → place widget above the cursor line + const widgetHeight = this._widget.getDomNode().offsetHeight || 30; + top = scrolledPosition.top - widgetHeight; + } + + this._widget.setPosition({ preference: { top, left } }); + } + + override dispose(): void { + if (this._widget) { + this._editor.removeOverlayWidget(this._widget); + this._widget = undefined; + } + super.dispose(); + } +} + +registerEditorContribution(AgentFeedbackEditorInputContribution.ID, AgentFeedbackEditorInputContribution, EditorContributionInstantiation.Eventually); diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorOverlay.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts similarity index 86% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorOverlay.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts index e0ba9f6c0a550..30c75a7556dfd 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorOverlay.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorOverlay.ts @@ -4,25 +4,25 @@ *--------------------------------------------------------------------------------------------*/ import './media/agentFeedbackEditorOverlay.css'; -import { Disposable, DisposableMap, DisposableStore, combinedDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { autorun, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../../base/common/observable.js'; -import { ActionViewItem, IBaseActionViewItemOptions } from '../../../../../base/browser/ui/actionbar/actionViewItems.js'; -import { IAction } from '../../../../../base/common/actions.js'; -import { Event } from '../../../../../base/common/event.js'; -import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../../../platform/actions/browser/toolbar.js'; -import { MenuId } from '../../../../../platform/actions/common/actions.js'; -import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; -import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; -import { ServiceCollection } from '../../../../../platform/instantiation/common/serviceCollection.js'; -import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; -import { IWorkbenchContribution } from '../../../../common/contributions.js'; -import { EditorGroupView } from '../../../../browser/parts/editor/editorGroupView.js'; -import { IEditorGroup, IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; +import { Disposable, DisposableMap, DisposableStore, combinedDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { autorun, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../base/common/observable.js'; +import { ActionViewItem, IBaseActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; +import { IAction } from '../../../../base/common/actions.js'; +import { Event } from '../../../../base/common/event.js'; +import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../../platform/actions/browser/toolbar.js'; +import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; +import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; +import { IWorkbenchContribution } from '../../../../workbench/common/contributions.js'; +import { EditorGroupView } from '../../../../workbench/browser/parts/editor/editorGroupView.js'; +import { IEditorGroup, IEditorGroupsService } from '../../../../workbench/services/editor/common/editorGroupsService.js'; import { IAgentFeedbackService } from './agentFeedbackService.js'; import { navigateNextFeedbackActionId, navigatePreviousFeedbackActionId, navigationBearingFakeActionId, submitFeedbackActionId } from './agentFeedbackEditorActions.js'; -import { assertType } from '../../../../../base/common/types.js'; -import { localize } from '../../../../../nls.js'; +import { assertType } from '../../../../base/common/types.js'; +import { localize } from '../../../../nls.js'; import { getActiveResourceCandidates } from './agentFeedbackEditorUtils.js'; +import { Menus } from '../../../browser/menus.js'; class AgentFeedbackActionViewItem extends ActionViewItem { @@ -84,7 +84,7 @@ class AgentFeedbackOverlayWidget extends Disposable { this._domNode.appendChild(this._toolbarNode); } - this._showStore.add(this._instaService.createInstance(MenuWorkbenchToolBar, this._toolbarNode, MenuId.AgentFeedbackEditorContent, { + this._showStore.add(this._instaService.createInstance(MenuWorkbenchToolBar, this._toolbarNode, Menus.AgentFeedbackEditorContent, { telemetrySource: 'agentFeedback.overlayToolbar', hiddenItemStrategy: HiddenItemStrategy.Ignore, toolbarOptions: { diff --git a/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorUtils.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorUtils.ts new file mode 100644 index 0000000000000..c4fc944e1bb6b --- /dev/null +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackEditorUtils.ts @@ -0,0 +1,60 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { URI } from '../../../../base/common/uri.js'; +import { EditorResourceAccessor, SideBySideEditor } from '../../../../workbench/common/editor.js'; +import { IChatEditingService } from '../../../../workbench/contrib/chat/common/editing/chatEditingService.js'; +import { IAgentSessionsService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentSessionsService.js'; +import { agentSessionContainsResource, editingEntriesContainResource } from '../../../../workbench/contrib/chat/browser/sessionResourceMatching.js'; + +export interface ISessionResourceMatch { + readonly sessionResource: URI; + readonly resourceUri: URI; +} + +/** + * Find the session that contains the given resource by checking editing sessions and agent sessions. + */ +export function getSessionForResource( + resourceUri: URI, + chatEditingService: IChatEditingService, + agentSessionsService: IAgentSessionsService, +): ISessionResourceMatch | undefined { + for (const editingSession of chatEditingService.editingSessionsObs.get()) { + if (editingEntriesContainResource(editingSession.entries.get(), resourceUri)) { + return { sessionResource: editingSession.chatSessionResource, resourceUri }; + } + } + + for (const session of agentSessionsService.model.sessions) { + if (agentSessionContainsResource(session, resourceUri)) { + return { sessionResource: session.resource, resourceUri }; + } + } + + return undefined; +} + +export function getActiveResourceCandidates(input: Parameters[0]): URI[] { + const result: URI[] = []; + const resources = EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH }); + if (!resources) { + return result; + } + + if (URI.isUri(resources)) { + result.push(resources); + return result; + } + + if (resources.secondary) { + result.push(resources.secondary); + } + if (resources.primary) { + result.push(resources.primary); + } + + return result; +} diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackHover.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackHover.ts similarity index 82% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackHover.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackHover.ts index c730e9460cf00..a1a5baa2f209b 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackHover.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackHover.ts @@ -3,21 +3,21 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import * as dom from '../../../../../base/browser/dom.js'; -import { HoverStyle } from '../../../../../base/browser/ui/hover/hover.js'; -import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; -import { Codicon } from '../../../../../base/common/codicons.js'; -import { Disposable, DisposableStore } from '../../../../../base/common/lifecycle.js'; -import { ThemeIcon } from '../../../../../base/common/themables.js'; -import { IRange } from '../../../../../editor/common/core/range.js'; -import { URI } from '../../../../../base/common/uri.js'; -import { localize } from '../../../../../nls.js'; -import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; -import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; -import { IEditorService } from '../../../../services/editor/common/editorService.js'; -import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../../browser/labels.js'; +import * as dom from '../../../../base/browser/dom.js'; +import { HoverStyle } from '../../../../base/browser/ui/hover/hover.js'; +import { HoverPosition } from '../../../../base/browser/ui/hover/hoverWidget.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Disposable, DisposableStore } from '../../../../base/common/lifecycle.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; +import { IRange } from '../../../../editor/common/core/range.js'; +import { URI } from '../../../../base/common/uri.js'; +import { localize } from '../../../../nls.js'; +import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; +import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../../workbench/browser/labels.js'; import { IAgentFeedbackService } from './agentFeedbackService.js'; -import { IAgentFeedbackVariableEntry } from '../../common/attachments/chatVariableEntries.js'; +import { IAgentFeedbackVariableEntry } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; /** * Creates the custom hover content for the "N comments" attachment. diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackService.ts b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts similarity index 92% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackService.ts rename to src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts index f1352d999bd4d..19f5baf47c227 100644 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackService.ts +++ b/src/vs/sessions/contrib/agentFeedback/browser/agentFeedbackService.ts @@ -3,24 +3,24 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { Emitter, Event } from '../../../../../base/common/event.js'; -import { Disposable } from '../../../../../base/common/lifecycle.js'; -import { URI } from '../../../../../base/common/uri.js'; -import { IRange } from '../../../../../editor/common/core/range.js'; -import { Comment, CommentThread, CommentThreadCollapsibleState, CommentThreadState, CommentInput } from '../../../../../editor/common/languages.js'; -import { createDecorator, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; -import { ICommentController, ICommentInfo, ICommentService, INotebookCommentInfo } from '../../../comments/browser/commentService.js'; -import { CancellationToken } from '../../../../../base/common/cancellation.js'; -import { generateUuid } from '../../../../../base/common/uuid.js'; -import { registerAction2, Action2, MenuId } from '../../../../../platform/actions/common/actions.js'; -import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; -import { Codicon } from '../../../../../base/common/codicons.js'; -import { localize } from '../../../../../nls.js'; -import { isEqual } from '../../../../../base/common/resources.js'; -import { IChatEditingService } from '../../common/editing/chatEditingService.js'; -import { IAgentSessionsService } from '../agentSessions/agentSessionsService.js'; -import { agentSessionContainsResource, editingEntriesContainResource } from '../sessionResourceMatching.js'; -import { IChatWidget, IChatWidgetService } from '../chat.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { IRange } from '../../../../editor/common/core/range.js'; +import { Comment, CommentThread, CommentThreadCollapsibleState, CommentThreadState, CommentInput } from '../../../../editor/common/languages.js'; +import { createDecorator, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { ICommentController, ICommentInfo, ICommentService, INotebookCommentInfo } from '../../../../workbench/contrib/comments/browser/commentService.js'; +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { generateUuid } from '../../../../base/common/uuid.js'; +import { registerAction2, Action2, MenuId } from '../../../../platform/actions/common/actions.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { localize } from '../../../../nls.js'; +import { isEqual } from '../../../../base/common/resources.js'; +import { IChatEditingService } from '../../../../workbench/contrib/chat/common/editing/chatEditingService.js'; +import { IAgentSessionsService } from '../../../../workbench/contrib/chat/browser/agentSessions/agentSessionsService.js'; +import { agentSessionContainsResource, editingEntriesContainResource } from '../../../../workbench/contrib/chat/browser/sessionResourceMatching.js'; +import { IChatWidget, IChatWidgetService } from '../../../../workbench/contrib/chat/browser/chat.js'; // --- Types -------------------------------------------------------------------- diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/media/agentFeedbackAttachment.css b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackAttachment.css similarity index 100% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/media/agentFeedbackAttachment.css rename to src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackAttachment.css diff --git a/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css new file mode 100644 index 0000000000000..5212171ceae4c --- /dev/null +++ b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorInput.css @@ -0,0 +1,32 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.agent-feedback-input-widget { + position: absolute; + z-index: 100; + background-color: var(--vscode-editorWidget-background); + border: 1px solid var(--vscode-editorWidget-border, var(--vscode-contrastBorder)); + box-shadow: 0 2px 8px var(--vscode-widget-shadow); + border-radius: 4px; + padding: 4px; +} + +.agent-feedback-input-widget input { + background-color: var(--vscode-input-background); + border: 1px solid var(--vscode-input-border, transparent); + color: var(--vscode-input-foreground); + border-radius: 2px; + padding: 2px 6px; + outline: none; + width: 240px; +} + +.agent-feedback-input-widget input:focus { + border-color: var(--vscode-focusBorder); +} + +.agent-feedback-input-widget input::placeholder { + color: var(--vscode-input-placeholderForeground); +} diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/media/agentFeedbackEditorOverlay.css b/src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorOverlay.css similarity index 100% rename from src/vs/workbench/contrib/chat/browser/agentFeedback/media/agentFeedbackEditorOverlay.css rename to src/vs/sessions/contrib/agentFeedback/browser/media/agentFeedbackEditorOverlay.css diff --git a/src/vs/sessions/contrib/chat/browser/media/chatWidget.css b/src/vs/sessions/contrib/chat/browser/media/chatWidget.css index e3d76a95b72c6..8710e63bf3dc3 100644 --- a/src/vs/sessions/contrib/chat/browser/media/chatWidget.css +++ b/src/vs/sessions/contrib/chat/browser/media/chatWidget.css @@ -21,6 +21,7 @@ /* Input area */ .sessions-chat-input-area { + position: relative; width: 100%; max-width: 800px; box-sizing: border-box; @@ -28,6 +29,8 @@ border-radius: 8px; background-color: var(--vscode-input-background); overflow: hidden; + display: flex; + flex-direction: column; } .sessions-chat-input-area:focus-within { @@ -37,9 +40,10 @@ /* Editor */ .sessions-chat-editor { padding: 0 6px 6px 6px; - height: 72px; - min-height: 72px; + height: 50px; + min-height: 36px; max-height: 200px; + flex-shrink: 1; } .sessions-chat-editor .monaco-editor, @@ -115,3 +119,110 @@ .sessions-chat-send-button .codicon { font-size: 16px; } + +/* Attach row (above editor, inside input area) */ +.sessions-chat-attach-row { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px; + padding: 4px 6px 0 6px; +} + +/* Attach context button */ +.sessions-chat-attach-button { + display: flex; + align-items: center; + justify-content: center; + width: 26px; + height: 26px; + border-radius: 4px; + cursor: pointer; + color: var(--vscode-descriptionForeground); + background: transparent; + border: none; + outline: none; +} + +.sessions-chat-attach-button:hover { + background-color: var(--vscode-toolbar-hoverBackground); + color: var(--vscode-foreground); +} + +.sessions-chat-attach-button:focus-visible { + outline: 1px solid var(--vscode-focusBorder); + outline-offset: -1px; +} + +.sessions-chat-attach-button .codicon { + font-size: 16px; +} + +/* Attached context container */ +.sessions-chat-attached-context { + display: flex; + flex-wrap: wrap; + gap: 4px; + align-items: center; +} + +.sessions-chat-attached-context:empty, +.sessions-chat-attached-context[style*="display: none"] { + display: none !important; +} + +/* Attachment pills */ +.sessions-chat-attachment-pill { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 2px 4px 2px 6px; + border-radius: 4px; + background-color: var(--vscode-badge-background); + color: var(--vscode-badge-foreground); + font-size: 12px; + line-height: 18px; + max-width: 200px; +} + +.sessions-chat-attachment-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sessions-chat-attachment-pill .codicon { + font-size: 12px; + flex-shrink: 0; +} + +.sessions-chat-attachment-remove { + display: flex; + align-items: center; + justify-content: center; + width: 16px; + height: 16px; + border-radius: 2px; + cursor: pointer; + flex-shrink: 0; +} + +.sessions-chat-attachment-remove:hover { + background-color: var(--vscode-toolbar-hoverBackground); +} + +/* Drag and drop */ +.sessions-chat-drop-overlay { + display: none; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + z-index: 10; +} + +.sessions-chat-input-area.sessions-chat-drop-active { + border-color: var(--vscode-focusBorder); + background-color: var(--vscode-list-dropBackground); +} diff --git a/src/vs/sessions/contrib/chat/browser/newChatContextAttachments.ts b/src/vs/sessions/contrib/chat/browser/newChatContextAttachments.ts new file mode 100644 index 0000000000000..3b502a1a93980 --- /dev/null +++ b/src/vs/sessions/contrib/chat/browser/newChatContextAttachments.ts @@ -0,0 +1,316 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as dom from '../../../../base/browser/dom.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { URI } from '../../../../base/common/uri.js'; +import { Emitter } from '../../../../base/common/event.js'; +import { renderIcon } from '../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { isObject } from '../../../../base/common/types.js'; +import { localize } from '../../../../nls.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; + +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IQuickInputService, IQuickPickItem, IQuickPickItemWithResource } from '../../../../platform/quickinput/common/quickInput.js'; +import { AnythingQuickAccessProviderRunOptions } from '../../../../platform/quickinput/common/quickAccess.js'; +import { ITextModelService } from '../../../../editor/common/services/resolverService.js'; +import { IFileService } from '../../../../platform/files/common/files.js'; +import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.js'; +import { IFileDialogService } from '../../../../platform/dialogs/common/dialogs.js'; +import { basename } from '../../../../base/common/resources.js'; + +import { AnythingQuickAccessProvider } from '../../../../workbench/contrib/search/browser/anythingQuickAccess.js'; +import { IChatRequestVariableEntry, OmittedState } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; +import { isSupportedChatFileScheme } from '../../../../workbench/contrib/chat/common/constants.js'; +import { resizeImage } from '../../../../workbench/contrib/chat/browser/chatImageUtils.js'; +import { imageToHash, isImage } from '../../../../workbench/contrib/chat/browser/widget/input/editor/chatPasteProviders.js'; +import { getPathForFile } from '../../../../platform/dnd/browser/dnd.js'; + +/** + * Manages context attachments for the sessions new-chat widget. + * + * Supports: + * - File picker via quick access ("Files and Open Folders...") + * - Image from Clipboard + * - Drag and drop files + */ +export class NewChatContextAttachments extends Disposable { + + private readonly _attachedContext: IChatRequestVariableEntry[] = []; + private _container: HTMLElement | undefined; + + private readonly _onDidChangeContext = this._register(new Emitter()); + readonly onDidChangeContext = this._onDidChangeContext.event; + + get attachments(): readonly IChatRequestVariableEntry[] { + return this._attachedContext; + } + + constructor( + @IInstantiationService private readonly instantiationService: IInstantiationService, + @IQuickInputService private readonly quickInputService: IQuickInputService, + @ITextModelService private readonly textModelService: ITextModelService, + @IFileService private readonly fileService: IFileService, + @IClipboardService private readonly clipboardService: IClipboardService, + @IFileDialogService private readonly fileDialogService: IFileDialogService, + ) { + super(); + } + + // --- Rendering --- + + renderAttachedContext(container: HTMLElement): void { + this._container = container; + this._updateRendering(); + } + + private _updateRendering(): void { + if (!this._container) { + return; + } + + dom.clearNode(this._container); + + if (this._attachedContext.length === 0) { + this._container.style.display = 'none'; + return; + } + + this._container.style.display = ''; + + for (const entry of this._attachedContext) { + const pill = dom.append(this._container, dom.$('.sessions-chat-attachment-pill')); + const icon = entry.kind === 'image' ? Codicon.fileMedia : Codicon.file; + dom.append(pill, renderIcon(icon)); + dom.append(pill, dom.$('span.sessions-chat-attachment-name', undefined, entry.name)); + + const removeButton = dom.append(pill, dom.$('.sessions-chat-attachment-remove')); + removeButton.title = localize('removeAttachment', "Remove"); + removeButton.tabIndex = 0; + removeButton.role = 'button'; + dom.append(removeButton, renderIcon(Codicon.close)); + this._register(dom.addDisposableListener(removeButton, dom.EventType.CLICK, (e) => { + e.stopPropagation(); + this._removeAttachment(entry.id); + })); + } + } + + // --- Drag and drop --- + + registerDropTarget(element: HTMLElement): void { + // Use a transparent overlay during drag to capture events over the Monaco editor + const overlay = dom.append(element, dom.$('.sessions-chat-drop-overlay')); + + // Use capture phase to intercept drag events before Monaco editor handles them + this._register(dom.addDisposableListener(element, dom.EventType.DRAG_ENTER, (e: DragEvent) => { + if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) { + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; + overlay.style.display = 'block'; + element.classList.add('sessions-chat-drop-active'); + } + }, true)); + + this._register(dom.addDisposableListener(element, dom.EventType.DRAG_OVER, (e: DragEvent) => { + if (e.dataTransfer && Array.from(e.dataTransfer.types).includes('Files')) { + e.preventDefault(); + e.dataTransfer.dropEffect = 'copy'; + if (overlay.style.display !== 'block') { + overlay.style.display = 'block'; + element.classList.add('sessions-chat-drop-active'); + } + } + }, true)); + + this._register(dom.addDisposableListener(overlay, dom.EventType.DRAG_OVER, (e) => { + e.preventDefault(); + e.dataTransfer!.dropEffect = 'copy'; + })); + + this._register(dom.addDisposableListener(overlay, dom.EventType.DRAG_LEAVE, (e) => { + if (e.relatedTarget && element.contains(e.relatedTarget as Node)) { + return; + } + overlay.style.display = 'none'; + element.classList.remove('sessions-chat-drop-active'); + })); + + this._register(dom.addDisposableListener(overlay, dom.EventType.DROP, async (e) => { + e.preventDefault(); + e.stopPropagation(); + overlay.style.display = 'none'; + element.classList.remove('sessions-chat-drop-active'); + + // Try items first (for URI-based drops from VS Code tree views) + const items = e.dataTransfer?.items; + if (items) { + for (const item of Array.from(items)) { + if (item.kind === 'file') { + const file = item.getAsFile(); + if (!file) { + continue; + } + const filePath = getPathForFile(file); + if (!filePath) { + continue; + } + const uri = URI.file(filePath); + await this._attachFileUri(uri, file.name); + } + } + } + })); + } + + // --- Picker --- + + showPicker(): void { + // Build addition picks for the quick access + const additionPicks: IQuickPickItem[] = []; + + // "Files and Open Folders..." pick - opens a file dialog + additionPicks.push({ + label: localize('filesAndFolders', "Files and Open Folders..."), + iconClass: ThemeIcon.asClassName(Codicon.file), + id: 'sessions.filesAndFolders', + }); + + // "Image from Clipboard" pick + additionPicks.push({ + label: localize('imageFromClipboard', "Image from Clipboard"), + iconClass: ThemeIcon.asClassName(Codicon.fileMedia), + id: 'sessions.imageFromClipboard', + }); + + const providerOptions: AnythingQuickAccessProviderRunOptions = { + filter: (pick) => { + if (_isQuickPickItemWithResource(pick) && pick.resource) { + return this.instantiationService.invokeFunction(accessor => isSupportedChatFileScheme(accessor, pick.resource!.scheme)); + } + return true; + }, + additionPicks, + handleAccept: async (item: IQuickPickItem) => { + if (item.id === 'sessions.filesAndFolders') { + await this._handleFileDialog(); + } else if (item.id === 'sessions.imageFromClipboard') { + await this._handleClipboardImage(); + } else { + await this._handleFilePick(item as IQuickPickItemWithResource); + } + } + }; + + this.quickInputService.quickAccess.show('', { + enabledProviderPrefixes: [AnythingQuickAccessProvider.PREFIX], + placeholder: localize('chatContext.attach.placeholder', "Attach as context..."), + providerOptions, + }); + } + + private async _handleFileDialog(): Promise { + const selected = await this.fileDialogService.showOpenDialog({ + canSelectFiles: true, + canSelectFolders: true, + canSelectMany: true, + title: localize('selectFilesOrFolders', "Select Files or Folders"), + }); + if (!selected) { + return; + } + + for (const uri of selected) { + await this._attachFileUri(uri, basename(uri)); + } + } + + private async _handleFilePick(pick: IQuickPickItemWithResource): Promise { + if (!pick.resource) { + return; + } + await this._attachFileUri(pick.resource, pick.label); + } + + private async _attachFileUri(uri: URI, name: string): Promise { + if (/\.(png|jpg|jpeg|bmp|gif|tiff)$/i.test(uri.path)) { + const readFile = await this.fileService.readFile(uri); + const resizedImage = await resizeImage(readFile.value.buffer); + this._addAttachments({ + id: uri.toString(), + name, + fullName: name, + value: resizedImage, + kind: 'image', + references: [{ reference: uri, kind: 'reference' }] + }); + } else { + let omittedState = OmittedState.NotOmitted; + try { + const ref = await this.textModelService.createModelReference(uri); + ref.dispose(); + } catch { + omittedState = OmittedState.Full; + } + + this._addAttachments({ + kind: 'file', + id: uri.toString(), + value: uri, + name, + omittedState, + }); + } + } + + private async _handleClipboardImage(): Promise { + const imageData = await this.clipboardService.readImage(); + if (!isImage(imageData)) { + return; + } + + this._addAttachments({ + id: await imageToHash(imageData), + name: localize('pastedImage', "Pasted Image"), + fullName: localize('pastedImage', "Pasted Image"), + value: imageData, + kind: 'image', + }); + } + + // --- State management --- + + private _addAttachments(...entries: IChatRequestVariableEntry[]): void { + for (const entry of entries) { + if (!this._attachedContext.some(e => e.id === entry.id)) { + this._attachedContext.push(entry); + } + } + this._updateRendering(); + this._onDidChangeContext.fire(); + } + + private _removeAttachment(id: string): void { + const index = this._attachedContext.findIndex(e => e.id === id); + if (index >= 0) { + this._attachedContext.splice(index, 1); + this._updateRendering(); + this._onDidChangeContext.fire(); + } + } + + clear(): void { + this._attachedContext.length = 0; + this._updateRendering(); + this._onDidChangeContext.fire(); + } +} + +function _isQuickPickItemWithResource(obj: unknown): obj is IQuickPickItemWithResource { + return ( + isObject(obj) + && URI.isUri((obj as IQuickPickItemWithResource).resource)); +} diff --git a/src/vs/sessions/contrib/chat/browser/newChatViewPane.ts b/src/vs/sessions/contrib/chat/browser/newChatViewPane.ts index 014ad6d8d4028..65d4286e855aa 100644 --- a/src/vs/sessions/contrib/chat/browser/newChatViewPane.ts +++ b/src/vs/sessions/contrib/chat/browser/newChatViewPane.ts @@ -56,7 +56,9 @@ import { IStorageService, StorageScope, StorageTarget } from '../../../../platfo import { IViewPaneOptions, ViewPane } from '../../../../workbench/browser/parts/views/viewPane.js'; import { ContextMenuController } from '../../../../editor/contrib/contextmenu/browser/contextmenu.js'; import { getSimpleEditorOptions } from '../../../../workbench/contrib/codeEditor/browser/simpleEditorOptions.js'; +import { IChatRequestVariableEntry } from '../../../../workbench/contrib/chat/common/attachments/chatVariableEntries.js'; import { isString } from '../../../../base/common/types.js'; +import { NewChatContextAttachments } from './newChatContextAttachments.js'; // #region --- Target Config --- @@ -166,6 +168,7 @@ export interface INewChatSendRequestData { readonly sendOptions: IChatSendRequestOptions; readonly selectedOptions: ReadonlyMap; readonly folderUri?: URI; + readonly attachedContext?: IChatRequestVariableEntry[]; } /** @@ -216,6 +219,9 @@ class NewChatWidget extends Disposable { private readonly _optionContextKeys = new Map>(); private readonly _whenClauseKeys = new Set(); + // Attached context + private readonly _contextAttachments: NewChatContextAttachments; + constructor( options: INewChatWidgetOptions, @IInstantiationService private readonly instantiationService: IInstantiationService, @@ -233,6 +239,7 @@ class NewChatWidget extends Disposable { @IStorageService private readonly storageService: IStorageService, ) { super(); + this._contextAttachments = this._register(this.instantiationService.createInstance(NewChatContextAttachments)); this._targetConfig = this._register(new TargetConfig(options.targetConfig)); this._options = options; @@ -311,8 +318,16 @@ class NewChatWidget extends Disposable { // Input area inside the input slot const inputArea = dom.$('.sessions-chat-input-area'); + this._contextAttachments.registerDropTarget(inputArea); + + // Attachments row (plus button + pills) inside input area, above editor + const attachRow = dom.append(inputArea, dom.$('.sessions-chat-attach-row')); + this._createAttachButton(attachRow); + const attachedContextContainer = dom.append(attachRow, dom.$('.sessions-chat-attached-context')); + this._contextAttachments.renderAttachedContext(attachedContextContainer); + this._createEditor(inputArea); - this._createToolbar(inputArea); + this._createBottomToolbar(inputArea); this._inputSlot.appendChild(inputArea); // Local mode picker (below the input, shown when Local is selected) @@ -416,14 +431,21 @@ class NewChatWidget extends Disposable { })); this._register(this._editor.onDidContentSizeChange(() => { - const contentHeight = this._editor.getContentHeight(); - const clampedHeight = Math.min(Math.max(contentHeight, 36), 200); - editorContainer.style.height = `${clampedHeight}px`; this._editor.layout(); })); } - private _createToolbar(container: HTMLElement): void { + private _createAttachButton(container: HTMLElement): void { + const attachButton = dom.append(container, dom.$('.sessions-chat-attach-button')); + attachButton.tabIndex = 0; + attachButton.role = 'button'; + attachButton.title = localize('addContext', "Add Context..."); + attachButton.ariaLabel = localize('addContext', "Add Context..."); + dom.append(attachButton, renderIcon(Codicon.add)); + this._register(dom.addDisposableListener(attachButton, dom.EventType.CLICK, () => this._contextAttachments.showPicker())); + } + + private _createBottomToolbar(container: HTMLElement): void { const toolbar = dom.append(container, dom.$('.sessions-chat-toolbar')); const modelPickerContainer = dom.append(toolbar, dom.$('.sessions-chat-model-picker')); @@ -1044,6 +1066,7 @@ class NewChatWidget extends Disposable { applyCodeBlockSuggestionId: undefined, }, agentIdSilent: contribution?.type, + attachedContext: this._contextAttachments.attachments.length > 0 ? [...this._contextAttachments.attachments] : undefined, }; const folderUri = this._selectedFolderUri ?? this.workspaceContextService.getWorkspace().folders[0]?.uri; @@ -1055,7 +1078,10 @@ class NewChatWidget extends Disposable { sendOptions, selectedOptions: new Map(this._selectedOptions), folderUri, + attachedContext: this._contextAttachments.attachments.length > 0 ? [...this._contextAttachments.attachments] : undefined, }); + + this._contextAttachments.clear(); } // --- Layout --- diff --git a/src/vs/sessions/contrib/sessions/browser/sessionsManagementService.ts b/src/vs/sessions/contrib/sessions/browser/sessionsManagementService.ts index 5ebd3496cb380..b25676606aa52 100644 --- a/src/vs/sessions/contrib/sessions/browser/sessionsManagementService.ts +++ b/src/vs/sessions/contrib/sessions/browser/sessionsManagementService.ts @@ -278,7 +278,7 @@ export class SessionsManagementService extends Disposable implements ISessionsMa async sendRequestForNewSession(sessionResource: URI, query: string, sendOptions: IChatSendRequestOptions, selectedOptions?: ReadonlyMap, folderUri?: URI): Promise { if (LocalChatSessionUri.isLocalSession(sessionResource)) { - await this.sendLocalSession(sessionResource, query, folderUri); + await this.sendLocalSession(sessionResource, query, sendOptions, folderUri); } else { await this.sendCustomSession(sessionResource, query, sendOptions, selectedOptions); } @@ -288,7 +288,7 @@ export class SessionsManagementService extends Disposable implements ISessionsMa * Local sessions run directly through the ChatWidget. * Set the workspace folder, open a fresh chat view, and submit via acceptInput. */ - private async sendLocalSession(sessionResource: URI, query: string, folderUri?: URI): Promise { + private async sendLocalSession(sessionResource: URI, query: string, sendOptions: IChatSendRequestOptions, folderUri?: URI): Promise { if (folderUri) { await this.workspaceEditingService.updateFolders(0, this.workspaceContextService.getWorkspace().folders.length, [{ uri: folderUri }]); } @@ -297,6 +297,9 @@ export class SessionsManagementService extends Disposable implements ISessionsMa const widget = this.chatWidgetService.lastFocusedWidget; if (widget) { + if (sendOptions.attachedContext?.length) { + widget.attachmentModel.addContext(...sendOptions.attachedContext); + } widget.setInput(query); widget.acceptInput(query); } diff --git a/src/vs/sessions/sessions.common.main.ts b/src/vs/sessions/sessions.common.main.ts index 4119d7eaf1342..2731989f776e5 100644 --- a/src/vs/sessions/sessions.common.main.ts +++ b/src/vs/sessions/sessions.common.main.ts @@ -206,7 +206,7 @@ import '../workbench/contrib/speech/browser/speech.contribution.js'; // Chat import '../workbench/contrib/chat/browser/chat.contribution.js'; -import '../workbench/contrib/inlineChat/browser/inlineChat.contribution.js'; +//import '../workbench/contrib/inlineChat/browser/inlineChat.contribution.js'; import '../workbench/contrib/mcp/browser/mcp.contribution.js'; import '../workbench/contrib/chat/browser/chatSessions/chatSessions.contribution.js'; import '../workbench/contrib/chat/browser/contextContrib/chatContext.contribution.js'; diff --git a/src/vs/sessions/sessions.desktop.main.ts b/src/vs/sessions/sessions.desktop.main.ts index b81b0de984e9c..81e6f1b534a56 100644 --- a/src/vs/sessions/sessions.desktop.main.ts +++ b/src/vs/sessions/sessions.desktop.main.ts @@ -165,7 +165,10 @@ import '../workbench/contrib/remoteTunnel/electron-browser/remoteTunnel.contribu // Chat import '../workbench/contrib/chat/electron-browser/chat.contribution.js'; -import '../workbench/contrib/inlineChat/electron-browser/inlineChat.contribution.js'; +//import '../workbench/contrib/inlineChat/electron-browser/inlineChat.contribution.js'; + +import './contrib/agentFeedback/browser/agentFeedback.contribution.js'; + // Encryption import '../workbench/contrib/encryption/electron-browser/encryption.contribution.js'; diff --git a/src/vs/workbench/contrib/browserView/electron-browser/browserEditor.ts b/src/vs/workbench/contrib/browserView/electron-browser/browserEditor.ts index e9f065deb3e64..42f9c41bf5313 100644 --- a/src/vs/workbench/contrib/browserView/electron-browser/browserEditor.ts +++ b/src/vs/workbench/contrib/browserView/electron-browser/browserEditor.ts @@ -43,7 +43,7 @@ import { ThemeIcon } from '../../../../base/common/themables.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { encodeBase64, VSBuffer } from '../../../../base/common/buffer.js'; import { IChatRequestVariableEntry } from '../../chat/common/attachments/chatVariableEntries.js'; -import { IBrowserTargetLocator, getDisplayNameFromOuterHTML } from '../../../../platform/browserElements/common/browserElements.js'; +import { IElementAncestor, IElementData, IBrowserTargetLocator, getDisplayNameFromOuterHTML } from '../../../../platform/browserElements/common/browserElements.js'; import { logBrowserOpen } from './browserViewTelemetry.js'; import { URI } from '../../../../base/common/uri.js'; @@ -372,6 +372,7 @@ export class BrowserEditor extends EditorPane { // Update navigation bar and context keys from model this.updateNavigationState(navEvent); + // Ensure a console session is active while a page URL is loaded. if (navEvent.url) { this.startConsoleSession(); } else { @@ -434,6 +435,11 @@ export class BrowserEditor extends EditorPane { this.layoutBrowserContainer(); this.updateVisibility(); this.doScreenshot(); + + // Start console log capture session if a URL is loaded + if (this._model.url) { + this.startConsoleSession(); + } } protected override setEditorVisible(visible: boolean): void { @@ -705,18 +711,21 @@ export class BrowserEditor extends EditorPane { // Prepare HTML/CSS context const displayName = getDisplayNameFromOuterHTML(elementData.outerHTML); const attachCss = this.configurationService.getValue('chat.sendElementsToChat.attachCSS'); - let value = (attachCss ? 'Attached HTML and CSS Context' : 'Attached HTML Context') + '\n\n' + elementData.outerHTML; - if (attachCss) { - value += '\n\n' + elementData.computedStyle; - } + const value = this.createElementContextValue(elementData, displayName, attachCss); toAttach.push({ id: 'element-' + Date.now(), name: displayName, fullName: displayName, value: value, + modelDescription: 'Structured browser element context with HTML path, attributes, and computed styles.', kind: 'element', icon: ThemeIcon.fromId(Codicon.layout.id), + ancestors: elementData.ancestors, + attributes: elementData.attributes, + computedStyles: elementData.computedStyles, + dimensions: elementData.dimensions, + innerText: elementData.innerText, }); // Attach screenshot if enabled @@ -770,6 +779,9 @@ export class BrowserEditor extends EditorPane { } } + /** + * Grab the current console logs from the active console session and attach them to chat. + */ async addConsoleLogsToChat(): Promise { const resourceUri = this.input?.resource; if (!resourceUri) { @@ -790,8 +802,9 @@ export class BrowserEditor extends EditorPane { name: localize('consoleLogs', 'Console Logs'), fullName: localize('consoleLogs', 'Console Logs'), value: logs, + modelDescription: 'Console logs captured from Integrated Browser.', kind: 'element', - icon: ThemeIcon.fromId(Codicon.output.id), + icon: ThemeIcon.fromId(Codicon.terminal.id), }); const widget = await this.chatWidgetService.revealWidget() ?? this.chatWidgetService.lastFocusedWidget; @@ -801,8 +814,11 @@ export class BrowserEditor extends EditorPane { } } + /** + * Start a console session to capture logs from the browser view. + */ private startConsoleSession(): void { - // don't restart if already running + // Don't restart if already running if (this._consoleSessionCts) { return; } @@ -823,6 +839,9 @@ export class BrowserEditor extends EditorPane { }); } + /** + * Stop the active console session. + */ private stopConsoleSession(): void { if (this._consoleSessionCts) { this._consoleSessionCts.dispose(true); @@ -830,6 +849,109 @@ export class BrowserEditor extends EditorPane { } } + private createElementContextValue(elementData: IElementData, displayName: string, attachCss: boolean): string { + const sections: string[] = []; + sections.push('Attached Element Context from Integrated Browser'); + sections.push(`Element: ${displayName}`); + + const htmlPath = this.formatElementPath(elementData.ancestors); + if (htmlPath) { + sections.push(`HTML Path:\n${htmlPath}`); + } + + const attributeTable = this.formatElementMap(elementData.attributes); + if (attributeTable) { + sections.push(`Attributes:\n${attributeTable}`); + } + + const computedStyleTable = this.formatElementMap(elementData.computedStyles); + if (computedStyleTable) { + sections.push(`Computed Styles:\n${computedStyleTable}`); + } + + if (elementData.dimensions) { + const { top, left, width, height } = elementData.dimensions; + sections.push( + `Dimensions:\n- top: ${Math.round(top)}px\n- left: ${Math.round(left)}px\n- width: ${Math.round(width)}px\n- height: ${Math.round(height)}px` + ); + } + + const innerText = elementData.innerText?.trim(); + if (innerText) { + sections.push(`Inner Text:\n\`\`\`text\n${innerText}\n\`\`\``); + } + + sections.push(`Outer HTML:\n\`\`\`html\n${elementData.outerHTML}\n\`\`\``); + + if (attachCss) { + sections.push(`Full Computed CSS:\n\`\`\`css\n${elementData.computedStyle}\n\`\`\``); + } + + return sections.join('\n\n'); + } + + private formatElementPath(ancestors: readonly IElementAncestor[] | undefined): string | undefined { + if (!ancestors || ancestors.length === 0) { + return undefined; + } + + return ancestors + .map(ancestor => { + const classes = ancestor.classNames?.length ? `.${ancestor.classNames.join('.')}` : ''; + const id = ancestor.id ? `#${ancestor.id}` : ''; + return `${ancestor.tagName}${id}${classes}`; + }) + .join(' > '); + } + + private formatElementMap(entries: Readonly> | undefined): string | undefined { + if (!entries || Object.keys(entries).length === 0) { + return undefined; + } + + const normalizedEntries = new Map(Object.entries(entries)); + const lines: string[] = []; + + const marginShorthand = this.createBoxShorthand(normalizedEntries, 'margin'); + if (marginShorthand) { + lines.push(`- margin: ${marginShorthand}`); + } + + const paddingShorthand = this.createBoxShorthand(normalizedEntries, 'padding'); + if (paddingShorthand) { + lines.push(`- padding: ${paddingShorthand}`); + } + + for (const [name, value] of Array.from(normalizedEntries.entries()).sort(([a], [b]) => a.localeCompare(b))) { + lines.push(`- ${name}: ${value}`); + } + + return lines.join('\n'); + } + + private createBoxShorthand(entries: Map, propertyName: 'margin' | 'padding'): string | undefined { + const topKey = `${propertyName}-top`; + const rightKey = `${propertyName}-right`; + const bottomKey = `${propertyName}-bottom`; + const leftKey = `${propertyName}-left`; + + const top = entries.get(topKey); + const right = entries.get(rightKey); + const bottom = entries.get(bottomKey); + const left = entries.get(leftKey); + + if (top === undefined || right === undefined || bottom === undefined || left === undefined) { + return undefined; + } + + entries.delete(topKey); + entries.delete(rightKey); + entries.delete(bottomKey); + entries.delete(leftKey); + + return `${top} ${right} ${bottom} ${left}`; + } + /** * Update navigation state and context keys */ diff --git a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorUtils.ts b/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorUtils.ts deleted file mode 100644 index 64b648b59ba19..0000000000000 --- a/src/vs/workbench/contrib/chat/browser/agentFeedback/agentFeedbackEditorUtils.ts +++ /dev/null @@ -1,29 +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 { URI } from '../../../../../base/common/uri.js'; -import { EditorResourceAccessor, SideBySideEditor } from '../../../../common/editor.js'; - -export function getActiveResourceCandidates(input: Parameters[0]): URI[] { - const result: URI[] = []; - const resources = EditorResourceAccessor.getOriginalUri(input, { supportSideBySide: SideBySideEditor.BOTH }); - if (!resources) { - return result; - } - - if (URI.isUri(resources)) { - result.push(resources); - return result; - } - - if (resources.secondary) { - result.push(resources.secondary); - } - if (resources.primary) { - result.push(resources.primary); - } - - return result; -} diff --git a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts index 7744f6a9e9f92..eb154e0b96f6a 100644 --- a/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts +++ b/src/vs/workbench/contrib/chat/browser/attachments/chatAttachmentWidgets.ts @@ -11,6 +11,7 @@ import { Button } from '../../../../../base/browser/ui/button/button.js'; import { HoverStyle, IDelayedHoverOptions, type IHoverLifecycleOptions, type IHoverOptions } from '../../../../../base/browser/ui/hover/hover.js'; import { createInstantHoverDelegate } from '../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { HoverPosition } from '../../../../../base/browser/ui/hover/hoverWidget.js'; +import { DomScrollableElement } from '../../../../../base/browser/ui/scrollbar/scrollableElement.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import * as event from '../../../../../base/common/event.js'; import { IMarkdownString, MarkdownString } from '../../../../../base/common/htmlContent.js'; @@ -19,6 +20,7 @@ import { KeyCode } from '../../../../../base/common/keyCodes.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../base/common/network.js'; import { basename, dirname } from '../../../../../base/common/path.js'; +import { ScrollbarVisibility } from '../../../../../base/common/scrollable.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { URI } from '../../../../../base/common/uri.js'; import { IRange } from '../../../../../editor/common/core/range.js'; @@ -77,6 +79,17 @@ const commonHoverLifecycleOptions: IHoverLifecycleOptions = { groupId: 'chat-attachments', }; +const KEY_ELEMENT_HOVER_COMPUTED_STYLE_PROPERTIES = [ + 'display', + 'position', + 'margin', + 'padding', + 'font-size', + 'font-family', + 'color', + 'background-color' +]; + abstract class AbstractChatAttachmentWidget extends Disposable { public readonly element: HTMLElement; public readonly label: IResourceLabel; @@ -927,7 +940,8 @@ export class ElementChatAttachmentWidget extends AbstractChatAttachmentWidget { @ICommandService commandService: ICommandService, @IOpenerService openerService: IOpenerService, @IConfigurationService configurationService: IConfigurationService, - @IEditorService editorService: IEditorService, + @IEditorService private readonly editorService: IEditorService, + @IHoverService private readonly hoverService: IHoverService, ) { super(attachment, options, container, contextResourceLabels, currentLanguageModel, commandService, openerService, configurationService); @@ -940,16 +954,282 @@ export class ElementChatAttachmentWidget extends AbstractChatAttachmentWidget { const withIcon = attachment.icon?.id ? `$(${attachment.icon.id})\u00A0${attachmentLabel}` : attachmentLabel; this.label.setLabel(withIcon, undefined, { title: localize('chat.clickToViewContents', "Click to view the contents of: {0}", attachmentLabel) }); + this._register(this.hoverService.setupDelayedHover(this.element, this.getHoverContent(attachment), commonHoverLifecycleOptions)); + this._register(dom.addDisposableListener(this.element, dom.EventType.CLICK, async () => { - const content = attachment.value?.toString() || ''; - await editorService.openEditor({ - resource: undefined, - contents: content, - options: { - pinned: true + await this.openElementAttachment(attachment); + })); + } + + private getHoverContent(attachment: IElementVariableEntry): IDelayedHoverOptions { + if (!this.shouldRenderRichElementHover(attachment)) { + return this.getSimpleHoverContent(attachment); + } + + const hoverElement = dom.$('div.chat-attached-context-hover.chat-element-hover'); + + // Wrap all sections in a scrollable container for VS Code styled scrollbar + const scrollableContent = dom.$('div.chat-element-hover-content'); + const innerScrollables: DomScrollableElement[] = []; + + // ELEMENT section: show the selected element tag with all attributes + { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.element', "ELEMENT")); + section.appendChild(header); + const elementPre = dom.$('pre.chat-element-hover-code'); + const elementCode = dom.$('code'); + // Build the element tag from the outerHTML (just the opening tag) + const tagDisplay = this.formatElementTag(attachment); + elementCode.textContent = tagDisplay; + elementPre.appendChild(elementCode); + const elementScrollable = this._register(new DomScrollableElement(elementPre, { + horizontal: ScrollbarVisibility.Auto, + vertical: ScrollbarVisibility.Hidden, + })); + innerScrollables.push(elementScrollable); + section.appendChild(elementScrollable.getDomNode()); + scrollableContent.appendChild(section); + } + + // KEY COMPUTED STYLES section + const computedStyleEntries = this.getComputedStyleEntriesForHover(attachment.computedStyles); + if (computedStyleEntries.length > 0) { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.computedStyles', "KEY COMPUTED STYLES")); + section.appendChild(header); + const table = dom.$('div.chat-element-hover-table'); + for (const [name, value] of computedStyleEntries) { + const row = dom.$('div.chat-element-hover-row'); + row.appendChild(dom.$('span.chat-element-hover-label', {}, `${name}:`)); + const valueContainer = dom.$('span.chat-element-hover-value'); + // Show color swatch for color properties + if ((name === 'color' || name === 'background-color') && value) { + const swatch = dom.$('span.chat-element-hover-color-swatch'); + swatch.style.backgroundColor = value; + valueContainer.appendChild(swatch); } - }); + valueContainer.appendChild(document.createTextNode(value)); + row.appendChild(valueContainer); + table.appendChild(row); + } + section.appendChild(table); + const showMoreButton = dom.$('button.chat-element-hover-show-more', { type: 'button' }, localize('chat.elementHover.showMore', "Show More...")); + this._register(dom.addDisposableListener(showMoreButton, dom.EventType.CLICK, async e => { + dom.EventHelper.stop(e, true); + await this.openElementAttachment(attachment); + })); + section.appendChild(showMoreButton); + scrollableContent.appendChild(section); + } + + // HTML PATH section: render ancestor chain as indented HTML tree + if (attachment.ancestors && attachment.ancestors.length > 1) { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.htmlPath', "HTML PATH")); + section.appendChild(header); + const lines: string[] = []; + for (let i = 0; i < attachment.ancestors.length; i++) { + const ancestor = attachment.ancestors[i]; + const indent = ' '.repeat(i); + const tag = this.formatAncestorTag(ancestor); + lines.push(`${indent}${tag}`); + } + const pathPre = dom.$('pre.chat-element-hover-code'); + const pathCode = dom.$('code'); + pathCode.textContent = lines.join('\n'); + pathPre.appendChild(pathCode); + const pathScrollable = this._register(new DomScrollableElement(pathPre, { + horizontal: ScrollbarVisibility.Auto, + vertical: ScrollbarVisibility.Hidden, + })); + innerScrollables.push(pathScrollable); + section.appendChild(pathScrollable.getDomNode()); + scrollableContent.appendChild(section); + } + + // ATTRIBUTES section + if (attachment.attributes && Object.keys(attachment.attributes).length > 0) { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.attributes', "ATTRIBUTES")); + section.appendChild(header); + const table = dom.$('div.chat-element-hover-table'); + for (const [name, value] of Object.entries(attachment.attributes)) { + const row = dom.$('div.chat-element-hover-row'); + row.appendChild(dom.$('span.chat-element-hover-label', {}, `${name}:`)); + row.appendChild(dom.$('span.chat-element-hover-value', {}, value)); + table.appendChild(row); + } + section.appendChild(table); + scrollableContent.appendChild(section); + } + + // POSITION & SIZE section + if (attachment.dimensions) { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.positionSize', "POSITION & SIZE")); + section.appendChild(header); + const table = dom.$('div.chat-element-hover-table'); + const dims: [string, number][] = [ + ['top:', attachment.dimensions.top], + ['left:', attachment.dimensions.left], + ['width:', attachment.dimensions.width], + ['height:', attachment.dimensions.height], + ]; + for (const [label, val] of dims) { + const row = dom.$('div.chat-element-hover-row'); + row.appendChild(dom.$('span.chat-element-hover-label', {}, label)); + row.appendChild(dom.$('span.chat-element-hover-value', {}, `${Math.round(val)}px`)); + table.appendChild(row); + } + section.appendChild(table); + scrollableContent.appendChild(section); + } + + // INNER TEXT section + if (attachment.innerText) { + const section = dom.$('div.chat-element-hover-section'); + const header = dom.$('div.chat-element-hover-header', {}, localize('chat.elementHover.innerText', "INNER TEXT")); + section.appendChild(header); + section.appendChild(dom.$('div.chat-element-hover-text', {}, attachment.innerText)); + scrollableContent.appendChild(section); + } + + const scrollableElement = this._register(new DomScrollableElement(scrollableContent, { + vertical: ScrollbarVisibility.Auto, + horizontal: ScrollbarVisibility.Hidden, + consumeMouseWheelIfScrollbarIsNeeded: true, })); + const scrollableDomNode = scrollableElement.getDomNode(); + scrollableDomNode.classList.add('chat-element-hover-scrollable'); + hoverElement.appendChild(scrollableDomNode); + + return { + ...commonHoverOptions, + content: hoverElement, + additionalClasses: ['chat-element-data-hover'], + onDidShow: () => { + for (const s of innerScrollables) { + s.scanDomNode(); + } + scrollableElement.scanDomNode(); + }, + }; + } + + private shouldRenderRichElementHover(attachment: IElementVariableEntry): boolean { + if (attachment.dimensions || attachment.innerText) { + return true; + } + + if (attachment.ancestors && attachment.ancestors.length > 0) { + return true; + } + + if (attachment.attributes && Object.keys(attachment.attributes).length > 0) { + return true; + } + + if (attachment.computedStyles && Object.keys(attachment.computedStyles).length > 0) { + return true; + } + + return false; + } + + private getSimpleHoverContent(attachment: IElementVariableEntry): IDelayedHoverOptions { + const content = attachment.value?.toString() ?? ''; + const hoverContent = new MarkdownString(); + hoverContent.appendText(attachment.fullName ?? attachment.name); + if (content.trim().length > 0) { + hoverContent.appendMarkdown('\n\n'); + hoverContent.appendCodeblock('text', content); + } + + return { + ...commonHoverOptions, + content: hoverContent, + }; + } + + private getComputedStyleEntriesForHover(computedStyles: Readonly> | undefined): ReadonlyArray<[string, string]> { + if (!computedStyles) { + return []; + } + + const keyEntries: Array<[string, string]> = []; + for (const property of KEY_ELEMENT_HOVER_COMPUTED_STYLE_PROPERTIES) { + if (property === 'margin' || property === 'padding') { + const shorthand = this.getBoxShorthandValue(computedStyles, property); + if (typeof shorthand === 'string') { + keyEntries.push([property, shorthand]); + continue; + } + } + + const value = computedStyles[property]; + if (typeof value === 'string') { + keyEntries.push([property, value]); + } + } + + // Fallback for older payloads that might not include the key properties. + if (keyEntries.length > 0) { + return keyEntries; + } + + return Object.entries(computedStyles).slice(0, KEY_ELEMENT_HOVER_COMPUTED_STYLE_PROPERTIES.length); + } + + private getBoxShorthandValue(computedStyles: Readonly>, propertyName: 'margin' | 'padding'): string | undefined { + const top = computedStyles[`${propertyName}-top`]; + const right = computedStyles[`${propertyName}-right`]; + const bottom = computedStyles[`${propertyName}-bottom`]; + const left = computedStyles[`${propertyName}-left`]; + + if (typeof top === 'string' && typeof right === 'string' && typeof bottom === 'string' && typeof left === 'string') { + return `${top} ${right} ${bottom} ${left}`; + } + + return computedStyles[propertyName]; + } + + private async openElementAttachment(attachment: IElementVariableEntry): Promise { + const content = attachment.value?.toString() || ''; + await this.editorService.openEditor({ + resource: undefined, + contents: content, + options: { + pinned: true + } + }); + } + + private formatElementTag(attachment: IElementVariableEntry): string { + // Extract the opening tag from the outerHTML within the value string + // Value format: "Attached HTML and CSS Context\n\n...\n\n..." + const content = attachment.value?.toString() ?? ''; + const htmlMatch = content.match(/\n\n(<[^>]+>)/); + if (htmlMatch) { + return htmlMatch[1]; + } + // Fallback: try first tag in content + const fallback = content.match(/<([^>]+)>/); + if (fallback) { + return `<${fallback[1]}>`; + } + return `<${attachment.name}>`; + } + + private formatAncestorTag(ancestor: { tagName: string; id?: string; classNames?: string[] }): string { + const parts = [`<${ancestor.tagName}`]; + if (ancestor.classNames?.length) { + parts.push(` class="${ancestor.classNames.join(' ')}"`); + } + if (ancestor.id) { + parts.push(` id="${ancestor.id}"`); + } + return parts.join('') + '>'; } } diff --git a/src/vs/workbench/contrib/chat/browser/attachments/simpleBrowserEditorOverlay.ts b/src/vs/workbench/contrib/chat/browser/attachments/simpleBrowserEditorOverlay.ts index d15972e2b3a7e..a270c52b91ddd 100644 --- a/src/vs/workbench/contrib/chat/browser/attachments/simpleBrowserEditorOverlay.ts +++ b/src/vs/workbench/contrib/chat/browser/attachments/simpleBrowserEditorOverlay.ts @@ -298,6 +298,11 @@ class SimpleBrowserOverlayWidget { value: value, kind: 'element', icon: ThemeIcon.fromId(Codicon.layout.id), + ancestors: elementData.ancestors, + attributes: elementData.attributes, + computedStyles: elementData.computedStyles, + dimensions: elementData.dimensions, + innerText: elementData.innerText, }); if (this.configurationService.getValue('chat.sendElementsToChat.attachImages')) { diff --git a/src/vs/workbench/contrib/chat/browser/chat.contribution.ts b/src/vs/workbench/contrib/chat/browser/chat.contribution.ts index 5f8f72a64e3c4..5144e6372af8b 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.contribution.ts @@ -141,10 +141,6 @@ import { ChatWindowNotifier } from './chatWindowNotifier.js'; import { ChatRepoInfoContribution } from './chatRepoInfo.js'; import { VALID_PROMPT_FOLDER_PATTERN } from '../common/promptSyntax/utils/promptFilesLocator.js'; import { ChatTipService, IChatTipService } from './chatTipService.js'; -import { AgentFeedbackService, IAgentFeedbackService } from './agentFeedback/agentFeedbackService.js'; -import { AgentFeedbackAttachmentContribution } from './agentFeedback/agentFeedbackAttachment.js'; -import { AgentFeedbackEditorOverlay } from './agentFeedback/agentFeedbackEditorOverlay.js'; -import { registerAgentFeedbackEditorActions } from './agentFeedback/agentFeedbackEditorActions.js'; import { ChatQueuePickerRendering } from './widget/input/chatQueuePickerActionItem.js'; import { ExploreAgentDefaultModel } from './exploreAgentDefaultModel.js'; import { PlanAgentDefaultModel } from './planAgentDefaultModel.js'; @@ -1159,7 +1155,7 @@ configurationRegistry.registerConfiguration({ [ChatConfiguration.ExitAfterDelegation]: { type: 'boolean', description: nls.localize('chat.exitAfterDelegation', "Controls whether the chat panel automatically exits after delegating a request to another session."), - default: true, + default: false, tags: ['preview'], }, 'chat.extensionUnification.enabled': { @@ -1482,7 +1478,6 @@ registerWorkbenchContribution2(ChatAgentRecommendation.ID, ChatAgentRecommendati registerWorkbenchContribution2(ChatEditingEditorAccessibility.ID, ChatEditingEditorAccessibility, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(ChatQueuePickerRendering.ID, ChatQueuePickerRendering, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(ChatEditingEditorOverlay.ID, ChatEditingEditorOverlay, WorkbenchPhase.AfterRestored); -registerWorkbenchContribution2(AgentFeedbackEditorOverlay.ID, AgentFeedbackEditorOverlay, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(SimpleBrowserOverlay.ID, SimpleBrowserOverlay, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(ChatEditingEditorContextKeys.ID, ChatEditingEditorContextKeys, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(ChatTransferContribution.ID, ChatTransferContribution, WorkbenchPhase.BlockRestore); @@ -1494,7 +1489,6 @@ registerWorkbenchContribution2(UserToolSetsContributions.ID, UserToolSetsContrib registerWorkbenchContribution2(PromptLanguageFeaturesProvider.ID, PromptLanguageFeaturesProvider, WorkbenchPhase.Eventually); registerWorkbenchContribution2(ChatWindowNotifier.ID, ChatWindowNotifier, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(ChatRepoInfoContribution.ID, ChatRepoInfoContribution, WorkbenchPhase.Eventually); -registerWorkbenchContribution2(AgentFeedbackAttachmentContribution.ID, AgentFeedbackAttachmentContribution, WorkbenchPhase.AfterRestored); registerChatActions(); registerChatAccessibilityActions(); @@ -1514,7 +1508,6 @@ registerNewChatActions(); registerChatContextActions(); registerChatDeveloperActions(); registerChatEditorActions(); -registerAgentFeedbackEditorActions(); registerChatElicitationActions(); registerChatToolActions(); registerLanguageModelActions(); @@ -1551,6 +1544,5 @@ registerSingleton(IChatTodoListService, ChatTodoListService, InstantiationType.D registerSingleton(IChatOutputRendererService, ChatOutputRendererService, InstantiationType.Delayed); registerSingleton(IChatLayoutService, ChatLayoutService, InstantiationType.Delayed); registerSingleton(IChatTipService, ChatTipService, InstantiationType.Delayed); -registerSingleton(IAgentFeedbackService, AgentFeedbackService, InstantiationType.Delayed); ChatWidget.CONTRIBS.push(ChatDynamicVariableModel); diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatInlineAnchorWidget.css b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatInlineAnchorWidget.css index d277f2219647e..d93bea631ad36 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatInlineAnchorWidget.css +++ b/src/vs/workbench/contrib/chat/browser/widget/chatContentParts/media/chatInlineAnchorWidget.css @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ .chat-inline-anchor-widget { - border: 1px solid var(--vscode-chat-requestBorder, var(--vscode-input-background, transparent)); + border: 0.5px solid var(--vscode-chat-requestBorder, var(--vscode-input-background, transparent)); border-radius: 4px; margin: 0 1px; padding: 1px 3px; @@ -12,11 +12,11 @@ width: fit-content; font-weight: normal; text-decoration: none; + font-size: var(--vscode-chat-font-size-body-s); } .chat-inline-anchor-widget .icon-label { padding: 0 3px; - text-wrap: wrap; .label-suffix { color: var(--vscode-peekViewTitleDescription-foreground); diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts index 4188fb18fd0be..66ff7a09fea72 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/editor/chatInputCompletions.ts @@ -79,7 +79,7 @@ class SlashCommandCompletions extends Disposable { return null; } - if (widget.lockedAgentId) { + if (widget.lockedAgentId && !widget.attachmentCapabilities.supportsPromptAttachments) { return null; } 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 095c128b58c26..e0c99f4eec624 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/media/chat.css +++ b/src/vs/workbench/contrib/chat/browser/widget/media/chat.css @@ -392,7 +392,7 @@ .interactive-item-container .value .rendered-markdown h1 { font-size: var(--vscode-chat-font-size-body-xxl); font-weight: 600; - margin: 16px 0 8px 0; + margin: 1.5em 0 0.875em 0; font-family: var(--vscode-chat-font-family, inherit); } @@ -400,14 +400,14 @@ .interactive-item-container .value .rendered-markdown h2 { font-size: var(--vscode-chat-font-size-body-xl); font-weight: 600; - margin: 16px 0 8px 0; + margin: 1.5em 0 0.875em 0; font-family: var(--vscode-chat-font-family, inherit); } .interactive-item-container .value .rendered-markdown h3 { font-size: var(--vscode-chat-font-size-body-l); font-weight: 600; - margin: 16px 0 8px 0; + margin: 1.5em 0 0.875em 0; font-family: var(--vscode-chat-font-family, inherit); } @@ -417,8 +417,7 @@ .interactive-item-container.editing-session .value .rendered-markdown h3 { font-size: var(--vscode-chat-font-size-body-m); - margin: 0 0 8px 0; - font-weight: unset; + margin: 1.5em 0 0.875em 0; } /* Codicons next to text need to be aligned with the text */ @@ -668,7 +667,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .monaco-tokenized-source, code { font-family: var(--monaco-monospace-font); - font-size: var(--vscode-chat-font-size-body-s); + font-size: var(--vscode-chat-font-size-body-xs); color: var(--vscode-textPreformat-foreground); background-color: var(--vscode-textPreformat-background); padding: 1px 3px; @@ -2383,6 +2382,130 @@ have to be updated for changes to the rules above, or to support more deeply nes margin-top: 2px; } +/* Element hover (DevTools-style) */ +.chat-element-hover { + max-width: 400px; + min-width: 250px; +} + +.monaco-hover.workbench-hover.chat-element-data-hover .hover-contents.html-hover-contents { + padding: 0; +} + +.monaco-hover.workbench-hover.chat-element-data-hover .chat-element-hover-scrollable { + width: 100%; +} + +.chat-element-hover.chat-attached-context-hover { + padding: 6px 0 6px 6px; +} + +.chat-element-hover-content { + max-height: 500px; + box-sizing: border-box; + padding-right: 10px; + padding-bottom: 15px; +} + +.chat-element-hover .chat-element-hover-section { + padding: 4px 6px; +} + +.chat-element-hover .chat-element-hover-section + .chat-element-hover-section { + border-top: 1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.2)); +} + +.chat-element-hover .chat-element-hover-header { + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + color: var(--vscode-descriptionForeground); + letter-spacing: 0.5px; + margin-bottom: 4px; +} + +.chat-element-hover .chat-element-hover-code { + margin: 0; + padding: 4px 6px; + background: var(--vscode-textCodeBlock-background); + border-radius: 3px; + font-family: var(--monaco-monospace-font); + font-size: 12px; + line-height: 1.5; + white-space: pre; + overflow: hidden; + color: var(--vscode-editor-foreground); +} + +.chat-element-hover .chat-element-hover-code code { + font-family: inherit; + font-size: inherit; + background: transparent; + padding: 0; + border-radius: 0; + display: block; +} + +.chat-element-hover .chat-element-hover-table { + display: grid; + grid-template-columns: auto 1fr; + gap: 2px 8px; +} + +.chat-element-hover .chat-element-hover-row { + display: contents; +} + +.chat-element-hover .chat-element-hover-label { + font-family: var(--monaco-monospace-font); + font-size: 12px; + color: var(--vscode-debugTokenExpression-name); + white-space: nowrap; +} + +.chat-element-hover .chat-element-hover-value { + font-family: var(--monaco-monospace-font); + font-size: 12px; + color: var(--vscode-editor-foreground); + word-break: break-all; + display: flex; + align-items: center; + gap: 4px; +} + +.chat-element-hover .chat-element-hover-color-swatch { + display: inline-block; + width: 12px; + height: 12px; + border: 1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.4)); + border-radius: 2px; + flex-shrink: 0; +} + +.chat-element-hover .chat-element-hover-text { + font-family: var(--monaco-monospace-font); + font-size: 12px; + color: var(--vscode-editor-foreground); + white-space: pre-wrap; + word-break: break-word; +} + +.chat-element-hover .chat-element-hover-show-more { + background: none; + border: none; + padding: 0; + margin-top: 6px; + color: var(--vscode-textLink-foreground); + cursor: pointer; + font-size: 12px; + text-decoration: none; +} + +.chat-element-hover .chat-element-hover-show-more:hover, +.chat-element-hover .chat-element-hover-show-more:focus-visible { + color: var(--vscode-textLink-activeForeground); +} + .chat-attached-context-attachment .chat-attached-context-pill { font-size: 12px; @@ -2522,7 +2645,7 @@ have to be updated for changes to the rules above, or to support more deeply nes .interactive-item-container.interactive-request .value .rendered-markdown { background-color: var(--vscode-chat-requestBubbleBackground); - border-radius: 8px; + border-radius: var(--vscode-cornerRadius-xLarge); padding: 8px 12px; max-width: 90%; margin-left: auto; diff --git a/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts b/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts index 58a14a2ad8966..5655cc695fd95 100644 --- a/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts +++ b/src/vs/workbench/contrib/chat/common/attachments/chatVariableEntries.ts @@ -222,8 +222,19 @@ export interface IDiagnosticVariableEntry extends IBaseChatRequestVariableEntry, readonly kind: 'diagnostic'; } +export interface IElementAncestorData { + readonly tagName: string; + readonly id?: string; + readonly classNames?: string[]; +} + export interface IElementVariableEntry extends IBaseChatRequestVariableEntry { readonly kind: 'element'; + readonly ancestors?: IElementAncestorData[]; + readonly attributes?: Record; + readonly computedStyles?: Record; + readonly dimensions?: { readonly top: number; readonly left: number; readonly width: number; readonly height: number }; + readonly innerText?: string; } export interface IPromptFileVariableEntry extends IBaseChatRequestVariableEntry { diff --git a/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts b/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts index 0dfb08c73e85d..60c1c4049c2cf 100644 --- a/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts +++ b/src/vs/workbench/contrib/mcp/browser/mcp.contribution.ts @@ -35,6 +35,7 @@ import { McpService } from '../common/mcpService.js'; import { IMcpElicitationService, IMcpSamplingService, IMcpService, IMcpWorkbenchService } from '../common/mcpTypes.js'; import { IWorkbenchMcpGatewayService } from '../common/mcpGatewayService.js'; import { BrowserMcpGatewayService } from './mcpGatewayService.js'; +import { McpGatewayToolBrokerContribution } from './mcpGatewayToolBrokerContribution.js'; import { McpAddContextContribution } from './mcpAddContextContribution.js'; import { AddConfigurationAction, EditStoredInput, InstallFromManifestAction, ListMcpServerCommand, McpBrowseCommand, McpBrowseResourcesCommand, McpConfigureSamplingModels, McpConfirmationServerOptionsCommand, MCPServerActionRendering, McpServerOptionsCommand, McpSkipCurrentAutostartCommand, McpStartPromptingServerCommand, OpenRemoteUserMcpResourceCommand, OpenUserMcpResourceCommand, OpenWorkspaceFolderMcpResourceCommand, OpenWorkspaceMcpResourceCommand, RemoveStoredInput, ResetMcpCachedTools, ResetMcpTrustCommand, RestartServer, ShowConfiguration, ShowInstalledMcpServersCommand, ShowOutput, StartServer, StopServer } from './mcpCommands.js'; import { McpDiscovery } from './mcpDiscovery.js'; @@ -65,6 +66,7 @@ registerWorkbenchContribution2('mcpContextKeys', McpContextKeysController, Workb registerWorkbenchContribution2('mcpLanguageFeatures', McpLanguageFeatures, WorkbenchPhase.Eventually); registerWorkbenchContribution2('mcpResourceFilesystem', McpResourceFilesystem, WorkbenchPhase.BlockRestore); registerWorkbenchContribution2(McpLanguageModelToolContribution.ID, McpLanguageModelToolContribution, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2('mcpGatewayToolBrokerRemote', McpGatewayToolBrokerContribution, WorkbenchPhase.AfterRestored); registerAction2(ListMcpServerCommand); registerAction2(McpServerOptionsCommand); diff --git a/src/vs/workbench/contrib/mcp/browser/mcpGatewayToolBrokerContribution.ts b/src/vs/workbench/contrib/mcp/browser/mcpGatewayToolBrokerContribution.ts new file mode 100644 index 0000000000000..175bb839214a9 --- /dev/null +++ b/src/vs/workbench/contrib/mcp/browser/mcpGatewayToolBrokerContribution.ts @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { McpGatewayToolBrokerChannelName } from '../../../../platform/mcp/common/mcpGateway.js'; +import { IRemoteAgentService } from '../../../services/remote/common/remoteAgentService.js'; +import { IMcpService } from '../common/mcpTypes.js'; +import { McpGatewayToolBrokerChannel } from '../common/mcpGatewayToolBrokerChannel.js'; + +export class McpGatewayToolBrokerContribution implements IWorkbenchContribution { + constructor( + @IRemoteAgentService remoteAgentService: IRemoteAgentService, + @IMcpService mcpService: IMcpService, + ) { + remoteAgentService.getConnection()?.registerChannel(McpGatewayToolBrokerChannelName, new McpGatewayToolBrokerChannel(mcpService)); + } +} diff --git a/src/vs/workbench/contrib/mcp/common/mcpGatewayToolBrokerChannel.ts b/src/vs/workbench/contrib/mcp/common/mcpGatewayToolBrokerChannel.ts new file mode 100644 index 0000000000000..796de07cf62bf --- /dev/null +++ b/src/vs/workbench/contrib/mcp/common/mcpGatewayToolBrokerChannel.ts @@ -0,0 +1,119 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../base/common/event.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { autorun } from '../../../../base/common/observable.js'; +import { IServerChannel } from '../../../../base/parts/ipc/common/ipc.js'; +import { IMcpServer, IMcpService, McpServerCacheState, McpToolVisibility } from './mcpTypes.js'; +import { MCP } from '../../../../platform/mcp/common/modelContextProtocol.js'; +import { startServerAndWaitForLiveTools } from './mcpTypesUtils.js'; + +interface ICallToolArgs { + name: string; + args: Record; +} + +export class McpGatewayToolBrokerChannel extends Disposable implements IServerChannel { + private readonly _onDidChangeTools = this._register(new Emitter()); + + constructor( + private readonly _mcpService: IMcpService, + ) { + super(); + + let initialized = false; + this._register(autorun(reader => { + for (const server of this._mcpService.servers.read(reader)) { + server.tools.read(reader); + } + + if (initialized) { + this._onDidChangeTools.fire(); + } else { + initialized = true; + } + })); + } + + listen(_ctx: unknown, event: string): Event { + switch (event) { + case 'onDidChangeTools': + return this._onDidChangeTools.event as Event; + } + + throw new Error(`Invalid listen: ${event}`); + } + + async call(_ctx: unknown, command: string, arg?: unknown, cancellationToken?: CancellationToken): Promise { + switch (command) { + case 'listTools': { + const tools = await this._listTools(); + return tools as T; + } + case 'callTool': { + const { name, args } = arg as ICallToolArgs; + const result = await this._callTool(name, args || {}, cancellationToken); + return result as T; + } + } + + throw new Error(`Invalid call: ${command}`); + } + + private async _listTools(): Promise { + const mcpTools: MCP.Tool[] = []; + const servers = this._mcpService.servers.get(); + await Promise.all(servers.map(server => this._ensureServerReady(server))); + + for (const server of servers) { + const cacheState = server.cacheState.get(); + if (cacheState !== McpServerCacheState.Live && cacheState !== McpServerCacheState.Cached && cacheState !== McpServerCacheState.RefreshingFromCached) { + continue; + } + + for (const tool of server.tools.get()) { + if (!(tool.visibility & McpToolVisibility.Model)) { + continue; + } + + mcpTools.push(tool.definition); + } + } + + return mcpTools; + } + + private async _callTool(name: string, args: Record, token: CancellationToken = CancellationToken.None): Promise { + for (const server of this._mcpService.servers.get()) { + const tool = server.tools.get().find(t => + t.definition.name === name && (t.visibility & McpToolVisibility.Model) + ); + + if (tool) { + return tool.call(args, undefined, token); + } + } + + throw new Error(`Unknown tool: ${name}`); + } + + private async _ensureServerReady(server: IMcpServer): Promise { + const cacheState = server.cacheState.get(); + if (cacheState !== McpServerCacheState.Unknown && cacheState !== McpServerCacheState.Outdated) { + return true; + } + + try { + return await startServerAndWaitForLiveTools(server, { + promptType: 'all-untrusted', + errorOnUserInteraction: true, + }); + } catch { + return false; + } + } +} diff --git a/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts b/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts index b71f9791274a8..218f3ab72c888 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpServerRequestHandler.ts @@ -5,11 +5,12 @@ import { equals } from '../../../../base/common/arrays.js'; import { assertNever, softAssertNever } from '../../../../base/common/assert.js'; -import { DeferredPromise, disposableTimeout, IntervalTimer } from '../../../../base/common/async.js'; +import { DeferredPromise, disposableTimeout, IntervalTimer, isThenable } from '../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; import { CancellationError } from '../../../../base/common/errors.js'; import { Emitter } from '../../../../base/common/event.js'; import { Iterable } from '../../../../base/common/iterator.js'; +import { JsonRpcError, JsonRpcProtocol } from '../../../../base/common/jsonRpcProtocol.js'; import { Disposable, DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; import { autorun, ISettableObservable, ObservablePromise, observableValue, transaction } from '../../../../base/common/observable.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; @@ -21,13 +22,6 @@ import { IMcpClientMethods, McpConnectionState, McpError, MpcResponseError } fro import { isTaskResult, translateMcpLogMessage } from './mcpTypesUtils.js'; import { MCP } from './modelContextProtocol.js'; -/** - * Maps request IDs to handlers. - */ -interface PendingRequest { - promise: DeferredPromise; -} - export interface McpRoot { uri: string; name?: string; @@ -51,8 +45,7 @@ export interface IMcpServerRequestHandlerOptions extends IMcpClientMethods { * handling of ping requests and typed client request methods. */ export class McpServerRequestHandler extends Disposable { - private _nextRequestId = 1; - private readonly _pendingRequests = new Map(); + private readonly _rpc: JsonRpcProtocol; private _hasAnnouncedRoots = false; private _roots: MCP.Root[] = []; @@ -185,6 +178,14 @@ export class McpServerRequestHandler extends Disposable { this._elicitationRequestHandler = elicitationRequestHandler; this._taskManager = taskManager; + this._rpc = this._register(new JsonRpcProtocol( + message => this.send(message as MCP.JSONRPCMessage), + { + handleRequest: (request, token) => this.handleServerRequest(request as MCP.JSONRPCRequest & MCP.ServerRequest, token), + handleNotification: notification => this.handleServerNotification(notification as MCP.JSONRPCNotification & MCP.ServerNotification), + } + )); + // Attach this handler to the task manager this._taskManager.setHandler(this); this._register(this._taskManager.onDidUpdateTask(task => { @@ -196,7 +197,12 @@ export class McpServerRequestHandler extends Disposable { })); this._register(toDisposable(() => this._taskManager.setHandler(undefined))); - this._register(launch.onDidReceiveMessage(message => this.handleMessage(message))); + this._register(launch.onDidReceiveMessage(message => { + if (canLog(this.logger.getLevel(), this._requestLogLevel)) { + log(this.logger, this._requestLogLevel, `[server -> editor] ${JSON.stringify(message)}`); + } + void this._rpc.handleMessage(message); + })); this._register(autorun(reader => { const state = launch.state.read(reader).state; // the handler will get disposed when the launch stops, but if we're still @@ -228,36 +234,16 @@ export class McpServerRequestHandler extends Disposable { return Promise.reject(new CancellationError()); } - const id = this._nextRequestId++; - - // Create the full JSON-RPC request - const jsonRpcRequest: MCP.JSONRPCRequest = { - jsonrpc: MCP.JSONRPC_VERSION, - id, - ...request - }; - - const promise = new DeferredPromise(); - // Store the pending request - this._pendingRequests.set(id, { promise }); - // Set up cancellation - const cancelListener = token.onCancellationRequested(() => { - if (!promise.isSettled) { - this._pendingRequests.delete(id); - this.sendNotification({ method: 'notifications/cancelled', params: { requestId: id } }); - promise.cancel(); + return this._rpc.sendRequest( + request, + token, + id => this.sendNotification({ method: 'notifications/cancelled', params: { requestId: id } }) + ).catch(error => { + if (error instanceof JsonRpcError) { + throw new MpcResponseError(error.message, error.code, error.data); } - cancelListener.dispose(); - }); - - // Send the request - this.send(jsonRpcRequest); - const ret = promise.p.finally(() => { - cancelListener.dispose(); - this._pendingRequests.delete(id); + throw error; }); - - return ret as Promise; } private send(mcp: MCP.JSONRPCMessage) { @@ -297,68 +283,25 @@ export class McpServerRequestHandler extends Disposable { } /** - * Handle incoming messages from the server - */ - private handleMessage(message: MCP.JSONRPCMessage): void { - if (canLog(this.logger.getLevel(), this._requestLogLevel)) { // avoid building the string if we don't need to - log(this.logger, this._requestLogLevel, `[server -> editor] ${JSON.stringify(message)}`); - } - - // Handle responses to our requests - if ('id' in message) { - if ('result' in message) { - this.handleResult(message); - } else if ('error' in message) { - this.handleError(message); - } - } - - // Handle requests from the server - if ('method' in message) { - if ('id' in message) { - this.handleServerRequest(message as MCP.JSONRPCRequest & MCP.ServerRequest); - } else { - this.handleServerNotification(message as MCP.JSONRPCNotification & MCP.ServerNotification); - } - } - } - - /** - * Handle successful responses + * Handle incoming server requests */ - 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); + private handleServerRequest(request: MCP.JSONRPCRequest & MCP.ServerRequest, token: CancellationToken): MCP.Result | Promise { + const mapError = (error: unknown): JsonRpcError => { + if (error instanceof McpError) { + return new JsonRpcError(error.code, error.message, error.data); } - } - } - /** - * Handle error responses - */ - 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)); - } - } - } + this.logger.error(`Error handling request ${request.method}:`, error); + const mcpError = McpError.unknown(error instanceof Error ? error : new Error(String(error))); + return new JsonRpcError(mcpError.code, mcpError.message, mcpError.data); + }; - /** - * Handle incoming server requests - */ - private async handleServerRequest(request: MCP.JSONRPCRequest & MCP.ServerRequest): Promise { try { - let response: MCP.Result | undefined; + let result: MCP.Result | Promise; if (request.method === 'ping') { - response = this.handlePing(request); + result = this.handlePing(request); } else if (request.method === 'roots/list') { - response = this.handleRootsList(request); + result = this.handleRootsList(request); } else if (request.method === 'sampling/createMessage' && this._createMessageRequestHandler) { // Check if this is a task-augmented request if (request.params.task) { @@ -368,9 +311,9 @@ export class McpServerRequestHandler extends Disposable { ); taskResult._meta ??= {}; taskResult._meta['io.modelcontextprotocol/related-task'] = { taskId: taskResult.task.taskId }; - response = taskResult; + result = taskResult; } else { - response = await this._createMessageRequestHandler(request.params); + result = this._createMessageRequestHandler(request.params, token); } } else if (request.method === 'elicitation/create' && this._elicitationRequestHandler) { // Check if this is a task-augmented request @@ -381,84 +324,76 @@ export class McpServerRequestHandler extends Disposable { ); taskResult._meta ??= {}; taskResult._meta['io.modelcontextprotocol/related-task'] = { taskId: taskResult.task.taskId }; - response = taskResult; + result = taskResult; } else { - response = await this._elicitationRequestHandler(request.params); + result = this._elicitationRequestHandler(request.params, token); } } else if (request.method === 'tasks/get') { - response = this._taskManager.getTask(request.params.taskId); + result = this._taskManager.getTask(request.params.taskId); } else if (request.method === 'tasks/result') { - response = await this._taskManager.getTaskResult(request.params.taskId); + result = this._taskManager.getTaskResult(request.params.taskId); } else if (request.method === 'tasks/cancel') { - response = this._taskManager.cancelTask(request.params.taskId); + result = this._taskManager.cancelTask(request.params.taskId); } else if (request.method === 'tasks/list') { - response = this._taskManager.listTasks(); + result = this._taskManager.listTasks(); } else { throw McpError.methodNotFound(request.method); } - this.respondToRequest(request, response); - } catch (e) { - if (!(e instanceof McpError)) { - this.logger.error(`Error handling request ${request.method}:`, e); - e = McpError.unknown(e); - } - const errorResponse: MCP.JSONRPCErrorResponse = { - jsonrpc: MCP.JSONRPC_VERSION, - id: request.id, - error: { - code: e.code, - message: e.message, - data: e.data, - } - }; + if (isThenable(result)) { + return result.then(undefined, (error: unknown) => { + throw mapError(error); + }); + } - this.send(errorResponse); + return result; + } catch (e) { + throw mapError(e); } } /** * Handle incoming server notifications */ private handleServerNotification(request: MCP.JSONRPCNotification & MCP.ServerNotification): void { - switch (request.method) { - case 'notifications/message': - return this.handleLoggingNotification(request); - case 'notifications/cancelled': - this._onDidReceiveCancelledNotification.fire(request); - return this.handleCancelledNotification(request); - case 'notifications/progress': - this._onDidReceiveProgressNotification.fire(request); - return; - case 'notifications/resources/list_changed': - this._onDidChangeResourceList.fire(); - return; - case 'notifications/resources/updated': - this._onDidUpdateResource.fire(request); - return; - case 'notifications/tools/list_changed': - this._onDidChangeToolList.fire(); - return; - case 'notifications/prompts/list_changed': - this._onDidChangePromptList.fire(); - return; - case 'notifications/elicitation/complete': - this._onDidReceiveElicitationCompleteNotification.fire(request); - return; - case 'notifications/tasks/status': - this._taskManager.getClientTask(request.params.taskId)?.onDidUpdateState(request.params); - return; - default: - softAssertNever(request); + try { + switch (request.method) { + case 'notifications/message': + return this.handleLoggingNotification(request); + case 'notifications/cancelled': + this._onDidReceiveCancelledNotification.fire(request); + return this.handleCancelledNotification(request); + case 'notifications/progress': + this._onDidReceiveProgressNotification.fire(request); + return; + case 'notifications/resources/list_changed': + this._onDidChangeResourceList.fire(); + return; + case 'notifications/resources/updated': + this._onDidUpdateResource.fire(request); + return; + case 'notifications/tools/list_changed': + this._onDidChangeToolList.fire(); + return; + case 'notifications/prompts/list_changed': + this._onDidChangePromptList.fire(); + return; + case 'notifications/elicitation/complete': + this._onDidReceiveElicitationCompleteNotification.fire(request); + return; + case 'notifications/tasks/status': + this._taskManager.getClientTask(request.params.taskId)?.onDidUpdateState(request.params); + return; + default: + softAssertNever(request); + } + } catch (error) { + this.logger.error(`Error handling notification ${request.method}:`, error); } } private handleCancelledNotification(request: MCP.CancelledNotification): void { if (request.params.requestId) { - const pendingRequest = this._pendingRequests.get(request.params.requestId); - if (pendingRequest) { - this._pendingRequests.delete(request.params.requestId); - pendingRequest.promise.cancel(); - } + this._rpc.cancelPendingRequest(request.params.requestId); } } @@ -466,18 +401,6 @@ export class McpServerRequestHandler extends Disposable { translateMcpLogMessage(this.logger, request.params); } - /** - * Send a generic response to a request - */ - private respondToRequest(request: MCP.JSONRPCRequest, result: MCP.Result): void { - const response: MCP.JSONRPCResponse = { - jsonrpc: MCP.JSONRPC_VERSION, - id: request.id, - result - }; - this.send(response); - } - /** * Send a response to a ping request */ @@ -494,8 +417,7 @@ export class McpServerRequestHandler extends Disposable { } private cancelAllRequests() { - this._pendingRequests.forEach(pending => pending.promise.cancel()); - this._pendingRequests.clear(); + this._rpc.cancelAllRequests(); } public override dispose(): void { diff --git a/src/vs/workbench/contrib/mcp/common/mcpTypesUtils.ts b/src/vs/workbench/contrib/mcp/common/mcpTypesUtils.ts index cdd61709f5927..a91311a81625f 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpTypesUtils.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpTypesUtils.ts @@ -75,6 +75,7 @@ export async function startServerAndWaitForLiveTools(server: IMcpServer, opts?: } })); }); + store.dispose(); if (ok) { await timeout(0); // let the tools register in the language model contribution diff --git a/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts b/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts index db33783efc616..070aa5d45c384 100644 --- a/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts +++ b/src/vs/workbench/contrib/mcp/common/modelContextProtocol.ts @@ -3,3275 +3,4 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -/* eslint-disable local/code-no-unexternalized-strings */ - -//#region proposals -/** - * MCP protocol proposals. - * - Proposals here MUST have an MCP PR linked to them - * - Proposals here are subject to change and SHALL be removed when - * the upstream MCP PR is merged or closed. - */ -export namespace MCP { - - // Nothing, yet - -} - -//#endregion - -/** - * Schema updated from the Model Context Protocol repository at - * https://github.com/modelcontextprotocol/specification/tree/main/schema - * - * ⚠️ Do not edit within `namespace` manually except to update schema versions ⚠️ - */ -export namespace MCP { - /* JSON-RPC types */ - - /** - * Refers to any valid JSON-RPC object that can be decoded off the wire, or encoded to be sent. - * - * @category JSON-RPC - */ - export type JSONRPCMessage = - | JSONRPCRequest - | JSONRPCNotification - | 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. - * - * @category Common Types - */ - export type ProgressToken = string | number; - - /** - * An opaque token used to represent a cursor for pagination. - * - * @category Common Types - */ - export type Cursor = string; - - /** - * Common params for any task-augmented request. - * - * @internal - */ - export interface TaskAugmentedRequestParams extends RequestParams { - /** - * If specified, the caller is requesting task-augmented execution for this request. - * 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. - * - * @category Common Types - */ - export interface RequestParams { - _meta?: RequestMetaObject; - } - - /** @internal */ - export interface Request { - method: string; - // Allow unofficial extensions of `Request.params` without impacting `RequestParams`. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - params?: { [key: string]: any }; - } - - /** - * Common params for any notification. - * - * @category Common Types - */ - export interface NotificationParams { - _meta?: MetaObject; - } - - /** @internal */ - export interface Notification { - method: string; - // Allow unofficial extensions of `Notification.params` without impacting `NotificationParams`. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - params?: { [key: string]: any }; - } - - /** - * Common result fields. - * - * @category Common Types - */ - export interface Result { - _meta?: MetaObject; - [key: string]: unknown; - } - - /** - * @category Errors - */ - export interface Error { - /** - * The error type that occurred. - */ - code: number; - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: string; - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data?: unknown; - } - - /** - * A uniquely identifying ID for a request in JSON-RPC. - * - * @category Common Types - */ - export type RequestId = string | number; - - /** - * A request that expects a response. - * - * @category JSON-RPC - */ - export interface JSONRPCRequest extends Request { - jsonrpc: typeof JSONRPC_VERSION; - id: RequestId; - } - - /** - * A notification which does not expect a response. - * - * @category JSON-RPC - */ - export interface JSONRPCNotification extends Notification { - jsonrpc: typeof JSONRPC_VERSION; - } - - /** - * A successful (non-error) response to a request. - * - * @category JSON-RPC - */ - 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; - export const METHOD_NOT_FOUND = -32601; - 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; - - /** - * 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< - JSONRPCErrorResponse, - "error" - > { - error: Error & { - code: typeof URL_ELICITATION_REQUIRED; - data: { - elicitations: ElicitRequestURLParams[]; - [key: string]: unknown; - }; - }; - } - - /* Empty result */ - /** - * A result that indicates success but carries no data. - * - * @category Common Types - */ - export type EmptyResult = Result; - - /* Cancellation */ - /** - * 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 { - /** - * The ID of the request to cancel. - * - * 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 {@link CancelTaskRequest | tasks/cancel} request instead). - */ - requestId?: RequestId; - - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason?: string; - } - - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - * - * 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` - */ - export interface CancelledNotification extends JSONRPCNotification { - method: "notifications/cancelled"; - params: CancelledNotificationParams; - } - - /* Initialization */ - /** - * Parameters for an `initialize` request. - * - * @example Full client capabilities - * {@includeCode ./examples/InitializeRequestParams/full-client-capabilities.json} - * - * @category `initialize` - */ - export interface InitializeRequestParams extends RequestParams { - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: string; - capabilities: ClientCapabilities; - clientInfo: Implementation; - } - - /** - * 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 { - method: "initialize"; - params: InitializeRequestParams; - } - - /** - * 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` - */ - export interface InitializeResult extends Result { - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: string; - capabilities: ServerCapabilities; - serverInfo: Implementation; - - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - 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 { - method: "notifications/initialized"; - params?: NotificationParams; - } - - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - * - * @category `initialize` - */ - export interface ClientCapabilities { - /** - * Experimental, non-standard capabilities that the client supports. - */ - 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?: { - /** - * Whether the client supports notifications for changes to the roots list. - */ - listChanged?: boolean; - }; - /** - * 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. - * 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. - */ - 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 }; - - /** - * Present if the client supports task-augmented requests. - */ - tasks?: { - /** - * Whether this client supports {@link ListTasksRequest | tasks/list}. - */ - list?: object; - /** - * Whether this client supports {@link CancelTaskRequest | tasks/cancel}. - */ - cancel?: object; - /** - * Specifies which request types can be augmented with tasks. - */ - requests?: { - /** - * Task support for sampling-related requests. - */ - sampling?: { - /** - * Whether the client supports task-augmented `sampling/createMessage` requests. - */ - createMessage?: object; - }; - /** - * Task support for elicitation-related requests. - */ - elicitation?: { - /** - * 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 }; - } - - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - * - * @category `initialize` - */ - export interface ServerCapabilities { - /** - * Experimental, non-standard capabilities that the server supports. - */ - 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?: { - /** - * Whether this server supports notifications for changes to the prompt list. - */ - listChanged?: boolean; - }; - /** - * 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?: { - /** - * Whether this server supports subscribing to resource updates. - */ - subscribe?: boolean; - /** - * Whether this server supports notifications for changes to the resource list. - */ - listChanged?: boolean; - }; - /** - * 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?: { - /** - * Whether this server supports notifications for changes to the tool list. - */ - listChanged?: boolean; - }; - /** - * Present if the server supports task-augmented requests. - */ - tasks?: { - /** - * Whether this server supports {@link ListTasksRequest | tasks/list}. - */ - list?: object; - /** - * Whether this server supports {@link CancelTaskRequest | tasks/cancel}. - */ - cancel?: object; - /** - * Specifies which request types can be augmented with tasks. - */ - requests?: { - /** - * Task support for tool-related requests. - */ - tools?: { - /** - * 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 }; - } - - /** - * An optionally-sized icon that can be displayed in a user interface. - * - * @category Common Types - */ - export interface Icon { - /** - * 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 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 - * executable JavaScript. - * - * @format uri - */ - src: string; - - /** - * Optional MIME type override if the source MIME type is missing or generic. - * For example: `"image/png"`, `"image/jpeg"`, or `"image/svg+xml"`. - */ - mimeType?: string; - - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - 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 - * 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. - */ - theme?: "light" | "dark"; - } - - /** - * Base interface to add `icons` property. - * - * @internal - */ - export interface Icons { - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons?: Icon[]; - } - - /** - * Base interface for metadata with name (identifier) and title (display name) properties. - * - * @internal - */ - export interface BaseMetadata { - /** - * Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present). - */ - name: string; - - /** - * 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 {@link Tool}, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title?: string; - } - - /** - * Describes the MCP implementation. - * - * @category `initialize` - */ - export interface Implementation extends BaseMetadata, Icons { - /** - * The version of this implementation. - */ - version: string; - - /** - * An optional human-readable description of what this implementation does. - * - * This can be used by clients or servers to provide context about their purpose - * and capabilities. For example, a server might describe the types of resources - * or tools it provides, while a client might describe its intended use case. - */ - description?: string; - - /** - * An optional URL of the website for this implementation. - * - * @format uri - */ - websiteUrl?: string; - } - - /* Ping */ - /** - * 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 { - method: "ping"; - 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 {@link ProgressNotification | notifications/progress} notification. - * - * @example Progress message - * {@includeCode ./examples/ProgressNotificationParams/progress-message.json} - * - * @category `notifications/progress` - */ - export interface ProgressNotificationParams extends NotificationParams { - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressToken; - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - * - * @TJS-type number - */ - progress: number; - /** - * Total number of items to process (or total progress required), if known. - * - * @TJS-type number - */ - total?: number; - /** - * An optional message describing the current progress. - */ - message?: string; - } - - /** - * 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 { - method: "notifications/progress"; - params: ProgressNotificationParams; - } - - /* Pagination */ - /** - * Common params for paginated requests. - * - * @example List request with cursor - * {@includeCode ./examples/PaginatedRequestParams/list-with-cursor.json} - * - * @category Common Types - */ - export interface PaginatedRequestParams extends RequestParams { - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor?: Cursor; - } - - /** @internal */ - export interface PaginatedRequest extends JSONRPCRequest { - params?: PaginatedRequestParams; - } - - /** @internal */ - export interface PaginatedResult extends Result { - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor?: Cursor; - } - - /* Resources */ - /** - * 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 { - method: "resources/list"; - } - - /** - * 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` - */ - export interface ListResourcesResult extends PaginatedResult { - 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 { - method: "resources/templates/list"; - } - - /** - * 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` - */ - export interface ListResourceTemplatesResult extends PaginatedResult { - resourceTemplates: ResourceTemplate[]; - } - - /** - * 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 - */ - export interface ResourceRequestParams extends RequestParams { - /** - * The URI of the resource. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: string; - } - - /** - * Parameters for a `resources/read` request. - * - * @category `resources/read` - */ - export interface ReadResourceRequestParams extends ResourceRequestParams { } - - /** - * 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 { - method: "resources/read"; - params: ReadResourceRequestParams; - } - - /** - * 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` - */ - export interface ReadResourceResult extends Result { - 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 { - method: "notifications/resources/list_changed"; - params?: NotificationParams; - } - - /** - * 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 {@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` - */ - export interface SubscribeRequest extends JSONRPCRequest { - method: "resources/subscribe"; - 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. - * - * @category `resources/unsubscribe` - */ - export interface UnsubscribeRequestParams extends ResourceRequestParams { } - - /** - * 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` - */ - export interface UnsubscribeRequest extends JSONRPCRequest { - method: "resources/unsubscribe"; - 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 { - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - * - * @format uri - */ - uri: string; - } - - /** - * 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` - */ - export interface ResourceUpdatedNotification extends JSONRPCNotification { - method: "notifications/resources/updated"; - params: ResourceUpdatedNotificationParams; - } - - /** - * 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 { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - /** - * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known. - * - * This can be used by Hosts to display file sizes and estimate context window usage. - */ - size?: number; - - _meta?: MetaObject; - } - - /** - * A template description for resources available on the server. - * - * @category `resources/templates/list` - */ - export interface ResourceTemplate extends BaseMetadata, Icons { - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - * - * @format uri-template - */ - uriTemplate: string; - - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType?: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - _meta?: MetaObject; - } - - /** - * The contents of a specific resource or sub-resource. - * - * @internal - */ - export interface ResourceContents { - /** - * The URI of this resource. - * - * @format uri - */ - uri: string; - /** - * The MIME type of this resource, if known. - */ - mimeType?: string; - - _meta?: MetaObject; - } - - /** - * @example Text file contents - * {@includeCode ./examples/TextResourceContents/text-file-contents.json} - * - * @category Content - */ - export interface TextResourceContents extends ResourceContents { - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: string; - } - - /** - * @example Image file contents - * {@includeCode ./examples/BlobResourceContents/image-file-contents.json} - * - * @category Content - */ - export interface BlobResourceContents extends ResourceContents { - /** - * A base64-encoded string representing the binary data of the item. - * - * @format byte - */ - blob: string; - } - - /* Prompts */ - /** - * 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 { - method: "prompts/list"; - } - - /** - * 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` - */ - export interface ListPromptsResult extends PaginatedResult { - 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 { - /** - * The name of the prompt or prompt template. - */ - name: string; - /** - * Arguments to use for templating the prompt. - */ - arguments?: { [key: string]: string }; - } - - /** - * 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 { - method: "prompts/get"; - params: GetPromptRequestParams; - } - - /** - * 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` - */ - export interface GetPromptResult extends Result { - /** - * An optional description for the prompt. - */ - description?: string; - 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. - * - * @category `prompts/list` - */ - export interface Prompt extends BaseMetadata, Icons { - /** - * An optional description of what this prompt provides - */ - description?: string; - - /** - * A list of arguments to use for templating the prompt. - */ - arguments?: PromptArgument[]; - - _meta?: MetaObject; - } - - /** - * Describes an argument that a prompt can accept. - * - * @category `prompts/list` - */ - export interface PromptArgument extends BaseMetadata { - /** - * A human-readable description of the argument. - */ - description?: string; - /** - * Whether this argument must be provided. - */ - required?: boolean; - } - - /** - * The sender or recipient of messages and data in a conversation. - * - * @category Common Types - */ - export type Role = "user" | "assistant"; - - /** - * Describes a message returned as part of a prompt. - * - * This is similar to {@link SamplingMessage}, but also supports the embedding of - * resources from the MCP server. - * - * @category `prompts/get` - */ - export interface PromptMessage { - role: Role; - content: ContentBlock; - } - - /** - * 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 {@link ListResourcesRequest | resources/list} requests. - * - * @example File resource link - * {@includeCode ./examples/ResourceLink/file-resource-link.json} - * - * @category Content - */ - export interface ResourceLink extends Resource { - type: "resource_link"; - } - - /** - * The contents of a resource, embedded into a prompt or tool call result. - * - * 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 { - type: "resource"; - resource: TextResourceContents | BlobResourceContents; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - _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 { - method: "notifications/prompts/list_changed"; - params?: NotificationParams; - } - - /* Tools */ - /** - * 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 { - method: "tools/list"; - } - - /** - * 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` - */ - export interface ListToolsResult extends PaginatedResult { - tools: Tool[]; - } - - /** - * 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` - */ - export interface CallToolResult extends Result { - /** - * A list of content objects that represent the unstructured result of the tool call. - */ - content: ContentBlock[]; - - /** - * An optional JSON object that represents the structured result of the tool call. - */ - structuredContent?: { [key: string]: unknown }; - - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - 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 { - /** - * The name of the tool. - */ - name: string; - /** - * Arguments to use for the tool call. - */ - arguments?: { [key: string]: unknown }; - } - - /** - * 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 { - method: "tools/call"; - params: CallToolRequestParams; - } - - /** - * 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 { - method: "notifications/tools/list_changed"; - params?: NotificationParams; - } - - /** - * Additional properties describing a {@link Tool} to clients. - * - * 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` - * received from untrusted servers. - * - * @category `tools/list` - */ - export interface ToolAnnotations { - /** - * A human-readable title for the tool. - */ - title?: string; - - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint?: boolean; - - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint?: boolean; - - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint?: boolean; - - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint?: boolean; - } - - /** - * Execution-related properties for a tool. - * - * @category `tools/list` - */ - export interface ToolExecution { - /** - * Indicates whether this tool supports task-augmented execution. - * 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 - * - * Default: `"forbidden"` - */ - taskSupport?: "forbidden" | "optional" | "required"; - } - - /** - * 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 { - /** - * A human-readable description of the tool. - * - * This can be used by clients to improve the LLM's understanding of available tools. It can be thought of like a "hint" to the model. - */ - description?: string; - - /** - * A JSON Schema object defining the expected parameters for the tool. - */ - inputSchema: { - $schema?: string; - type: "object"; - properties?: { [key: string]: object }; - required?: string[]; - }; - - /** - * Execution-related properties for this tool. - */ - execution?: ToolExecution; - - /** - * An optional JSON Schema object defining the structure of the tool's output returned in - * 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. - */ - outputSchema?: { - $schema?: string; - type: "object"; - properties?: { [key: string]: object }; - required?: string[]; - }; - - /** - * Optional additional tool information. - * - * Display name precedence order is: `title`, `annotations.title`, then `name`. - */ - annotations?: ToolAnnotations; - - _meta?: MetaObject; - } - - /* Tasks */ - - /** - * The status of a task. - * - * @category `tasks` - */ - export type TaskStatus = - | "working" // The request is currently being processed - | "input_required" // The task is waiting for input (e.g., elicitation or sampling) - | "completed" // The request completed successfully and results are available - | "failed" // The associated request did not complete successfully. For tool calls specifically, this includes cases where the tool call result has `isError` set to true. - | "cancelled"; // The request was cancelled before completion - - /** - * Metadata for augmenting a request with task execution. - * Include this in the `task` field of the request parameters. - * - * @category `tasks` - */ - export interface TaskMetadata { - /** - * Requested duration in milliseconds to retain task from creation. - */ - ttl?: number; - } - - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @category `tasks` - */ - export interface RelatedTaskMetadata { - /** - * The task identifier this message is associated with. - */ - taskId: string; - } - - /** - * Data associated with a task. - * - * @category `tasks` - */ - export interface Task { - /** - * The task identifier. - */ - taskId: string; - - /** - * Current task state. - */ - status: TaskStatus; - - /** - * Optional human-readable message describing the current task state. - * This can provide context for any status, including: - * - Reasons for "cancelled" status - * - Summaries for "completed" status - * - Diagnostic information for "failed" status (e.g., error details, what went wrong) - */ - statusMessage?: string; - - /** - * ISO 8601 timestamp when the task was created. - */ - createdAt: string; - - /** - * ISO 8601 timestamp when the task was last updated. - */ - lastUpdatedAt: string; - - /** - * Actual retention duration from creation in milliseconds, null for unlimited. - */ - ttl: number | null; - - /** - * Suggested polling interval in milliseconds. - */ - pollInterval?: number; - } - - /** - * The result returned for a task-augmented request. - * - * @category `tasks` - */ - export interface CreateTaskResult extends Result { - 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. - * - * @category `tasks/get` - */ - export interface GetTaskRequest extends JSONRPCRequest { - method: "tasks/get"; - params: { - /** - * The task identifier to query. - */ - taskId: string; - }; - } - - /** - * 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. - * - * @category `tasks/result` - */ - export interface GetTaskPayloadRequest extends JSONRPCRequest { - method: "tasks/result"; - params: { - /** - * The task identifier to retrieve results for. - */ - taskId: string; - }; - } - - /** - * The result returned for a {@link GetTaskPayloadRequest | tasks/result} request. - * The structure matches the result type of the original request. - * For example, a {@link CallToolRequest | tools/call} task would return the {@link CallToolResult} structure. - * - * @category `tasks/result` - */ - export interface GetTaskPayloadResult extends Result { - [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. - * - * @category `tasks/cancel` - */ - export interface CancelTaskRequest extends JSONRPCRequest { - method: "tasks/cancel"; - params: { - /** - * The task identifier to cancel. - */ - taskId: string; - }; - } - - /** - * 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. - * - * @category `tasks/list` - */ - export interface ListTasksRequest extends PaginatedRequest { - method: "tasks/list"; - } - - /** - * The result returned for a {@link ListTasksRequest | tasks/list} request. - * - * @category `tasks/list` - */ - export interface ListTasksResult extends PaginatedResult { - 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. - * - * @category `notifications/tasks/status` - */ - export type TaskStatusNotificationParams = NotificationParams & Task; - - /** - * An optional notification from the receiver to the requestor, informing them that a task's status has changed. Receivers are not required to send these notifications. - * - * @category `notifications/tasks/status` - */ - export interface TaskStatusNotification extends JSONRPCNotification { - method: "notifications/tasks/status"; - params: TaskStatusNotificationParams; - } - - /* Logging */ - - /** - * 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 {@link LoggingMessageNotification | notifications/message}. - */ - level: LoggingLevel; - } - - /** - * 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 { - method: "logging/setLevel"; - 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 { - /** - * The severity of this log message. - */ - level: LoggingLevel; - /** - * An optional name of the logger issuing this message. - */ - logger?: string; - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: unknown; - } - - /** - * 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` - */ - export interface LoggingMessageNotification extends JSONRPCNotification { - method: "notifications/message"; - params: LoggingMessageNotificationParams; - } - - /** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 - * - * @category Common Types - */ - export type LoggingLevel = - | "debug" - | "info" - | "notice" - | "warning" - | "error" - | "critical" - | "alert" - | "emergency"; - - /* Sampling */ - /** - * 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 { - messages: SamplingMessage[]; - /** - * The server's preferences for which model to select. The client MAY ignore these preferences. - */ - modelPreferences?: ModelPreferences; - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt?: string; - /** - * 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 {@link ClientCapabilities.sampling.context}. These values may be removed in future spec releases. - */ - includeContext?: "none" | "thisServer" | "allServers"; - /** - * @TJS-type number - */ - temperature?: number; - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: number; - stopSequences?: string[]; - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata?: object; - /** - * Tools that the model may use during generation. - * 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 {@link ClientCapabilities.sampling.tools} is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice?: ToolChoice; - } - - /** - * Controls tool selection behavior for sampling requests. - * - * @category `sampling/createMessage` - */ - 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 - */ - mode?: "auto" | "required" | "none"; - } - - /** - * 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 { - method: "sampling/createMessage"; - params: CreateMessageRequestParams; - } - - /** - * 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 { - /** - * The name of the model that generated the message. - */ - model: string; - - /** - * 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 - * - * 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[]; - _meta?: MetaObject; - } - - /** - * @category `sampling/createMessage` - */ - export type SamplingMessageContentBlock = - | TextContent - | ImageContent - | AudioContent - | ToolUseContent - | ToolResultContent; - - /** - * Optional annotations for the client. The client can use annotations to inform how objects are used or displayed - * - * @category Common Types - */ - export interface Annotations { - /** - * Describes who the intended audience of this object or data is. - * - * It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`). - */ - audience?: Role[]; - - /** - * Describes how important this data is for operating the server. - * - * A value of 1 means "most important," and indicates that the data is - * effectively required, while 0 means "least important," and indicates that - * the data is entirely optional. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - priority?: number; - - /** - * The moment the resource was last modified, as an ISO 8601 formatted string. - * - * Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z"). - * - * Examples: last activity timestamp in an open file, timestamp when the resource - * was attached, etc. - */ - lastModified?: string; - } - - /** - * @category Content - */ - export type ContentBlock = - | TextContent - | ImageContent - | AudioContent - | ResourceLink - | EmbeddedResource; - - /** - * Text provided to or from an LLM. - * - * @example Text content - * {@includeCode ./examples/TextContent/text-content.json} - * - * @category Content - */ - export interface TextContent { - type: "text"; - - /** - * The text content of the message. - */ - text: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - _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 { - type: "image"; - - /** - * The base64-encoded image data. - * - * @format byte - */ - data: string; - - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - _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 { - type: "audio"; - - /** - * The base64-encoded audio data. - * - * @format byte - */ - data: string; - - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: string; - - /** - * Optional annotations for the client. - */ - annotations?: Annotations; - - _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 { - type: "tool_use"; - - /** - * A unique identifier for this tool use. - * - * This ID is used to match tool results to their corresponding tool uses. - */ - id: string; - - /** - * The name of the tool to call. - */ - name: string; - - /** - * The arguments to pass to the tool, conforming to the tool's input schema. - */ - input: { [key: string]: unknown }; - - /** - * Optional metadata about the tool use. Clients SHOULD preserve this field when - * including tool uses in subsequent sampling requests to enable caching optimizations. - */ - _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 { - type: "tool_result"; - - /** - * The ID of the tool use this result corresponds to. - * - * 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 {@link CallToolResult.content} and can include text, images, - * audio, resource links, and embedded resources. - */ - content: ContentBlock[]; - - /** - * An optional structured result object. - * - * If the tool defined an {@link Tool.outputSchema}, this SHOULD conform to that schema. - */ - structuredContent?: { [key: string]: unknown }; - - /** - * Whether the tool use resulted in an error. - * - * If true, the content typically describes the error that occurred. - * Default: false - */ - isError?: boolean; - - /** - * Optional metadata about the tool result. Clients SHOULD preserve this field when - * including tool results in subsequent sampling requests to enable caching optimizations. - */ - _meta?: MetaObject; - } - - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * Because LLMs can vary along multiple dimensions, choosing the "best" model is - * rarely straightforward. Different models excel in different areas-some are - * faster but less capable, others are more capable but more expensive, and so - * on. This interface allows servers to express their priorities across multiple - * dimensions to help clients make an appropriate selection for their use case. - * - * These preferences are always advisory. The client MAY ignore them. It is also - * 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 { - /** - * Optional hints to use for model selection. - * - * If multiple hints are specified, the client MUST evaluate them in order - * (such that the first match is taken). - * - * The client SHOULD prioritize these hints over the numeric priorities, but - * MAY still use the priorities to select from ambiguous matches. - */ - hints?: ModelHint[]; - - /** - * How much to prioritize cost when selecting a model. A value of 0 means cost - * is not important, while a value of 1 means cost is the most important - * factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - costPriority?: number; - - /** - * How much to prioritize sampling speed (latency) when selecting a model. A - * value of 0 means speed is not important, while a value of 1 means speed is - * the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - speedPriority?: number; - - /** - * How much to prioritize intelligence and capabilities when selecting a - * model. A value of 0 means intelligence is not important, while a value of 1 - * means intelligence is the most important factor. - * - * @TJS-type number - * @minimum 0 - * @maximum 1 - */ - intelligencePriority?: number; - } - - /** - * Hints to use for model selection. - * - * Keys not declared here are currently left unspecified by the spec and are up - * to the client to interpret. - * - * @category `sampling/createMessage` - */ - export interface ModelHint { - /** - * A hint for a model name. - * - * The client SHOULD treat this as a substring of a model name; for example: - * - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022` - * - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc. - * - `claude` should match any Claude model - * - * The client MAY also map the string to a different provider's model name or a different model family, as long as it fills a similar niche; for example: - * - `gemini-1.5-flash` could match `claude-3-haiku-20240307` - */ - name?: string; - } - - /* Autocomplete */ - /** - * 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; - /** - * The argument's information - */ - argument: { - /** - * The name of the argument - */ - name: string; - /** - * The value of the argument to use for completion matching. - */ - value: string; - }; - - /** - * Additional, optional context for completions - */ - context?: { - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments?: { [key: string]: string }; - }; - } - - /** - * 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 { - method: "completion/complete"; - params: CompleteRequestParams; - } - - /** - * 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: { - /** - * An array of completion values. Must not exceed 100 items. - */ - values: string[]; - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total?: number; - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore?: boolean; - }; - } - - /** - * 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. - * - * @category `completion/complete` - */ - export interface ResourceTemplateReference { - type: "ref/resource"; - /** - * The URI or URI template of the resource. - * - * @format uri-template - */ - uri: string; - } - - /** - * Identifies a prompt. - * - * @category `completion/complete` - */ - export interface PromptReference extends BaseMetadata { - type: "ref/prompt"; - } - - /* Roots */ - /** - * Sent from the server to request a list of root URIs from the client. Roots allow - * servers to ask for specific directories or files to operate on. A common example - * for roots is providing a set of repositories or directories a server should operate - * on. - * - * 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 { - method: "roots/list"; - params?: RequestParams; - } - - /** - * 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. - * This restriction may be relaxed in future versions of the protocol to allow - * other URI schemes. - * - * @format uri - */ - uri: string; - /** - * An optional name for the root. This can be used to provide a human-readable - * identifier for the root, which may be useful for display purposes or for - * referencing the root in other parts of the application. - */ - name?: string; - - _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 {@link ListRootsRequest}. - * - * @example Roots list changed - * {@includeCode ./examples/RootsListChangedNotification/roots-list-changed.json} - * - * @category `notifications/roots/list_changed` - */ - export interface RootsListChangedNotification extends JSONRPCNotification { - method: "notifications/roots/list_changed"; - params?: NotificationParams; - } - - /** - * 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 { - /** - * The elicitation mode. - */ - mode?: "form"; - - /** - * The message to present to the user describing what information is being requested. - */ - message: string; - - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: { - $schema?: string; - type: "object"; - properties: { - [key: string]: PrimitiveSchemaDefinition; - }; - required?: string[]; - }; - } - - /** - * 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 { - /** - * The elicitation mode. - */ - mode: "url"; - - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: string; - - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: string; - - /** - * The URL that the user should navigate to. - * - * @format uri - */ - url: string; - } - - /** - * The parameters for a request to elicit additional information from the user via the client. - * - * @category `elicitation/create` - */ - export type ElicitRequestParams = - | ElicitRequestFormParams - | ElicitRequestURLParams; - - /** - * 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 { - method: "elicitation/create"; - params: ElicitRequestParams; - } - - /** - * Restricted schema definitions that only allow primitive types - * without nested objects or arrays. - * - * @category `elicitation/create` - */ - export type PrimitiveSchemaDefinition = - | StringSchema - | NumberSchema - | BooleanSchema - | EnumSchema; - - /** - * @example Email input schema - * {@includeCode ./examples/StringSchema/email-input-schema.json} - * - * @category `elicitation/create` - */ - export interface StringSchema { - type: "string"; - title?: string; - description?: string; - minLength?: number; - maxLength?: number; - format?: "email" | "uri" | "date" | "date-time"; - default?: string; - } - - /** - * @example Number input schema - * {@includeCode ./examples/NumberSchema/number-input-schema.json} - * - * @category `elicitation/create` - */ - export interface NumberSchema { - type: "number" | "integer"; - title?: string; - description?: string; - minimum?: number; - maximum?: number; - default?: number; - } - - /** - * @example Boolean input schema - * {@includeCode ./examples/BooleanSchema/boolean-input-schema.json} - * - * @category `elicitation/create` - */ - export interface BooleanSchema { - type: "boolean"; - title?: string; - description?: string; - default?: boolean; - } - - /** - * 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 { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum values to choose from. - */ - enum: string[]; - /** - * Optional default value. - */ - default?: string; - } - - /** - * 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 { - type: "string"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Array of enum options with values and display labels. - */ - oneOf: Array<{ - /** - * The enum value. - */ - const: string; - /** - * Display label for this option. - */ - title: string; - }>; - /** - * Optional default value. - */ - default?: string; - } - - /** - * @category `elicitation/create` - */ - // Combined single selection enumeration - export type SingleSelectEnumSchema = - | UntitledSingleSelectEnumSchema - | TitledSingleSelectEnumSchema; - - /** - * 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 { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for the array items. - */ - items: { - type: "string"; - /** - * Array of enum values to choose from. - */ - enum: string[]; - }; - /** - * Optional default value. - */ - default?: string[]; - } - - /** - * 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 { - type: "array"; - /** - * Optional title for the enum field. - */ - title?: string; - /** - * Optional description for the enum field. - */ - description?: string; - /** - * Minimum number of items to select. - */ - minItems?: number; - /** - * Maximum number of items to select. - */ - maxItems?: number; - /** - * Schema for array items with enum options and display labels. - */ - items: { - /** - * Array of enum options with values and display labels. - */ - anyOf: Array<{ - /** - * The constant enum value. - */ - const: string; - /** - * Display title for this option. - */ - title: string; - }>; - }; - /** - * Optional default value. - */ - default?: string[]; - } - - /** - * @category `elicitation/create` - */ - // Combined multiple selection enumeration - export type MultiSelectEnumSchema = - | UntitledMultiSelectEnumSchema - | TitledMultiSelectEnumSchema; - - /** - * Use {@link TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - * - * @category `elicitation/create` - */ - export interface LegacyTitledEnumSchema { - type: "string"; - title?: string; - description?: string; - enum: string[]; - /** - * (Legacy) Display names for enum values. - * Non-standard according to JSON schema 2020-12. - */ - enumNames?: string[]; - default?: string; - } - - /** - * @category `elicitation/create` - */ - // Union type for all enum schemas - export type EnumSchema = - | SingleSelectEnumSchema - | MultiSelectEnumSchema - | LegacyTitledEnumSchema; - - /** - * 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 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"`. - * 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 { - method: "notifications/elicitation/complete"; - params: { - /** - * The ID of the elicitation that completed. - */ - elicitationId: string; - }; - } - - /* Client messages */ - /** @internal */ - export type ClientRequest = - | PingRequest - | InitializeRequest - | CompleteRequest - | SetLevelRequest - | GetPromptRequest - | ListPromptsRequest - | ListResourcesRequest - | ListResourceTemplatesRequest - | ReadResourceRequest - | SubscribeRequest - | UnsubscribeRequest - | CallToolRequest - | ListToolsRequest - | GetTaskRequest - | GetTaskPayloadRequest - | ListTasksRequest - | CancelTaskRequest; - - /** @internal */ - export type ClientNotification = - | CancelledNotification - | ProgressNotification - | InitializedNotification - | RootsListChangedNotification - | TaskStatusNotification; - - /** @internal */ - export type ClientResult = - | EmptyResult - | CreateMessageResult - | ListRootsResult - | ElicitResult - | GetTaskResult - | GetTaskPayloadResult - | ListTasksResult - | CancelTaskResult; - - /* Server messages */ - /** @internal */ - export type ServerRequest = - | PingRequest - | CreateMessageRequest - | ListRootsRequest - | ElicitRequest - | GetTaskRequest - | GetTaskPayloadRequest - | ListTasksRequest - | CancelTaskRequest; - - /** @internal */ - export type ServerNotification = - | CancelledNotification - | ProgressNotification - | LoggingMessageNotification - | ResourceUpdatedNotification - | ResourceListChangedNotification - | ToolListChangedNotification - | PromptListChangedNotification - | ElicitationCompleteNotification - | TaskStatusNotification; - - /** @internal */ - export type ServerResult = - | EmptyResult - | InitializeResult - | CompleteResult - | GetPromptResult - | ListPromptsResult - | ListResourceTemplatesResult - | ListResourcesResult - | ReadResourceResult - | CallToolResult - | CreateTaskResult - | ListToolsResult - | GetTaskResult - | GetTaskPayloadResult - | ListTasksResult - | CancelTaskResult; -} +export { MCP } from '../../../../platform/mcp/common/modelContextProtocol.js'; diff --git a/src/vs/workbench/contrib/mcp/common/modelContextProtocolApps.ts b/src/vs/workbench/contrib/mcp/common/modelContextProtocolApps.ts index 4569e8f25ac8d..e45a5c065592c 100644 --- a/src/vs/workbench/contrib/mcp/common/modelContextProtocolApps.ts +++ b/src/vs/workbench/contrib/mcp/common/modelContextProtocolApps.ts @@ -3,735 +3,4 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { MCP } from './modelContextProtocol.js'; - -type CallToolResult = MCP.CallToolResult; -type ContentBlock = MCP.ContentBlock; -type Implementation = MCP.Implementation; -type RequestId = MCP.RequestId; -type Tool = MCP.Tool; - -export namespace McpApps { - export type AppRequest = - | MCP.CallToolRequest - | MCP.ReadResourceRequest - | MCP.PingRequest - | (McpUiOpenLinkRequest & MCP.JSONRPCRequest) - | (McpUiUpdateModelContextRequest & MCP.JSONRPCRequest) - | (McpUiMessageRequest & MCP.JSONRPCRequest) - | (McpUiRequestDisplayModeRequest & MCP.JSONRPCRequest) - | (McpApps.McpUiInitializeRequest & MCP.JSONRPCRequest); - - export type AppNotification = - | McpUiInitializedNotification - | McpUiSizeChangedNotification - | MCP.LoggingMessageNotification - | CustomSandboxWheelNotification; - - export type AppMessage = AppRequest | AppNotification; - - export type HostResult = - | MCP.CallToolResult - | MCP.ReadResourceResult - | MCP.EmptyResult - | McpApps.McpUiInitializeResult - | McpUiMessageResult - | McpUiOpenLinkResult - | McpUiRequestDisplayModeResult; - - export type HostNotification = - | McpUiHostContextChangedNotification - | McpUiResourceTeardownRequest - | McpUiToolInputNotification - | McpUiToolInputPartialNotification - | McpUiToolResultNotification - | McpUiToolCancelledNotification - | McpUiSizeChangedNotification; - - export type HostMessage = HostResult | HostNotification; - - - /** Custom notification used for bubbling up sandbox wheel events. */ - export interface CustomSandboxWheelNotification { - method: 'ui/notifications/sandbox-wheel'; - params: { - deltaMode: number; - deltaX: number; - deltaY: number; - deltaZ: number; - }; - } -} - -/* eslint-disable local/code-no-unexternalized-strings */ - - -/** - * Schema updated from the Model Context Protocol Apps repository at - * https://github.com/modelcontextprotocol/ext-apps/blob/main/src/spec.types.ts - * - * ⚠️ Do not edit within `namespace` manually except to update schema versions ⚠️ - */ -export namespace McpApps { - /** - * Current protocol version supported by this SDK. - * - * The SDK automatically handles version negotiation during initialization. - * Apps and hosts don't need to manage protocol versions manually. - */ - export const LATEST_PROTOCOL_VERSION = "2026-01-26"; - - /** - * @description Color theme preference for the host environment. - */ - export type McpUiTheme = "light" | "dark"; - - /** - * @description Display mode for UI presentation. - */ - export type McpUiDisplayMode = "inline" | "fullscreen" | "pip"; - - /** - * @description CSS variable keys available to MCP apps for theming. - */ - export type McpUiStyleVariableKey = - // Background colors - | "--color-background-primary" - | "--color-background-secondary" - | "--color-background-tertiary" - | "--color-background-inverse" - | "--color-background-ghost" - | "--color-background-info" - | "--color-background-danger" - | "--color-background-success" - | "--color-background-warning" - | "--color-background-disabled" - // Text colors - | "--color-text-primary" - | "--color-text-secondary" - | "--color-text-tertiary" - | "--color-text-inverse" - | "--color-text-ghost" - | "--color-text-info" - | "--color-text-danger" - | "--color-text-success" - | "--color-text-warning" - | "--color-text-disabled" - | "--color-text-ghost" - // Border colors - | "--color-border-primary" - | "--color-border-secondary" - | "--color-border-tertiary" - | "--color-border-inverse" - | "--color-border-ghost" - | "--color-border-info" - | "--color-border-danger" - | "--color-border-success" - | "--color-border-warning" - | "--color-border-disabled" - // Ring colors - | "--color-ring-primary" - | "--color-ring-secondary" - | "--color-ring-inverse" - | "--color-ring-info" - | "--color-ring-danger" - | "--color-ring-success" - | "--color-ring-warning" - // Typography - Family - | "--font-sans" - | "--font-mono" - // Typography - Weight - | "--font-weight-normal" - | "--font-weight-medium" - | "--font-weight-semibold" - | "--font-weight-bold" - // Typography - Text Size - | "--font-text-xs-size" - | "--font-text-sm-size" - | "--font-text-md-size" - | "--font-text-lg-size" - // Typography - Heading Size - | "--font-heading-xs-size" - | "--font-heading-sm-size" - | "--font-heading-md-size" - | "--font-heading-lg-size" - | "--font-heading-xl-size" - | "--font-heading-2xl-size" - | "--font-heading-3xl-size" - // Typography - Text Line Height - | "--font-text-xs-line-height" - | "--font-text-sm-line-height" - | "--font-text-md-line-height" - | "--font-text-lg-line-height" - // Typography - Heading Line Height - | "--font-heading-xs-line-height" - | "--font-heading-sm-line-height" - | "--font-heading-md-line-height" - | "--font-heading-lg-line-height" - | "--font-heading-xl-line-height" - | "--font-heading-2xl-line-height" - | "--font-heading-3xl-line-height" - // Border radius - | "--border-radius-xs" - | "--border-radius-sm" - | "--border-radius-md" - | "--border-radius-lg" - | "--border-radius-xl" - | "--border-radius-full" - // Border width - | "--border-width-regular" - // Shadows - | "--shadow-hairline" - | "--shadow-sm" - | "--shadow-md" - | "--shadow-lg"; - - /** - * @description Style variables for theming MCP apps. - * - * Individual style keys are optional - hosts may provide any subset of these values. - * Values are strings containing CSS values (colors, sizes, font stacks, etc.). - * - * Note: This type uses `Record` rather than `Partial>` - * for compatibility with Zod schema generation. Both are functionally equivalent for validation. - */ - export type McpUiStyles = Record; - - /** - * @description Request to open an external URL in the host's default browser. - * @see {@link app.App.sendOpenLink} for the method that sends this request - */ - export interface McpUiOpenLinkRequest { - method: "ui/open-link"; - params: { - /** @description URL to open in the host's browser */ - url: string; - }; - } - - /** - * @description Result from opening a URL. - * @see {@link McpUiOpenLinkRequest} - */ - export interface McpUiOpenLinkResult { - /** @description True if the host failed to open the URL (e.g., due to security policy). */ - isError?: boolean; - /** - * Index signature required for MCP SDK `Protocol` class compatibility. - * Note: The schema intentionally omits this to enforce strict validation. - */ - [key: string]: unknown; - } - - /** - * @description Request to send a message to the host's chat interface. - * @see {@link app.App.sendMessage} for the method that sends this request - */ - export interface McpUiMessageRequest { - method: "ui/message"; - params: { - /** @description Message role, currently only "user" is supported. */ - role: "user"; - /** @description Message content blocks (text, image, etc.). */ - content: ContentBlock[]; - }; - } - - /** - * @description Result from sending a message. - * @see {@link McpUiMessageRequest} - */ - export interface McpUiMessageResult { - /** @description True if the host rejected or failed to deliver the message. */ - isError?: boolean; - /** - * Index signature required for MCP SDK `Protocol` class compatibility. - * Note: The schema intentionally omits this to enforce strict validation. - */ - [key: string]: unknown; - } - - /** - * @description Notification that the sandbox proxy iframe is ready to receive content. - * @internal - * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#sandbox-proxy - */ - export interface McpUiSandboxProxyReadyNotification { - method: "ui/notifications/sandbox-proxy-ready"; - params: {}; - } - - /** - * @description Notification containing HTML resource for the sandbox proxy to load. - * @internal - * @see https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#sandbox-proxy - */ - export interface McpUiSandboxResourceReadyNotification { - method: "ui/notifications/sandbox-resource-ready"; - params: { - /** @description HTML content to load into the inner iframe. */ - html: string; - /** @description Optional override for the inner iframe's sandbox attribute. */ - sandbox?: string; - /** @description CSP configuration from resource metadata. */ - csp?: McpUiResourceCsp; - /** @description Sandbox permissions from resource metadata. */ - permissions?: McpUiResourcePermissions; - }; - } - - /** - * @description Notification of UI size changes (bidirectional: Guest <-> Host). - * @see {@link app.App.sendSizeChanged} for the method to send this from Guest UI - */ - export interface McpUiSizeChangedNotification { - method: "ui/notifications/size-changed"; - params: { - /** @description New width in pixels. */ - width?: number; - /** @description New height in pixels. */ - height?: number; - }; - } - - /** - * @description Notification containing complete tool arguments (Host -> Guest UI). - */ - export interface McpUiToolInputNotification { - method: "ui/notifications/tool-input"; - params: { - /** @description Complete tool call arguments as key-value pairs. */ - arguments?: Record; - }; - } - - /** - * @description Notification containing partial/streaming tool arguments (Host -> Guest UI). - */ - export interface McpUiToolInputPartialNotification { - method: "ui/notifications/tool-input-partial"; - params: { - /** @description Partial tool call arguments (incomplete, may change). */ - arguments?: Record; - }; - } - - /** - * @description Notification containing tool execution result (Host -> Guest UI). - */ - export interface McpUiToolResultNotification { - method: "ui/notifications/tool-result"; - /** @description Standard MCP tool execution result. */ - params: CallToolResult; - } - - /** - * @description Notification that tool execution was cancelled (Host -> Guest UI). - * Host MUST send this if tool execution was cancelled for any reason (user action, - * sampling error, classifier intervention, etc.). - */ - export interface McpUiToolCancelledNotification { - method: "ui/notifications/tool-cancelled"; - params: { - /** @description Optional reason for the cancellation (e.g., "user action", "timeout"). */ - reason?: string; - }; - } - - /** - * @description CSS blocks that can be injected by apps. - */ - export interface McpUiHostCss { - /** @description CSS for font loading (@font-face rules or @import statements). Apps must apply using applyHostFonts(). */ - fonts?: string; - } - - /** - * @description Style configuration for theming MCP apps. - */ - export interface McpUiHostStyles { - /** @description CSS variables for theming the app. */ - variables?: McpUiStyles; - /** @description CSS blocks that apps can inject. */ - css?: McpUiHostCss; - } - - /** - * @description Rich context about the host environment provided to Guest UIs. - */ - export interface McpUiHostContext { - /** @description Allow additional properties for forward compatibility. */ - [key: string]: unknown; - /** @description Metadata of the tool call that instantiated this App. */ - toolInfo?: { - /** @description JSON-RPC id of the tools/call request. */ - id?: RequestId; - /** @description Tool definition including name, inputSchema, etc. */ - tool: Tool; - }; - /** @description Current color theme preference. */ - theme?: McpUiTheme; - /** @description Style configuration for theming the app. */ - styles?: McpUiHostStyles; - /** @description How the UI is currently displayed. */ - displayMode?: McpUiDisplayMode; - /** @description Display modes the host supports. */ - availableDisplayModes?: string[]; - /** - * @description Container dimensions. Represents the dimensions of the iframe or other - * container holding the app. Specify either width or maxWidth, and either height or maxHeight. - */ - containerDimensions?: ( - | { - /** @description Fixed container height in pixels. */ - height: number; - } - | { - /** @description Maximum container height in pixels. */ - maxHeight?: number | undefined; - } - ) & - ( - | { - /** @description Fixed container width in pixels. */ - width: number; - } - | { - /** @description Maximum container width in pixels. */ - maxWidth?: number | undefined; - } - ); - /** @description User's language and region preference in BCP 47 format. */ - locale?: string; - /** @description User's timezone in IANA format. */ - timeZone?: string; - /** @description Host application identifier. */ - userAgent?: string; - /** @description Platform type for responsive design decisions. */ - platform?: "web" | "desktop" | "mobile"; - /** @description Device input capabilities. */ - deviceCapabilities?: { - /** @description Whether the device supports touch input. */ - touch?: boolean; - /** @description Whether the device supports hover interactions. */ - hover?: boolean; - }; - /** @description Mobile safe area boundaries in pixels. */ - safeAreaInsets?: { - /** @description Top safe area inset in pixels. */ - top: number; - /** @description Right safe area inset in pixels. */ - right: number; - /** @description Bottom safe area inset in pixels. */ - bottom: number; - /** @description Left safe area inset in pixels. */ - left: number; - }; - } - - /** - * @description Notification that host context has changed (Host -> Guest UI). - * @see {@link McpUiHostContext} for the full context structure - */ - export interface McpUiHostContextChangedNotification { - method: "ui/notifications/host-context-changed"; - /** @description Partial context update containing only changed fields. */ - params: McpUiHostContext; - } - - /** - * @description Request to update the agent's context without requiring a follow-up action (Guest UI -> Host). - * - * Unlike `notifications/message` which is for debugging/logging, this request is intended - * to update the Host's model context. Each request overwrites the previous context sent by the Guest UI. - * Unlike messages, context updates do not trigger follow-ups. - * - * The host will typically defer sending the context to the model until the next user message - * (including `ui/message`), and will only send the last update received. - * - * @see {@link app.App.updateModelContext} for the method that sends this request - */ - export interface McpUiUpdateModelContextRequest { - method: "ui/update-model-context"; - params: { - /** @description Context content blocks (text, image, etc.). */ - content?: ContentBlock[]; - /** @description Structured content for machine-readable context data. */ - structuredContent?: Record; - }; - } - - /** - * @description Request for graceful shutdown of the Guest UI (Host -> Guest UI). - * @see {@link app-bridge.AppBridge.teardownResource} for the host method that sends this - */ - export interface McpUiResourceTeardownRequest { - method: "ui/resource-teardown"; - params: {}; - } - - /** - * @description Result from graceful shutdown request. - * @see {@link McpUiResourceTeardownRequest} - */ - export interface McpUiResourceTeardownResult { - /** - * Index signature required for MCP SDK `Protocol` class compatibility. - */ - [key: string]: unknown; - } - - export interface McpUiSupportedContentBlockModalities { - /** @description Host supports text content blocks. */ - text?: {}; - /** @description Host supports image content blocks. */ - image?: {}; - /** @description Host supports audio content blocks. */ - audio?: {}; - /** @description Host supports resource content blocks. */ - resource?: {}; - /** @description Host supports resource link content blocks. */ - resourceLink?: {}; - /** @description Host supports structured content. */ - structuredContent?: {}; - } - - /** - * @description Capabilities supported by the host application. - * @see {@link McpUiInitializeResult} for the initialization result that includes these capabilities - */ - export interface McpUiHostCapabilities { - /** @description Experimental features (structure TBD). */ - experimental?: {}; - /** @description Host supports opening external URLs. */ - openLinks?: {}; - /** @description Host can proxy tool calls to the MCP server. */ - serverTools?: { - /** @description Host supports tools/list_changed notifications. */ - listChanged?: boolean; - }; - /** @description Host can proxy resource reads to the MCP server. */ - serverResources?: { - /** @description Host supports resources/list_changed notifications. */ - listChanged?: boolean; - }; - /** @description Host accepts log messages. */ - logging?: {}; - /** @description Sandbox configuration applied by the host. */ - sandbox?: { - /** @description Permissions granted by the host (camera, microphone, geolocation). */ - permissions?: McpUiResourcePermissions; - /** @description CSP domains approved by the host. */ - csp?: McpUiResourceCsp; - }; - /** @description Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns. */ - updateModelContext?: McpUiSupportedContentBlockModalities; - /** @description Host supports receiving content messages (ui/message) from the View. */ - message?: McpUiSupportedContentBlockModalities; - } - - /** - * @description Capabilities provided by the View (App). - * @see {@link McpUiInitializeRequest} for the initialization request that includes these capabilities - */ - export interface McpUiAppCapabilities { - /** @description Experimental features (structure TBD). */ - experimental?: {}; - /** @description App exposes MCP-style tools that the host can call. */ - tools?: { - /** @description App supports tools/list_changed notifications. */ - listChanged?: boolean; - }; - /** - * @description Display modes the app supports. See Display Modes section of the spec for details. - * @example ["inline", "fullscreen"] - */ - availableDisplayModes?: McpUiDisplayMode[]; - } - - /** - * @description Initialization request sent from Guest UI to Host. - * @see {@link app.App.connect} for the method that sends this request - */ - export interface McpUiInitializeRequest { - method: "ui/initialize"; - params: { - /** @description App identification (name and version). */ - appInfo: Implementation; - /** @description Features and capabilities this app provides. */ - appCapabilities: McpUiAppCapabilities; - /** @description Protocol version this app supports. */ - protocolVersion: string; - }; - } - - /** - * @description Initialization result returned from Host to Guest UI. - * @see {@link McpUiInitializeRequest} - */ - export interface McpUiInitializeResult { - /** @description Negotiated protocol version string (e.g., "2025-11-21"). */ - protocolVersion: string; - /** @description Host application identification and version. */ - hostInfo: Implementation; - /** @description Features and capabilities provided by the host. */ - hostCapabilities: McpUiHostCapabilities; - /** @description Rich context about the host environment. */ - hostContext: McpUiHostContext; - /** - * Index signature required for MCP SDK `Protocol` class compatibility. - * Note: The schema intentionally omits this to enforce strict validation. - */ - [key: string]: unknown; - } - - /** - * @description Notification that Guest UI has completed initialization (Guest UI -> Host). - * @see {@link app.App.connect} for the method that sends this notification - */ - export interface McpUiInitializedNotification { - method: "ui/notifications/initialized"; - params?: {}; - } - - /** - * @description Content Security Policy configuration for UI resources. - */ - export interface McpUiResourceCsp { - /** @description Origins for network requests (fetch/XHR/WebSocket). */ - connectDomains?: string[]; - /** @description Origins for static resources (scripts, images, styles, fonts). */ - resourceDomains?: string[]; - /** @description Origins for nested iframes (frame-src directive). */ - frameDomains?: string[]; - /** @description Allowed base URIs for the document (base-uri directive). */ - baseUriDomains?: string[]; - } - - /** - * @description Sandbox permissions requested by the UI resource. - * Hosts MAY honor these by setting appropriate iframe `allow` attributes. - * Apps SHOULD NOT assume permissions are granted; use JS feature detection as fallback. - */ - export interface McpUiResourcePermissions { - /** @description Request camera access (Permission Policy `camera` feature). */ - camera?: {}; - /** @description Request microphone access (Permission Policy `microphone` feature). */ - microphone?: {}; - /** @description Request geolocation access (Permission Policy `geolocation` feature). */ - geolocation?: {}; - /** @description Request clipboard write access (Permission Policy `clipboard-write` feature). */ - clipboardWrite?: {}; - } - - /** - * @description UI Resource metadata for security and rendering configuration. - */ - export interface McpUiResourceMeta { - /** @description Content Security Policy configuration. */ - csp?: McpUiResourceCsp; - /** @description Sandbox permissions requested by the UI. */ - permissions?: McpUiResourcePermissions; - /** @description Dedicated origin for widget sandbox. */ - domain?: string; - /** @description Visual boundary preference - true if UI prefers a visible border. */ - prefersBorder?: boolean; - } - - /** - * @description Request to change the display mode of the UI. - * The host will respond with the actual display mode that was set, - * which may differ from the requested mode if not supported. - * @see {@link app.App.requestDisplayMode} for the method that sends this request - */ - export interface McpUiRequestDisplayModeRequest { - method: "ui/request-display-mode"; - params: { - /** @description The display mode being requested. */ - mode: McpUiDisplayMode; - }; - } - - /** - * @description Result from requesting a display mode change. - * @see {@link McpUiRequestDisplayModeRequest} - */ - export interface McpUiRequestDisplayModeResult { - /** @description The display mode that was actually set. May differ from requested if not supported. */ - mode: McpUiDisplayMode; - /** - * Index signature required for MCP SDK `Protocol` class compatibility. - * Note: The schema intentionally omits this to enforce strict validation. - */ - [key: string]: unknown; - } - - /** - * @description Tool visibility scope - who can access the tool. - */ - export type McpUiToolVisibility = "model" | "app"; - - /** - * @description UI-related metadata for tools. - */ - export interface McpUiToolMeta { - /** - * URI of the UI resource to display for this tool, if any. - * This is converted to `_meta["ui/resourceUri"]`. - * - * @example "ui://weather/widget.html" - */ - resourceUri?: string; - /** - * @description Who can access this tool. Default: ["model", "app"] - * - "model": Tool visible to and callable by the agent - * - "app": Tool callable by the app from this server only - */ - visibility?: McpUiToolVisibility[]; - } - - /** - * Method string constants for MCP Apps protocol messages. - * - * These constants provide a type-safe way to check message methods without - * accessing internal Zod schema properties. External libraries should use - * these constants instead of accessing `schema.shape.method._def.values[0]`. - * - * @example - * ```typescript - * import { SANDBOX_PROXY_READY_METHOD } from '@modelcontextprotocol/ext-apps'; - * - * if (event.data.method === SANDBOX_PROXY_READY_METHOD) { - * // Handle sandbox proxy ready notification - * } - * ``` - */ - export const OPEN_LINK_METHOD: McpUiOpenLinkRequest["method"] = "ui/open-link"; - export const MESSAGE_METHOD: McpUiMessageRequest["method"] = "ui/message"; - export const SANDBOX_PROXY_READY_METHOD: McpUiSandboxProxyReadyNotification["method"] = - "ui/notifications/sandbox-proxy-ready"; - export const SANDBOX_RESOURCE_READY_METHOD: McpUiSandboxResourceReadyNotification["method"] = - "ui/notifications/sandbox-resource-ready"; - export const SIZE_CHANGED_METHOD: McpUiSizeChangedNotification["method"] = - "ui/notifications/size-changed"; - export const TOOL_INPUT_METHOD: McpUiToolInputNotification["method"] = - "ui/notifications/tool-input"; - export const TOOL_INPUT_PARTIAL_METHOD: McpUiToolInputPartialNotification["method"] = - "ui/notifications/tool-input-partial"; - export const TOOL_RESULT_METHOD: McpUiToolResultNotification["method"] = - "ui/notifications/tool-result"; - export const TOOL_CANCELLED_METHOD: McpUiToolCancelledNotification["method"] = - "ui/notifications/tool-cancelled"; - export const HOST_CONTEXT_CHANGED_METHOD: McpUiHostContextChangedNotification["method"] = - "ui/notifications/host-context-changed"; - export const RESOURCE_TEARDOWN_METHOD: McpUiResourceTeardownRequest["method"] = - "ui/resource-teardown"; - export const INITIALIZE_METHOD: McpUiInitializeRequest["method"] = - "ui/initialize"; - export const INITIALIZED_METHOD: McpUiInitializedNotification["method"] = - "ui/notifications/initialized"; - export const REQUEST_DISPLAY_MODE_METHOD: McpUiRequestDisplayModeRequest["method"] = - "ui/request-display-mode"; - export const UPDATE_MODEL_CONTEXT_METHOD: McpUiUpdateModelContextRequest["method"] = - "ui/update-model-context"; -} +export { McpApps } from '../../../../platform/mcp/common/modelContextProtocolApps.js'; diff --git a/src/vs/workbench/contrib/mcp/electron-browser/mcp.contribution.ts b/src/vs/workbench/contrib/mcp/electron-browser/mcp.contribution.ts index 701c78f4c08e1..799f135c54809 100644 --- a/src/vs/workbench/contrib/mcp/electron-browser/mcp.contribution.ts +++ b/src/vs/workbench/contrib/mcp/electron-browser/mcp.contribution.ts @@ -11,7 +11,10 @@ import { IMcpDevModeDebugging } from '../common/mcpDevMode.js'; import { McpDevModeDebuggingNode } from './mcpDevModeDebuggingNode.js'; import { NativeMcpDiscovery } from './nativeMpcDiscovery.js'; import { WorkbenchMcpGatewayService } from './mcpGatewayService.js'; +import { McpGatewayToolBrokerContribution } from './mcpGatewayToolBrokerContribution.js'; +import { registerWorkbenchContribution2, WorkbenchPhase } from '../../../common/contributions.js'; mcpDiscoveryRegistry.register(new SyncDescriptor(NativeMcpDiscovery)); registerSingleton(IMcpDevModeDebugging, McpDevModeDebuggingNode, InstantiationType.Delayed); registerSingleton(IWorkbenchMcpGatewayService, WorkbenchMcpGatewayService, InstantiationType.Delayed); +registerWorkbenchContribution2('mcpGatewayToolBrokerLocal', McpGatewayToolBrokerContribution, WorkbenchPhase.AfterRestored); diff --git a/src/vs/workbench/contrib/mcp/electron-browser/mcpGatewayToolBrokerContribution.ts b/src/vs/workbench/contrib/mcp/electron-browser/mcpGatewayToolBrokerContribution.ts new file mode 100644 index 0000000000000..af994c82fe31a --- /dev/null +++ b/src/vs/workbench/contrib/mcp/electron-browser/mcpGatewayToolBrokerContribution.ts @@ -0,0 +1,19 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { IWorkbenchContribution } from '../../../common/contributions.js'; +import { IMainProcessService } from '../../../../platform/ipc/common/mainProcessService.js'; +import { McpGatewayToolBrokerChannelName } from '../../../../platform/mcp/common/mcpGateway.js'; +import { IMcpService } from '../common/mcpTypes.js'; +import { McpGatewayToolBrokerChannel } from '../common/mcpGatewayToolBrokerChannel.js'; + +export class McpGatewayToolBrokerContribution implements IWorkbenchContribution { + constructor( + @IMainProcessService mainProcessService: IMainProcessService, + @IMcpService mcpService: IMcpService, + ) { + mainProcessService.registerChannel(McpGatewayToolBrokerChannelName, new McpGatewayToolBrokerChannel(mcpService)); + } +} diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpGatewayToolBrokerChannel.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpGatewayToolBrokerChannel.test.ts new file mode 100644 index 0000000000000..ee893807ecf1c --- /dev/null +++ b/src/vs/workbench/contrib/mcp/test/common/mcpGatewayToolBrokerChannel.test.ts @@ -0,0 +1,201 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { observableValue } from '../../../../../base/common/observable.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { MCP } from '../../common/modelContextProtocol.js'; +import { McpGatewayToolBrokerChannel } from '../../common/mcpGatewayToolBrokerChannel.js'; +import { IMcpIcons, IMcpServer, IMcpTool, McpConnectionState, McpServerCacheState, McpToolVisibility } from '../../common/mcpTypes.js'; +import { TestMcpService } from './testMcpService.js'; + +suite('McpGatewayToolBrokerChannel', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('lists model-visible tools with namespaced identities', async () => { + const mcpService = new TestMcpService(); + const channel = new McpGatewayToolBrokerChannel(mcpService); + + const serverA = createServer('collectionA', 'serverA', [ + createTool('mcp_serverA_echo', async () => ({ content: [{ type: 'text', text: 'A' }] })), + createTool('app-only', async () => ({ content: [{ type: 'text', text: 'A2' }] }), McpToolVisibility.App), + ]); + const serverB = createServer('collectionB', 'serverB', [ + createTool('mcp_serverB_echo', async () => ({ content: [{ type: 'text', text: 'B' }] })), + ]); + + mcpService.servers.set([serverA, serverB], undefined); + + const result = await channel.call(undefined, 'listTools'); + const names = result.map(tool => tool.name).sort(); + + assert.deepStrictEqual(names, [ + 'mcp_serverA_echo', + 'mcp_serverB_echo', + ]); + + channel.dispose(); + }); + + test('routes tool calls by namespaced identity', async () => { + const mcpService = new TestMcpService(); + const channel = new McpGatewayToolBrokerChannel(mcpService); + + const invoked: string[] = []; + const serverA = createServer('collectionA', 'serverA', [ + createTool('mcp_serverA_echo', async args => { + invoked.push(`A:${String(args.name)}`); + return { content: [{ type: 'text', text: 'from A' }] }; + }), + ]); + const serverB = createServer('collectionB', 'serverB', [ + createTool('mcp_serverB_echo', async args => { + invoked.push(`B:${String(args.name)}`); + return { content: [{ type: 'text', text: 'from B' }] }; + }), + ]); + + mcpService.servers.set([serverA, serverB], undefined); + + const resultA = await channel.call(undefined, 'callTool', { + name: 'mcp_serverA_echo', + args: { name: 'one' }, + }); + const resultB = await channel.call(undefined, 'callTool', { + name: 'mcp_serverB_echo', + args: { name: 'two' }, + }); + + assert.deepStrictEqual(invoked, ['A:one', 'B:two']); + assert.strictEqual((resultA.content[0] as MCP.TextContent).text, 'from A'); + assert.strictEqual((resultB.content[0] as MCP.TextContent).text, 'from B'); + + channel.dispose(); + }); + + test('emits onDidChangeTools when tool lists change', async () => { + const mcpService = new TestMcpService(); + const channel = new McpGatewayToolBrokerChannel(mcpService); + const server = createServer('collectionA', 'serverA', [ + createTool('echo', async () => ({ content: [{ type: 'text', text: 'A' }] })), + ]); + + mcpService.servers.set([server], undefined); + + let events = 0; + const disposable = channel.listen(undefined, 'onDidChangeTools')(() => { + events++; + }); + + server.toolsValue.set([ + createTool('echo', async () => ({ content: [{ type: 'text', text: 'A' }] })), + createTool('echo2', async () => ({ content: [{ type: 'text', text: 'A2' }] })), + ], undefined); + + assert.ok(events >= 1); + + disposable.dispose(); + channel.dispose(); + }); + + test('does not start server when cache state is live', async () => { + const mcpService = new TestMcpService(); + const channel = new McpGatewayToolBrokerChannel(mcpService); + + const server = createServer( + 'collectionA', + 'serverA', + [createTool('echo', async () => ({ content: [{ type: 'text', text: 'A' }] }))], + McpServerCacheState.Live, + ); + + mcpService.servers.set([server], undefined); + await channel.call(undefined, 'listTools'); + + assert.strictEqual(server.startCalls, 0); + channel.dispose(); + }); + + test('starts server when cache state is unknown', async () => { + const mcpService = new TestMcpService(); + const channel = new McpGatewayToolBrokerChannel(mcpService); + + const server = createServer( + 'collectionA', + 'serverA', + [createTool('echo', async () => ({ content: [{ type: 'text', text: 'A' }] }))], + McpServerCacheState.Unknown, + ); + + mcpService.servers.set([server], undefined); + await channel.call(undefined, 'listTools'); + + assert.strictEqual(server.startCalls, 1); + channel.dispose(); + }); +}); + +function createServer( + collectionId: string, + definitionId: string, + initialTools: readonly IMcpTool[], + initialCacheState: McpServerCacheState = McpServerCacheState.Live, +): IMcpServer & { toolsValue: ReturnType>; startCalls: number } { + const owner = {}; + const tools = observableValue(owner, initialTools); + const connectionState = observableValue(owner, { state: McpConnectionState.Kind.Running }); + const cacheState = observableValue(owner, initialCacheState); + let startCalls = 0; + + return { + collection: { id: collectionId, label: collectionId }, + definition: { id: definitionId, label: definitionId }, + connection: observableValue(owner, undefined), + connectionState, + serverMetadata: observableValue(owner, undefined), + readDefinitions: () => observableValue(owner, { server: undefined, collection: undefined }), + showOutput: async () => { }, + start: async () => { + startCalls++; + cacheState.set(McpServerCacheState.Live, undefined); + return { state: McpConnectionState.Kind.Running }; + }, + stop: async () => { }, + cacheState, + tools, + prompts: observableValue(owner, []), + capabilities: observableValue(owner, undefined), + resources: () => (async function* () { })(), + resourceTemplates: async () => [], + dispose: () => { }, + toolsValue: tools, + get startCalls() { return startCalls; }, + }; +} + +function createTool(name: string, call: (params: Record) => Promise, visibility: McpToolVisibility = McpToolVisibility.Model): IMcpTool { + const definition: MCP.Tool = { + name, + description: `Tool ${name}`, + inputSchema: { + type: 'object', + properties: { + input: { type: 'string' }, + }, + }, + }; + + return { + id: `tool_${name}`, + referenceName: name, + icons: {} as IMcpIcons, + definition, + visibility, + uiResourceUri: undefined, + call: (params: Record, _context, _token) => call(params), + callWithProgress: (params: Record, _progress, _context, _token = CancellationToken.None) => call(params), + }; +}