Fix VS Code MCP tool override descriptions by adding sessionId to URL

- Modified mcpConfigManager.ts to include sessionId in MCP URL configuration
- Fixed server.ts URL parsing to handle query parameters properly
- Enhanced reloadOverrideFile to trigger MCP notifications
- VS Code now shows custom tool descriptions from HumanAgentOverride.json
This commit is contained in:
B Harper
2025-10-24 20:06:49 +11:00
parent 068e745460
commit 59be50e9d9
9 changed files with 66 additions and 2297 deletions
+2 -2
View File
@@ -265,11 +265,11 @@ export async function activate(context: vscode.ExtensionContext) {
await vscode.commands.executeCommand('humanagent-mcp.restartServer');
break;
case '📝 Register for This Workspace':
await mcpConfigManager!.ensureMcpServerRegistered(false);
await mcpConfigManager!.ensureMcpServerRegistered(false, workspaceSessionId);
vscode.window.showInformationMessage('MCP server registered for this workspace! Restart VS Code to enable Copilot integration.');
break;
case '🌐 Register Globally':
await mcpConfigManager!.ensureMcpServerRegistered(true);
await mcpConfigManager!.ensureMcpServerRegistered(true, workspaceSessionId);
vscode.window.showInformationMessage('MCP server registered globally! Restart VS Code to enable Copilot integration.');
break;
case '🗑️ Unregister from This Workspace':
+16 -17
View File
@@ -26,15 +26,15 @@ export class McpConfigManager {
}
}
async ensureMcpServerRegistered(global: boolean = false): Promise<boolean> {
async ensureMcpServerRegistered(global: boolean = false, sessionId?: string): Promise<boolean> {
if (global) {
return this.registerGlobally();
return this.registerGlobally(sessionId);
} else {
return this.registerInWorkspace();
return this.registerInWorkspace(sessionId);
}
}
private async registerInWorkspace(): Promise<boolean> {
private async registerInWorkspace(sessionId?: string): Promise<boolean> {
const currentWorkspaceRoot = this.getCurrentWorkspaceRoot();
if (!currentWorkspaceRoot) {
throw new Error('No workspace folder available for workspace registration - this is a blank workspace');
@@ -53,28 +53,26 @@ export class McpConfigManager {
fs.mkdirSync(vscodeDirPath, { recursive: true });
}
// Read existing config or create new one
// Load existing config or create new one
let config: McpConfiguration = { servers: {}, inputs: [] };
if (fs.existsSync(mcpConfigPath)) {
try {
const configContent = fs.readFileSync(mcpConfigPath, 'utf8');
config = JSON.parse(configContent);
} catch (error) {
console.warn('Failed to parse existing mcp.json, creating new one', error);
const existingConfig = fs.readFileSync(mcpConfigPath, 'utf8');
config = JSON.parse(existingConfig);
if (!config.servers) { config.servers = {}; }
if (!config.inputs) { config.inputs = []; }
} catch (parseError) {
console.log(`Creating new MCP config file due to parse error: ${parseError}`);
}
}
// Check if our server is already registered
if (config.servers[McpConfigManager.SERVER_NAME]) {
return true; // Already configured
}
// Use the extension path passed during construction
// Configure our MCP server (HTTP transport)
const mcpUrl = sessionId ? `http://127.0.0.1:3737/mcp?sessionId=${sessionId}` : 'http://127.0.0.1:3737/mcp';
const serverConfig: any = {
type: 'http',
url: 'http://127.0.0.1:3737/mcp',
url: mcpUrl,
notifications: {
enableSound: true,
enableFlashing: true
@@ -94,7 +92,7 @@ export class McpConfigManager {
}
}
private async registerGlobally(): Promise<boolean> {
private async registerGlobally(sessionId?: string): Promise<boolean> {
if (!this.extensionPath) {
throw new Error('Extension path not provided');
}
@@ -103,9 +101,10 @@ export class McpConfigManager {
// Use the extension path passed during construction
// Configure our MCP server (HTTP transport)
const mcpUrl = sessionId ? `http://127.0.0.1:3737/mcp?sessionId=${sessionId}` : 'http://127.0.0.1:3737/mcp';
const serverConfig: any = {
type: 'http',
url: 'http://127.0.0.1:3737/mcp',
url: mcpUrl,
notifications: {
enableSound: true,
enableFlashing: true
+20 -3
View File
@@ -482,7 +482,10 @@ export class McpServer extends EventEmitter {
}
// Handle different endpoints
if (req.url === '/mcp') {
// Parse URL to handle query parameters
const reqUrl = new URL(req.url!, `http://${req.headers.host}`);
if (reqUrl.pathname === '/mcp') {
// Main MCP protocol endpoint
} else if (req.url === '/HumanAgent') {
// Web interface for multi-session chat
@@ -527,10 +530,24 @@ export class McpServer extends EventEmitter {
this.debugLogger.log('HTTP', `Complete request body received (${body.length} bytes)`);
this.debugLogger.log('HTTP', 'Request Body:', body);
// Extract sessionId from query params in URL
const url = new URL(req.url!, `http://${req.headers.host}`);
const sessionId = url.searchParams.get('sessionId');
this.debugLogger.log('HTTP', `MCP request sessionId from URL: ${sessionId}`);
try {
const message = JSON.parse(body);
this.debugLogger.log('HTTP', 'Parsed JSON message:', message);
// Add sessionId to message params if available
if (sessionId) {
if (!message.params) {
message.params = {};
}
message.params.sessionId = sessionId;
this.debugLogger.log('HTTP', `Added sessionId ${sessionId} to MCP message params`);
}
const response = await this.handleMessage(message);
this.debugLogger.log('HTTP', 'Response from handleMessage:', response);
@@ -1524,10 +1541,10 @@ export class McpServer extends EventEmitter {
}
private handleToolsList(message: McpMessage): McpMessage {
// Use extension session ID if available, otherwise fall back to detecting from headers
// Use extension session ID if available, otherwise extract from message params
let sessionIdToUse = this.sessionId; // Extension session ID
// If no extension session, try to extract from message params or headers
// If no extension session, try to extract from message params
if (!sessionIdToUse && message.params?.sessionId) {
sessionIdToUse = message.params.sessionId;
}
+21
View File
@@ -314,6 +314,27 @@ export class ChatWebviewProvider implements vscode.WebviewViewProvider {
}
}
// Call reload endpoint to trigger tools/list_changed notification to VS Code MCP
try {
const reloadResponse = await fetch('http://localhost:3737/reload', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
workspacePath: workspaceFolder.uri.fsPath
})
});
if (reloadResponse.ok) {
console.log('Successfully triggered tools/list_changed notification for VS Code MCP');
} else {
console.error('Failed to trigger MCP tools reload');
}
} catch (reloadError) {
console.error('Failed to call /reload endpoint:', reloadError);
}
vscode.window.showInformationMessage('Override file reloaded successfully!');
} else {
vscode.window.showWarningMessage('Failed to get sessions from server');