Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
microsoft
GitHub Repository: microsoft/vscode
Path: blob/main/extensions/copilot/src/extension/chatSessions/copilotcli/vscode-node/tools/getSelection.ts
13406 views
1
/*---------------------------------------------------------------------------------------------
2
* Copyright (c) Microsoft Corporation. All rights reserved.
3
* Licensed under the MIT License. See License.txt in the project root for license information.
4
*--------------------------------------------------------------------------------------------*/
5
6
import * as vscode from 'vscode';
7
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
8
import { makeTextResult } from './utils';
9
import { ILogger } from '../../../../../platform/log/common/logService';
10
11
export interface SelectionInfo {
12
text: string;
13
filePath: string;
14
fileUrl: string;
15
selection: {
16
start: { line: number; character: number };
17
end: { line: number; character: number };
18
isEmpty: boolean;
19
};
20
}
21
22
export function getSelectionInfo(editor: vscode.TextEditor): SelectionInfo {
23
const document = editor.document;
24
const selection = editor.selection;
25
const text = document.getText(selection);
26
27
return {
28
text,
29
filePath: document.uri.fsPath,
30
fileUrl: document.uri.toString(),
31
selection: {
32
start: { line: selection.start.line, character: selection.start.character },
33
end: { line: selection.end.line, character: selection.end.character },
34
isEmpty: selection.isEmpty,
35
},
36
};
37
}
38
39
export class SelectionState {
40
private _latestSelection: SelectionInfo | null = null;
41
42
update(selection: SelectionInfo | null): void {
43
this._latestSelection = selection;
44
}
45
46
get latest(): SelectionInfo | null {
47
return this._latestSelection;
48
}
49
}
50
51
export function registerGetSelectionTool(server: McpServer, logger: ILogger, selectionState: SelectionState): void {
52
server.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 () => {
53
logger.debug('Getting text selection');
54
const editor = vscode.window.activeTextEditor;
55
if (editor) {
56
const selectionInfo = getSelectionInfo(editor);
57
logger.trace(`Returning current selection from: ${selectionInfo.filePath}`);
58
return makeTextResult({ ...selectionInfo, current: true });
59
}
60
if (selectionState.latest) {
61
logger.trace(`Returning cached selection from: ${selectionState.latest.filePath}`);
62
return makeTextResult({ ...selectionState.latest, current: false });
63
}
64
logger.trace('No selection available');
65
return makeTextResult(null);
66
});
67
}
68
69