Skip to content

Commit bcdb8c4

Browse files
author
Eric Oliver
committed
mcp servers working
1 parent d33c71f commit bcdb8c4

File tree

4 files changed

+179
-0
lines changed

4 files changed

+179
-0
lines changed

src/cli/cli-entry.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,34 @@ program
283283
console.log()
284284
}
285285

286+
// Initialize MCP service if auto-connect is enabled
287+
if (options.mcpAutoConnect) {
288+
try {
289+
getCLILogger().debug("[cli-entry] Initializing GlobalCLIMcpService...")
290+
const { GlobalCLIMcpService } = await import("./services/GlobalCLIMcpService")
291+
const globalMcpService = GlobalCLIMcpService.getInstance()
292+
293+
// Initialize with MCP-specific options
294+
await globalMcpService.initialize({
295+
mcpConfigPath: options.mcpConfig,
296+
mcpAutoConnect: options.mcpAutoConnect,
297+
mcpTimeout: options.mcpTimeout,
298+
mcpRetries: options.mcpRetries,
299+
})
300+
getCLILogger().debug("[cli-entry] GlobalCLIMcpService initialized successfully")
301+
} catch (error) {
302+
getCLILogger().debug("[cli-entry] Failed to initialize GlobalCLIMcpService:", error)
303+
if (options.verbose) {
304+
console.warn(
305+
chalk.yellow("Warning: MCP initialization failed:"),
306+
error instanceof Error ? error.message : String(error),
307+
)
308+
}
309+
}
310+
} else {
311+
getCLILogger().debug("[cli-entry] MCP auto-connect disabled, skipping MCP initialization")
312+
}
313+
286314
// Pass configuration to processors
287315
if (options.batch || options.stdin || !options.interactive) {
288316
// Use NonInteractiveModeService for non-interactive operations

src/cli/index.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,9 +171,13 @@ program
171171
.option("--no-mcp-auto-connect", "Do not automatically connect to enabled MCP servers")
172172
.option("--mcp-log-level <level>", "MCP logging level (error, warn, info, debug)", validateMcpLogLevel)
173173
.action(async (options: CliOptions) => {
174+
console.log("[DEBUG] CLI: Entered main action with options:", JSON.stringify(options, null, 2))
175+
174176
// Initialize CLI logger first
175177
const logger = initializeCLILogger(options.verbose, options.quiet, options.color)
176178

179+
console.log("[DEBUG] CLI: Logger initialized")
180+
177181
// Set up graceful shutdown handlers
178182
let isShuttingDown = false
179183
const gracefulShutdown = async (signal: string) => {
@@ -235,21 +239,35 @@ program
235239
await PlatformServiceFactory.initialize(PlatformContext.CLI, "roo-cline", options.config)
236240

237241
// Initialize global MCP service once at startup
242+
console.log(
243+
"[DEBUG] CLI: MCP auto-connect check:",
244+
options.mcpAutoConnect,
245+
"!== false =",
246+
options.mcpAutoConnect !== false,
247+
)
238248
if (options.mcpAutoConnect !== false) {
249+
console.log("[DEBUG] CLI: About to initialize global MCP service...")
239250
try {
251+
const { GlobalCLIMcpService } = await import("./services/GlobalCLIMcpService")
252+
console.log("[DEBUG] CLI: GlobalCLIMcpService imported successfully")
240253
const globalMcpService = GlobalCLIMcpService.getInstance()
254+
console.log("[DEBUG] CLI: GlobalCLIMcpService instance obtained")
241255
await globalMcpService.initialize({
242256
mcpConfigPath: options.mcpConfig,
243257
mcpAutoConnect: options.mcpAutoConnect,
244258
mcpTimeout: options.mcpTimeout,
245259
mcpRetries: options.mcpRetries,
246260
})
261+
console.log("[DEBUG] CLI: GlobalCLIMcpService.initialize() completed")
247262
if (options.verbose) {
248263
logger.debug("Global MCP service initialized successfully")
249264
}
250265
} catch (error) {
266+
console.error("[DEBUG] CLI: Failed to initialize global MCP service:", error)
251267
logger.warn("Failed to initialize global MCP service:", error)
252268
}
269+
} else {
270+
console.log("[DEBUG] CLI: MCP auto-connect disabled, skipping MCP initialization")
253271
}
254272

255273
// Handle MCP auto-connect logic: default to true, but allow explicit override

src/cli/services/GlobalCLIMcpService.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,27 @@ class GlobalCLIMcpService {
5555
const logger = getCLILogger()
5656

5757
try {
58+
console.log("[GlobalCLIMcpService] DEBUG: Starting MCP service initialization...")
59+
console.log("[GlobalCLIMcpService] DEBUG: Config path:", this.configPath || "undefined")
60+
console.log("[GlobalCLIMcpService] DEBUG: Auto-connect:", this.mcpAutoConnect)
61+
5862
logger.debug("[GlobalCLIMcpService] Initializing MCP service...")
5963

6064
this.mcpService = new CLIMcpService(this.configPath)
6165

6266
// Load and connect to configured servers
67+
console.log("[GlobalCLIMcpService] DEBUG: About to load server configs...")
6368
const serverConfigs = await this.mcpService.loadServerConfigs()
6469
console.log(`Loading Roo Code MCP configuration from: ${this.configPath || "default locations"}`)
6570
console.log(`Found ${serverConfigs.length} enabled MCP servers`)
6671

72+
// Debug: log server details
73+
serverConfigs.forEach((config) => {
74+
console.log(` - Server: ${config.name} (${config.id}) - enabled: ${config.enabled !== false}`)
75+
})
76+
6777
if (this.mcpAutoConnect && serverConfigs.length > 0) {
78+
console.log("[GlobalCLIMcpService] DEBUG: Starting server connections...")
6879
for (const config of serverConfigs) {
6980
try {
7081
console.log(`CLI MCP: Connecting to server ${config.name}...`)
@@ -75,12 +86,17 @@ class GlobalCLIMcpService {
7586
}
7687
}
7788
} else if (!this.mcpAutoConnect) {
89+
console.log("[GlobalCLIMcpService] DEBUG: Auto-connect disabled, servers loaded but not connected")
7890
logger.debug("CLI MCP: Auto-connect disabled, servers loaded but not connected")
91+
} else {
92+
console.log("[GlobalCLIMcpService] DEBUG: No servers to connect to")
7993
}
8094

8195
this.initialized = true
96+
console.log("[GlobalCLIMcpService] DEBUG: MCP service initialization completed successfully")
8297
logger.debug("[GlobalCLIMcpService] MCP service initialized successfully")
8398
} catch (error) {
99+
console.error("[GlobalCLIMcpService] ERROR: Failed to initialize MCP service:", error)
84100
logger.warn(`[GlobalCLIMcpService] Failed to initialize MCP service:`, error)
85101
// Don't throw - allow CLI to continue without MCP
86102
}

src/core/task/Task.ts

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,17 @@ import { getWorkspacePath } from "../../utils/path"
5050
// prompts
5151
import { formatResponse } from "../prompts/responses"
5252
import { SYSTEM_PROMPT } from "../prompts/system"
53+
import { getToolDescriptionsForMode } from "../prompts/tools"
54+
import {
55+
getRulesSection,
56+
getSystemInfoSection,
57+
getObjectiveSection,
58+
getMcpServersSection,
59+
getToolUseGuidelinesSection,
60+
getCapabilitiesSection,
61+
getModesSection,
62+
addCustomInstructions,
63+
} from "../prompts/sections"
5364

5465
// core modules
5566
import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector"
@@ -750,6 +761,17 @@ export class Task extends EventEmitter<ClineEvents> {
750761
return result
751762
}
752763

764+
case "search_files": {
765+
const { searchFilesTool } = await import("../tools/searchFilesTool")
766+
const result = await this.executeToolWithCLIInterface(searchFilesTool, {
767+
name: toolName,
768+
params,
769+
type: "tool_use",
770+
partial: false,
771+
})
772+
return result
773+
}
774+
753775
case "attempt_completion": {
754776
const { attemptCompletionTool } = await import("../tools/attemptCompletionTool")
755777
const result = await this.executeToolWithCLIInterface(attemptCompletionTool, {
@@ -1364,6 +1386,64 @@ ${getObjectiveSection()}`
13641386
return systemPrompt
13651387
}
13661388

1389+
// In CLI mode, provider might be undefined, so we need to handle this case
1390+
if (!provider) {
1391+
// For CLI mode, create a minimal system prompt that includes MCP server information
1392+
const mcpServersSection = await getMcpServersSection(
1393+
mcpHub,
1394+
this.diffEnabled ? this.diffStrategy : undefined,
1395+
enableMcpServerCreation,
1396+
)
1397+
1398+
const systemPrompt = `You are Roo, a highly skilled software engineer with extensive knowledge in many programming languages, frameworks, design patterns, and best practices. Applying the wisdom in this document (docs/prompts/development-prompt.md), you write the application code
1399+
1400+
====
1401+
1402+
MARKDOWN RULES
1403+
1404+
ALL responses MUST show ANY \`language construct\` OR filename reference as clickable, exactly as [\`filename OR language.declaration()\`](relative/file/path.ext:line); line is required for \`syntax\` and optional for filename links. This applies to ALL markdown responses and ALSO those in <attempt_completion>
1405+
1406+
====
1407+
1408+
TOOL USE
1409+
1410+
You have access to a set of tools that are executed upon the user's approval. You can use one tool per message, and will receive the result of that tool use in the user's response. You use tools step-by-step to accomplish a given task, with each tool use informed by the result of the previous tool use.
1411+
1412+
${getToolDescriptionsForMode(
1413+
mode,
1414+
this.workspacePath,
1415+
(this.api.getModel().info.supportsComputerUse ?? false) && (browserToolEnabled ?? true),
1416+
undefined, // codeIndexManager not available in CLI mode
1417+
this.diffEnabled ? this.diffStrategy : undefined,
1418+
browserViewportSize,
1419+
mcpHub,
1420+
customModes,
1421+
experiments,
1422+
maxReadFileLine !== -1,
1423+
{
1424+
maxConcurrentFileReads,
1425+
},
1426+
)}
1427+
1428+
${getToolUseGuidelinesSection()}
1429+
1430+
${mcpServersSection}
1431+
1432+
${getCapabilitiesSection(this.workspacePath, (this.api.getModel().info.supportsComputerUse ?? false) && (browserToolEnabled ?? true), mcpHub, this.diffEnabled ? this.diffStrategy : undefined, undefined)}
1433+
1434+
${await this.getCliModesSection(customModes)}
1435+
1436+
${getRulesSection(this.workspacePath, (this.api.getModel().info.supportsComputerUse ?? false) && (browserToolEnabled ?? true), this.diffEnabled ? this.diffStrategy : undefined)}
1437+
1438+
${getSystemInfoSection(this.workspacePath)}
1439+
1440+
${getObjectiveSection()}
1441+
1442+
${await addCustomInstructions("", customInstructions || "", this.workspacePath, mode, { language: language ?? "English", rooIgnoreInstructions })}`
1443+
1444+
return systemPrompt
1445+
}
1446+
13671447
return SYSTEM_PROMPT(
13681448
provider.context,
13691449
this.workspacePath,
@@ -1387,6 +1467,43 @@ ${getObjectiveSection()}`
13871467
)
13881468
}
13891469

1470+
/**
1471+
* Create a simplified modes section for CLI mode that doesn't require VSCode context
1472+
*/
1473+
private async getCliModesSection(customModes?: any[]): Promise<string> {
1474+
// Import modes directly instead of using VSCode context
1475+
const { getAllModes } = await import("../../shared/modes")
1476+
const allModes = getAllModes(customModes)
1477+
1478+
let modesContent = `====
1479+
1480+
MODES
1481+
1482+
- These are the currently available modes:
1483+
${allModes
1484+
.map((mode: any) => {
1485+
let description: string
1486+
if (mode.whenToUse && mode.whenToUse.trim() !== "") {
1487+
// Use whenToUse as the primary description, indenting subsequent lines for readability
1488+
description = mode.whenToUse.replace(/\n/g, "\n ")
1489+
} else {
1490+
// Fallback to the first sentence of roleDefinition if whenToUse is not available
1491+
description = mode.roleDefinition.split(".")[0]
1492+
}
1493+
return ` * "${mode.name}" mode (${mode.slug}) - ${description}`
1494+
})
1495+
.join("\n")}`
1496+
1497+
modesContent += `
1498+
If the user asks you to create or edit a new mode for this project, you should read the instructions by using the fetch_instructions tool, like this:
1499+
<fetch_instructions>
1500+
<task>create_mode</task>
1501+
</fetch_instructions>
1502+
`
1503+
1504+
return modesContent
1505+
}
1506+
13901507
private async getEnvironmentDetails(includeFileDetails: boolean): Promise<string> {
13911508
return getEnvironmentDetails(this, includeFileDetails)
13921509
}

0 commit comments

Comments
 (0)