Path: blob/main/extensions/copilot/src/extension/chatSessions/copilotcli/vscode-node/tools/getSelection.ts
13406 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import * as vscode from 'vscode';6import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';7import { makeTextResult } from './utils';8import { ILogger } from '../../../../../platform/log/common/logService';910export interface SelectionInfo {11text: string;12filePath: string;13fileUrl: string;14selection: {15start: { line: number; character: number };16end: { line: number; character: number };17isEmpty: boolean;18};19}2021export function getSelectionInfo(editor: vscode.TextEditor): SelectionInfo {22const document = editor.document;23const selection = editor.selection;24const text = document.getText(selection);2526return {27text,28filePath: document.uri.fsPath,29fileUrl: document.uri.toString(),30selection: {31start: { line: selection.start.line, character: selection.start.character },32end: { line: selection.end.line, character: selection.end.character },33isEmpty: selection.isEmpty,34},35};36}3738export class SelectionState {39private _latestSelection: SelectionInfo | null = null;4041update(selection: SelectionInfo | null): void {42this._latestSelection = selection;43}4445get latest(): SelectionInfo | null {46return this._latestSelection;47}48}4950export function registerGetSelectionTool(server: McpServer, logger: ILogger, selectionState: SelectionState): void {51server.registerTool('get_selection', { description: 'Get text selection. Returns current selection if an editor is active, otherwise returns the latest cached selection. The "current" field indicates if this is from the active editor (true) or cached (false).' }, async () => {52logger.debug('Getting text selection');53const editor = vscode.window.activeTextEditor;54if (editor) {55const selectionInfo = getSelectionInfo(editor);56logger.trace(`Returning current selection from: ${selectionInfo.filePath}`);57return makeTextResult({ ...selectionInfo, current: true });58}59if (selectionState.latest) {60logger.trace(`Returning cached selection from: ${selectionState.latest.filePath}`);61return makeTextResult({ ...selectionState.latest, current: false });62}63logger.trace('No selection available');64return makeTextResult(null);65});66}676869