Skip to content

Set port dynamically in VSCode extension and read from it in gemini-cli and send initial notification #4255

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jul 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions packages/cli/src/config/config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,7 @@ describe('loadCliConfig ideMode', () => {
// Explicitly delete TERM_PROGRAM and SANDBOX before each test
delete process.env.TERM_PROGRAM;
delete process.env.SANDBOX;
delete process.env.GEMINI_CLI_IDE_SERVER_PORT;
});

afterEach(() => {
Expand Down Expand Up @@ -816,6 +817,7 @@ describe('loadCliConfig ideMode', () => {
process.argv = ['node', 'script.js', '--ide-mode'];
const argv = await parseArguments();
process.env.TERM_PROGRAM = 'vscode';
process.env.GEMINI_CLI_IDE_SERVER_PORT = '3000';
const settings: Settings = {};
const config = await loadCliConfig(settings, [], 'test-session', argv);
expect(config.getIdeMode()).toBe(true);
Expand All @@ -825,6 +827,7 @@ describe('loadCliConfig ideMode', () => {
process.argv = ['node', 'script.js'];
const argv = await parseArguments();
process.env.TERM_PROGRAM = 'vscode';
process.env.GEMINI_CLI_IDE_SERVER_PORT = '3000';
const settings: Settings = { ideMode: true };
const config = await loadCliConfig(settings, [], 'test-session', argv);
expect(config.getIdeMode()).toBe(true);
Expand All @@ -834,6 +837,7 @@ describe('loadCliConfig ideMode', () => {
process.argv = ['node', 'script.js', '--ide-mode'];
const argv = await parseArguments();
process.env.TERM_PROGRAM = 'vscode';
process.env.GEMINI_CLI_IDE_SERVER_PORT = '3000';
const settings: Settings = { ideMode: false };
const config = await loadCliConfig(settings, [], 'test-session', argv);
expect(config.getIdeMode()).toBe(true);
Expand Down Expand Up @@ -872,6 +876,7 @@ describe('loadCliConfig ideMode', () => {
process.argv = ['node', 'script.js', '--ide-mode'];
const argv = await parseArguments();
process.env.TERM_PROGRAM = 'vscode';
process.env.GEMINI_CLI_IDE_SERVER_PORT = '3000';
const settings: Settings = {};
const config = await loadCliConfig(settings, [], 'test-session', argv);
expect(config.getIdeMode()).toBe(true);
Expand All @@ -881,4 +886,16 @@ describe('loadCliConfig ideMode', () => {
expect(mcpServers['_ide_server'].description).toBe('IDE connection');
expect(mcpServers['_ide_server'].trust).toBe(false);
});

it('should throw an error if ideMode is true and no port is set', async () => {
process.argv = ['node', 'script.js', '--ide-mode'];
const argv = await parseArguments();
process.env.TERM_PROGRAM = 'vscode';
const settings: Settings = {};
await expect(
loadCliConfig(settings, [], 'test-session', argv),
).rejects.toThrow(
"Could not run in ide mode, make sure you're running in vs code integrated terminal. Try running in a fresh terminal.",
);
});
});
9 changes: 8 additions & 1 deletion packages/cli/src/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -286,13 +286,20 @@ export async function loadCliConfig(
}

if (ideMode) {
const companionPort = process.env.GEMINI_CLI_IDE_SERVER_PORT;
if (!companionPort) {
throw new Error(
"Could not run in ide mode, make sure you're running in vs code integrated terminal. Try running in a fresh terminal.",
);
}
const httpUrl = `http://localhost:${companionPort}/mcp`;
mcpServers[IDE_SERVER_NAME] = new MCPServerConfig(
undefined, // command
undefined, // args
undefined, // env
undefined, // cwd
undefined, // url
'http://localhost:3000/mcp', // httpUrl
httpUrl, // httpUrl
undefined, // headers
undefined, // tcp
undefined, // timeout
Expand Down
65 changes: 39 additions & 26 deletions packages/vscode-ide-companion/src/ide-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,31 @@ import {
type JSONRPCNotification,
} from '@modelcontextprotocol/sdk/types.js';

import { Server } from 'node:http';

function sendActiveFileChangedNotification(
transport: StreamableHTTPServerTransport,
) {
const editor = vscode.window.activeTextEditor;
const filePath = editor ? editor.document.uri.fsPath : '';
const notification: JSONRPCNotification = {
jsonrpc: '2.0',
method: 'ide/activeFileChanged',
params: { filePath },
};
transport.send(notification);
}

export async function startIDEServer(context: vscode.ExtensionContext) {
const app = express();
app.use(express.json());

const transports: { [sessionId: string]: StreamableHTTPServerTransport } = {};
const sessionsWithInitialNotification = new Set<string>();

const disposable = vscode.window.onDidChangeActiveTextEditor((editor) => {
const filePath = editor ? editor.document.uri.fsPath : null;
const notification: JSONRPCNotification = {
jsonrpc: '2.0',
method: 'ide/activeFileChanged',
params: { filePath },
};
const disposable = vscode.window.onDidChangeActiveTextEditor((_editor) => {
for (const transport of Object.values(transports)) {
transport.send(notification);
sendActiveFileChangedNotification(transport);
}
});
context.subscriptions.push(disposable);
Expand All @@ -44,19 +54,12 @@ export async function startIDEServer(context: vscode.ExtensionContext) {
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (newSessionId) => {
transports[newSessionId] = transport;
const editor = vscode.window.activeTextEditor;
const filePath = editor ? editor.document.uri.fsPath : null;
const notification: JSONRPCNotification = {
jsonrpc: '2.0',
method: 'ide/activeFileChanged',
params: { filePath },
};
transport.send(notification);
},
});

transport.onclose = () => {
if (transport.sessionId) {
sessionsWithInitialNotification.delete(transport.sessionId);
delete transports[transport.sessionId];
}
};
Expand Down Expand Up @@ -101,6 +104,7 @@ export async function startIDEServer(context: vscode.ExtensionContext) {
}

const transport = transports[sessionId];

try {
await transport.handleRequest(req, res);
} catch (error) {
Expand All @@ -109,20 +113,31 @@ export async function startIDEServer(context: vscode.ExtensionContext) {
res.status(400).send('Bad Request');
}
}

if (!sessionsWithInitialNotification.has(sessionId)) {
sendActiveFileChangedNotification(transport);
sessionsWithInitialNotification.add(sessionId);
}
};

app.get('/mcp', handleSessionRequest);

// TODO(#3918): Generate dynamically and write to env variable
const PORT = 3000;
app.listen(PORT, (error?: Error) => {
if (error) {
console.error('Failed to start server:', error);
const server = app.listen(0, () => {
const address = (server as Server).address();
if (address && typeof address !== 'string') {
const port = address.port;
context.environmentVariableCollection.replace(
'GEMINI_CLI_IDE_SERVER_PORT',
port.toString(),
);
console.log(`MCP Streamable HTTP Server listening on port ${port}`);
} else {
const port = 0;
console.error('Failed to start server:', 'Unknown error');
vscode.window.showErrorMessage(
`Companion server failed to start on port ${PORT}: ${error.message}`,
`Companion server failed to start on port ${port}: Unknown error`,
);
}
console.log(`MCP Streamable HTTP Server listening on port ${PORT}`);
});
}

Expand All @@ -144,9 +159,7 @@ const createMcpServer = () => {
async () => {
try {
const activeEditor = vscode.window.activeTextEditor;
const filePath = activeEditor
? activeEditor.document.uri.fsPath
: undefined;
const filePath = activeEditor ? activeEditor.document.uri.fsPath : '';
if (filePath) {
return {
content: [{ type: 'text', text: `Active file: ${filePath}` }],
Expand Down