Getting a list of Jupyter kernels in a VS Code extension: What's the proper way?

I’m working on a VS Code extension and I need to get a list of all the Jupyter kernels available. I’ve tried using the Jupyter extension API from ms-toolsai.jupyter, but I’m running into some trouble.

Here’s what I’ve done so far:

async function fetchKernels() {
  const jupyterExtension = vscode.extensions.getExtension('ms-toolsai.jupyter');
  if (!jupyterExtension) {
    console.error('No Jupyter extension found');
    return [];
  }

  await jupyterExtension.activate();

  const api = jupyterExtension.exports;
  if (!api) {
    console.error('Jupyter API not available');
    return [];
  }

  try {
    const kernelManager = await api.getKernelManager();
    return kernelManager.getAvailableKernels();
  } catch (err) {
    console.error('Failed to fetch kernels:', err);
    return [];
  }
}

But when I run this, I get an error saying I need to contact the Jupyter Extension for API access. I’ve made sure the Jupyter extension is installed and active.

Does anyone know the right way to do this? Am I missing some kind of permission? How can I fix this error and get the list of kernels? Any help would be awesome!

hey mate, i had the same problem. try using the jupyter.kernelspec.findKernelSpecs() command instead. it worked for me without needing special permissions. just make sure u have the jupyter extension installed and activated first. good luck!

I’ve encountered this issue before. The Jupyter extension API can be tricky. Have you considered using the VSCode Notebook API instead? It’s more stable and doesn’t require special permissions. Here’s a snippet that might help:

import * as vscode from 'vscode';

async function getKernels() {
    const kernels = await vscode.notebooks.getNotebookKernels();
    return kernels.filter(k => k.notebookType === 'jupyter-notebook');
}

This approach leverages VSCode’s built-in functionality, which is generally more reliable. It also doesn’t depend on the Jupyter extension being installed, which could make your extension more robust. Just ensure you’re targeting the appropriate VSCode version that supports this API.

I ran into a similar issue when developing a VS Code extension that interacted with Jupyter. The key is to properly declare the dependency on the Jupyter extension in your package.json file. Add this to your extensionDependencies:

"extensionDependencies": [
    "ms-toolsai.jupyter"
],

This tells VS Code that your extension requires Jupyter to function. Additionally, make sure you’re using the correct API version. The Jupyter API has evolved, so check their latest documentation for the most up-to-date method calls.

One more thing - sometimes the kernels aren’t immediately available when the extension activates. You might need to implement a retry mechanism or listen for a specific event that signals when kernels are ready. Hope this helps you get unstuck!