mscode
MS Code Extension API / core/extensionAPI/mscode
core/extensionAPI/mscode
Type Aliases
MSCodeAPI
MSCodeAPI =
ReturnType<typeofcreateMSCodeAPI>
Defined in: core/extensionAPI/mscode.ts:128
Functions
createMSCodeAPI()
createMSCodeAPI(
extId):object
Defined in: core/extensionAPI/mscode.ts:28
Parameters
extId
string
Returns
authentication
authentication:
object
Authentication API Allows extensions to securely request GitHub access tokens. Prompts the user for permission if not already granted.
authentication.getSession
getSession: () =>
Promise<string|null>
Requests a GitHub authentication session (Token) for the current user.
- Behavior:
- If the user has already granted access to this extension, it returns the token instantly.
- If the user has previously denied access, it returns
null. - If this is the first time, it suspends execution and prompts the user with a secure dialog:
"Extension [Name] wants to sign in using your GitHub account."
Returns
Promise<string | null>
The GitHub Personal Access Token (or OAuth token), or null if denied/not logged in.
*
Example
const token = await mscode.authentication.getSession();
* if (token) {
// Use the token to fetch private GitHub data
const res = await fetch('[https://api.github.com/user/repos](https://api.github.com/user/repos)', {
headers: { Authorization: `token ${token}` }
});
const repos = await res.json();
} else {
mscode.window.showErrorMessage("GitHub access is required to view Pull Requests.");
}
authentication.getUser
getUser: () =>
GitHubUser|null
Retrieves the currently authenticated GitHub user's public profile information.
This acts as a convenience method to avoid making a manual api.github.com/user fetch.
- Security: This will return
nullif the extension has not been granted access viagetSession(), even if the user is logged into the IDE globally.
Returns
GitHubUser | null
The user profile object containing login, name, email, and avatar_url.
*
Example
const user = mscode.authentication.getUser();
if (user) {
console.log(`Welcome back, ${user.name}! (@${user.login})`);
mscode.window.showInformationMessage(`Logged in as ${user.email}`);
}
authentication.hasAccess
hasAccess: () =>
boolean
Synchronously checks if the extension has already been granted GitHub access. This method is completely silent and will never prompt the user.
- Useful for checking state during extension activation to toggle UI elements (e.g., showing a "Sign in" button inside a sidebar view if access is missing).
Returns
boolean
true if the user is authenticated globally AND has authorized this extension.
*
Example
if (mscode.authentication.hasAccess()) {
mscode.menus.registerMenuItem('sidebar/git/actions', { ... });
}
commands
commands:
object
Command palette integration. Register & execute commands; users can invoke them via the palette.
commands.executeCommand
executeCommand: (
id, ...args) =>Promise<any>
Programmatically execute a registered command.
Parameters
id
string
args
...any[]
Returns
Promise<any>
Example
await mscode.commands.executeCommand('editor.action.formatDocument');
commands.registerCommand
registerCommand: (
id,handler) =>IDisposable
Register a new command. Returns a disposable — call .dispose() in deactivate() to unregister.
Parameters
id
string
handler
(...args) => any
Returns
Example
const disposable = mscode.commands.registerCommand('myExt.helloWorld', () => {
mscode.window.showInformationMessage('Hello World!');
});
extensions
extensions:
object
Extensions ecosystem API. Query installed extensions, check active states, or programmatically route users to the marketplace.
extensions.all
all: () =>
ExtensionInfo[]
Retrieves an array of all currently installed extensions. *
Returns
ExtensionInfo[]
A list of extension metadata objects.
Example
const allExts = mscode.extensions.all();
console.log(`There are ${allExts.length} extensions installed.`);
extensions.getExtension
getExtension: (
extensionId) =>ExtensionInfo|undefined
Retrieves details about a specific extension by its unique ID. *
Parameters
extensionId
string
The full ID of the target extension (e.g., ms.python).
Returns
ExtensionInfo | undefined
The extension metadata, or undefined if not installed.
Example
const gitExt = mscode.extensions.getExtension('mscode.git');
if (!gitExt?.isActive) {
mscode.window.showWarningMessage("Please enable the Git extension first!");
}
extensions.installExtension
installExtension: (
extensionId) =>Promise<boolean>
Programmatically installs an extension from the cloud marketplace. Helpful for creating "Extension Packs" that automatically pull down dependencies. *
Parameters
extensionId
string
The ID of the extension to install.
Returns
Promise<boolean>
True if installation succeeded, false otherwise.
extensions.showMarketplace
showMarketplace: (
searchQuery?) =>void
Opens the internal Extensions Sidebar View and optionally applies a search query. Ideal for redirecting users to install a recommended tool or theme. *
Parameters
searchQuery?
string
Optional text to inject into the marketplace search bar.
Returns
void
Example
// Open the marketplace and search for Python tools
mscode.extensions.showMarketplace('@category:languages python');
languages
languages:
object
Language feature contributions. Snippets (and future: formatters, code-lens providers, etc.)
languages.createDiagnosticCollection
createDiagnosticCollection: (
name) =>object
Creates a dedicated container for diagnostic markers. Useful for linking custom external linters, builders, or toolchains (e.g., ESLint).
Parameters
name
string
The human-readable name of the collection.
Returns
An object managing the collection lifetime and markers state.
clear
clear: () =>
void
Wipes all active diagnostic markers published by this specific collection instance.
Returns
void
dispose
dispose: () =>
void
Disposes the collection container and clears all of its registered markers.
Returns
void
name
name:
string
set
set: (
uri,diagnostics) =>void
Publishes an array of diagnostics for a specific file resource path. This triggers native Monaco editor squiggles and updates the UI Problems Panel.
Parameters
uri
string
The absolute target document URI string.
diagnostics
IMarkerData[]
The markers metadata payload array.
Returns
void
languages.getDiagnostics
getDiagnostics: (
uri?) =>IMarker[]
Retrieves all currently active diagnostics (problems) in the editor workspace.
Parameters
uri?
string
Optional target file URI to filter diagnostics.
Returns
IMarker[]
Array of diagnostic markers matching the criteria.
languages.onDidChangeDiagnostics
onDidChangeDiagnostics: (
handler) =>object
Fired globally when file markers or diagnostics are added, changed, or completely cleared.
Parameters
handler
(diagnostics) => void
Callback invoked when a system diagnostics sync occurs.
Returns
object
A disposable instance object to detach the event listener hook securely.
dispose
dispose: () =>
void
Returns
void
languages.registerDocumentFormattingEditProvider
registerDocumentFormattingEditProvider: (
languageId,provider) =>object
Registers a formatting provider for a specific language.
Parameters
languageId
string
The target language identifier (e.g., 'javascript', 'cpp', 'css').
provider
DocumentFormattingEditProvider
The implementation of the formatting logic.
Returns
A disposable object to unregister the provider.
dispose
dispose: () =>
void
Unregisters the formatting provider and cleans up resources.
Returns
void
languages.registerSnippets
registerSnippets: (
languageId,snippetData) =>object
Register code snippets for a language.
snippetData should follow the VS Code snippet JSON format.
Parameters
languageId
string
snippetData
any
Returns
object
dispose
dispose: () =>
void
Returns
void
Example
mscode.languages.registerSnippets('rust', {
'println macro': {
prefix: 'println',
body: ['println!("$1");'],
description: 'Print to stdout',
}
});
lsp
lsp:
object
LSP server registration. Register language servers so the editor can provide completions, hover, diagnostics, etc. for your language.
lsp.registerServer
registerServer: (
languages,config) =>void
Register a language server for one or more language IDs.
Parameters
languages
string[]
config
unknown
Returns
void
Example
mscode.lsp.registerServer(['rust'], {
checkCmd: 'rust-analyzer --version',
packages: ['rust-analyzer'],
serverCmd: 'rust-analyzer',
});
lsp.unregisterServer
unregisterServer: (
languages) =>void
Unregister a previously registered language server. Call this in your extension's deactivate() to clean up.
Parameters
languages
string[]
Returns
void
menus
menus:
object
Dynamic menu contributions. Add context menu items, toolbar buttons, etc.
menus.registerItem
registerItem: (
menuPath,item) =>object
Register a single dynamic menu item into a named menu path. Returns a disposable to remove the item on deactivate.
Parameters
menuPath
string
Target path (e.g., 'editor/context', 'sidebar/files/file-tree/actions')
item
Defines the action, icon, submenu (children), ordering, and structural flatness.
Returns
object
dispose
dispose: () =>
void
Returns
void
Example
const item = mscode.menus.registerItem('editor/title/context', {
id: 'myExt.runFile',
label: 'Run File',
icon: 'play',
order: 0,
onClick: () => console.log("Run executed!")
});
// Later: item.dispose();
menus.registerItems
registerItems: (
menuPath,items) =>object
Register multiple dynamic menu items or complete blocks (with separators) into a named menu path at once. Returns a batch disposable to clean up all injected items on extension deactivate. *
Parameters
menuPath
string
Target path (e.g., 'editor/title', 'editor/context')
items
MenuItem[]
Array of MenuItem objects including separators. *
Returns
object
dispose
dispose: () =>
void
Returns
void
Example
const batch = mscode.menus.registerItems('editor/title', [
{ id: 'ext-feat-1', label: 'Feature One', icon: 'zap', order: 210 },
{ id: 'ext-sep-1', type: 'separator', order: 215 },
{
id: 'ext-feat-2',
label: 'Feature Two',
icon: 'gear',
order: 220 ,
showOnlyWhenSubOptionAvailable: true,
children: [
{ id: 'sub-option-a', label: 'Option A', icon: 'verified-filled', order: 0, onClick: () => commands.executeCommand('extension.myext.a') },
{ id: 'sub-option-b', label: 'Option B', icon: 'verified-filled', order: 1, onClick: () => commands.executeCommand('extension.myext.b') },
],
}
]);
search
search:
object
Search & Replace API.
HIGH-LEVEL (UI-integrated): findInFiles / replaceInFiles / getResults / clearResults → Results appear in the Search Panel sidebar.
LOW-LEVEL (silent / background): search() → Calls the native engine directly; Search Panel is untouched. → Ideal for "find all references", rename preview, analysis tools.
Example
// Show results in sidebar
const files = await mscode.search.findInFiles({ query: 'TODO', includes: ['*.ts'] });
// Silent background search
const refs = await mscode.search.search({ query: 'myFunction', useRegex: false });
search.clearResults
clearResults: () =>
void
Clear all Search Panel results.
Returns
void
search.findInFiles
findInFiles: (
opts) =>Promise<SearchFileResult[]>
Search the workspace and show results in the Search Panel sidebar. Returns the matched results so the caller can also process them.
Parameters
opts
Returns
Promise<SearchFileResult[]>
Example
const results = await mscode.search.findInFiles({
query: 'TODO',
matchCase: false,
includes: ['*.ts'],
});
console.log(`Found ${results.length} files`);
search.getResults
getResults: () =>
SearchFileResult[]
Return the current Search Panel results without running a new search.
Returns
SearchFileResult[]
search.getResultsForFile
getResultsForFile: (
filePath) =>SearchFileResult|undefined
Get all results from a specific file path (if it has matches).
Parameters
filePath
string
Returns
SearchFileResult | undefined
search.getTotalMatchCount
getTotalMatchCount: () =>
number
Total number of matches across all current results. Useful for badge counters in custom sidebar panels.
Returns
number
search.replaceInFiles
replaceInFiles: (
opts) =>Promise<void>
Replace text in the workspace and refresh the Search Panel.
• No filePath → replaces ALL matches across ALL files • filePath only → replaces ALL matches in that file • filePath + matchId → replaces ONE specific match
Parameters
opts
Returns
Promise<void>
Example
// Replace a single match
await mscode.search.replaceInFiles({
replacement: 'newName',
filePath: '/sdcard/project/src/index.ts',
matchId: 'match-42',
});
search.search
search: (
opts) =>Promise<SearchFileResult[]>
Run a search silently using the native engine. The Search Panel state is NOT touched — perfect for background operations like "find all usages", rename-symbol preview, dependency analysis, etc.
Parameters
opts
Returns
Promise<SearchFileResult[]>
Example
const results = await mscode.search.search({
query: 'useAuthStore',
includes: ['*.ts', '*.tsx'],
excludes: ['*.test.ts'],
});
const totalHits = results.reduce((n, f) => n + f.matches.length, 0);
mscode.window.showInformationMessage(`Found ${totalHits} references`);
tasks
tasks:
object
Background task execution. Run shell commands and stream output to the Output panel.
tasks.execute
execute: (
cmd,cwd,onData,channel?) =>object
Execute a shell command and stream output.
outputChannel: false → silent (no Output panel, no Tasks panel entry).
outputChannel: string → mirrored to that channel + listed in Tasks panel.
Parameters
cmd
string
cwd
string
onData
(d) => void
channel?
string | false
Returns
object
kill
kill: () =>
void
Returns
void
result
result:
Promise<{exitCode:number; }>
tasks.runInBackground
runInBackground: (
command,options?) =>object
Run a command in the background and pipe its output to a named Output Channel (visible in the Termis > Output panel). The task will appear in the Tasks panel.
Parameters
command
string
options?
cwd?
string
outputChannel?
string
Returns
object
kill
kill: () =>
void
Returns
void
result
result:
Promise<{exitCode:number; }>
Example
mscode.tasks.runInBackground('npm install', {
cwd: '/sdcard/my-project',
outputChannel: 'npm',
});
termis
termis:
object
Termis panel control. Open/close the terminal panel and switch between terminal, output, and problems views.
termis.closePanel
closePanel: () =>
void
Close / hide the Termis panel.
Returns
void
termis.onDidChangeTermisActiveView
onDidChangeTermisActiveView: (
handler) =>object
Fired when the active view inside the Termis panel changes.
Parameters
handler
(view) => void
Callback receiving the new view name ('terminal' | 'output' | 'problems').
Returns
object
dispose
dispose: () =>
void
Returns
void
termis.onDidCloseTermisPanel
onDidCloseTermisPanel: (
handler) =>object
Fired when the Termis panel is closed or hidden.
Parameters
handler
() => void
Returns
object
dispose
dispose: () =>
void
Returns
void
termis.onDidOpenTermisPanel
onDidOpenTermisPanel: (
handler) =>object
Fired when the Termis panel is opened or becomes visible.
Parameters
handler
() => void
Returns
object
dispose
dispose: () =>
void
Returns
void
termis.openPanel
openPanel: () =>
void
Open the Termis panel and show the terminal view. Creates a default terminal instance if none exist.
Returns
void
termis.setActiveView
setActiveView: (
view) =>void
Switch the active view inside the Termis panel.
Parameters
view
Returns
void
Example
mscode.termis.setActiveView('output'); // show Output tab
termis.activeView
Get Signature
get activeView():
TermisView
Defined in: core/extensionAPI/modules/termisModule.ts:37
- Returns the currently active view ('terminal' | 'output' | 'problems').
Returns
termis.isVisible
Get Signature
get isVisible():
boolean
Defined in: core/extensionAPI/modules/termisModule.ts:31
- Returns true if the Termis panel is currently visible.
Returns
boolean
themes
themes:
object
Editor Themes
themes.themes
themes:
object
themes.themes.getActiveThemeId
getActiveThemeId: () =>
string
Returns the unique ID of the currently active theme.
Returns
string
The active theme ID.
themes.themes.getAll
getAll: () =>
ThemeRegistryEntry[]
Retrieves a list of all registered themes (built-in and extension-contributed).
Returns
Array of theme definitions.
themes.themes.onDidChangeColorTheme
onDidChangeColorTheme: (
callback) => () =>void
Parameters
callback
(themeId) => void
Returns
() => void
themes.themes.register
register: (
def) =>object
Registers a pre-defined TypeScript/JavaScript theme object.
Parameters
def
The theme definition object.
Returns
object
A disposable object to unregister the theme on deactivation.
dispose
dispose: () =>
void
Returns
void
themes.themes.registerFromJson
registerFromJson: (
json) =>object
Registers a theme from a raw JSON string or object.
Parameters
json
string | object
A valid theme JSON string or object.
Returns
object
A disposable object to unregister the theme.
dispose
dispose: () =>
void
Returns
void
themes.themes.setTheme
setTheme: (
id) =>void
Switches the editor to a registered theme.
Parameters
id
string
The unique ID of the theme to apply.
Returns
void
ui
ui:
object
Native UI Toolkit Exposes MS Code's core React components (Collapsible, Button, Icon, etc.) so extensions can render seamlessly integrated custom views.
ui.components
components:
object
MS Code Native React Components. Allows extension developers to build custom views that perfectly match the IDE's theme and behavior.
ui.components.Button
Button:
FC<ButtonProps>
Standard MS Code Button. Supports variants and split-button layouts.
ui.components.Collapsible
Collapsible:
FC<CollapsibleProps>
Highly flexible Collapsible/Accordion component. *
Example
const { Collapsible } = mscode.ui.components;
* const MyCustomView = () => (
<Collapsible
title="Advanced Options"
actions={[{ id: 'add', icon: 'plus', onClick: () => {} }]}
>
<div>Inside content</div>
</Collapsible>
);
ui.components.Icon
Icon:
FC<IconProps>
Standard MS Code Icon component leveraging the Codicon library.
ui.components.InputBox
InputBox:
FC<InputBoxProps>
Native Input Box for text entry with optional inside-icons.
ui.components.Modal
Modal:
FC<ModalProps>
Native MS Code Modal component for building custom dialogs.
Example
const { Modal } = mscode.ui.components;
<Modal isOpen={open} title="Custom Form" onClose={() => setOpen(false)}>
<input type="text" />
</Modal>
ui.components.RichText
RichText:
FC<RichTextProps>
Native RichText component to render Markdown content (supports #setting# links).
Example
const { RichText } = mscode.ui.components;
* const content = "### Guide \n Click to configure: #editor.wordWrap#";
* <RichText
text={content}
onLinkClick={(settingId) => console.log('Open setting:', settingId)}
/>
ui.components.Select
Select:
FC<SelectProps>
Native MS Code Select Dropdown.
Example
const { Select } = mscode.ui.components;
<Select options={[{label: 'A', value: 'a'}]} value={val} onChange={setVal} />
window
window:
any
Window UI. Notifications, output channels, terminal creation and management.
workspace
workspace:
object
Workspace configuration. Read user settings and contribute your extension's setting schema.
workspace.addRecentWorkspace
addRecentWorkspace: (
name,path) =>Promise<void>
Adds a new project or workspace to the history.
Parameters
name
string
The display name of the project.
path
string
The absolute file system path of the workspace.
Returns
Promise<void>
Resolves when the workspace is added to persistence.
workspace.clearRecentWorkspaces
clearRecentWorkspaces: () =>
Promise<void>
Clears the entire recent workspace history.
Returns
Promise<void>
Resolves when the history is wiped.
workspace.getConfiguration
getConfiguration: (
section?) =>object
Accesses configuration settings for a specific section.
Parameters
section?
string
The configuration section (e.g., 'editor', 'terminal').
Returns
An object containing the get method for the specified section.
get
get: <
T>(key,defaultValue?) =>T
Retrieves a configuration value.
Type Parameters
T
T = any
The expected type of the configuration value.
Parameters
key
string
The configuration key.
defaultValue?
T
The fallback value if the key is not found.
Returns
T
The value from settings or the provided default.
workspace.getRecentWorkspaces
getRecentWorkspaces: () =>
RecentWorkspace[]
Retrieves the list of all recently opened workspaces.
Returns
RecentWorkspace[]
A list of recent workspace entries.
workspace.name
name:
string|undefined
workspace.registerConfiguration
registerConfiguration: (
schema) =>object
Registers a new configuration schema to the IDE settings UI.
Parameters
schema
The configuration schema defining properties and defaults.
Returns
An object with a dispose method to unregister the settings.
dispose
dispose: () =>
void
Unregisters the configuration associated with this extension.
Returns
void
workspace.workspacePath
workspacePath:
string|undefined