@google/gemini-cli-core 0.1.12 → 0.1.13-nightly.250727.3e81359c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -3
- package/dist/google-gemini-cli-core-0.1.13.tgz +0 -0
- package/dist/src/code_assist/codeAssist.js +2 -2
- package/dist/src/code_assist/codeAssist.js.map +1 -1
- package/dist/src/code_assist/oauth2.js +46 -5
- package/dist/src/code_assist/oauth2.js.map +1 -1
- package/dist/src/code_assist/oauth2.test.js +107 -10
- package/dist/src/code_assist/oauth2.test.js.map +1 -1
- package/dist/src/code_assist/server.d.ts +4 -6
- package/dist/src/code_assist/server.js +4 -69
- package/dist/src/code_assist/server.js.map +1 -1
- package/dist/src/code_assist/server.test.js +10 -2
- package/dist/src/code_assist/server.test.js.map +1 -1
- package/dist/src/code_assist/setup.d.ts +6 -1
- package/dist/src/code_assist/setup.js +4 -1
- package/dist/src/code_assist/setup.js.map +1 -1
- package/dist/src/code_assist/setup.test.js +4 -1
- package/dist/src/code_assist/setup.test.js.map +1 -1
- package/dist/src/code_assist/types.d.ts +2 -2
- package/dist/src/config/config.d.ts +55 -11
- package/dist/src/config/config.js +85 -33
- package/dist/src/config/config.js.map +1 -1
- package/dist/src/config/config.test.js +29 -26
- package/dist/src/config/config.test.js.map +1 -1
- package/dist/src/config/flashFallback.test.js +1 -1
- package/dist/src/config/flashFallback.test.js.map +1 -1
- package/dist/src/core/client.d.ts +8 -3
- package/dist/src/core/client.js +62 -3
- package/dist/src/core/client.js.map +1 -1
- package/dist/src/core/client.test.js +145 -37
- package/dist/src/core/client.test.js.map +1 -1
- package/dist/src/core/contentGenerator.d.ts +3 -2
- package/dist/src/core/contentGenerator.js +5 -4
- package/dist/src/core/contentGenerator.js.map +1 -1
- package/dist/src/core/contentGenerator.test.js +12 -5
- package/dist/src/core/contentGenerator.test.js.map +1 -1
- package/dist/src/core/coreToolScheduler.js +14 -1
- package/dist/src/core/coreToolScheduler.js.map +1 -1
- package/dist/src/core/coreToolScheduler.test.js +84 -2
- package/dist/src/core/coreToolScheduler.test.js.map +1 -1
- package/dist/src/core/geminiChat.d.ts +4 -3
- package/dist/src/core/geminiChat.js +8 -11
- package/dist/src/core/geminiChat.js.map +1 -1
- package/dist/src/core/geminiRequest.js +2 -37
- package/dist/src/core/geminiRequest.js.map +1 -1
- package/dist/src/core/logger.js +6 -0
- package/dist/src/core/logger.js.map +1 -1
- package/dist/src/core/logger.test.js +1 -1
- package/dist/src/core/logger.test.js.map +1 -1
- package/dist/src/core/modelCheck.d.ts +1 -1
- package/dist/src/core/modelCheck.js +10 -3
- package/dist/src/core/modelCheck.js.map +1 -1
- package/dist/src/core/nonInteractiveToolExecutor.test.js +8 -5
- package/dist/src/core/nonInteractiveToolExecutor.test.js.map +1 -1
- package/dist/src/core/prompts.js +42 -18
- package/dist/src/core/prompts.js.map +1 -1
- package/dist/src/core/prompts.test.js +121 -4
- package/dist/src/core/prompts.test.js.map +1 -1
- package/dist/src/core/turn.d.ts +12 -3
- package/dist/src/core/turn.js +10 -0
- package/dist/src/core/turn.js.map +1 -1
- package/dist/src/core/turn.test.js +129 -0
- package/dist/src/core/turn.test.js.map +1 -1
- package/dist/src/ide/ide-client.d.ts +28 -0
- package/dist/src/ide/ide-client.js +88 -0
- package/dist/src/ide/ide-client.js.map +1 -0
- package/dist/src/ide/ideContext.d.ts +174 -0
- package/dist/src/ide/ideContext.js +101 -0
- package/dist/src/ide/ideContext.js.map +1 -0
- package/dist/src/ide/ideContext.test.js +111 -0
- package/dist/src/ide/ideContext.test.js.map +1 -0
- package/dist/src/index.d.ts +15 -0
- package/dist/src/index.js +17 -0
- package/dist/src/index.js.map +1 -1
- package/dist/src/mcp/google-auth-provider.d.ts +23 -0
- package/dist/src/mcp/google-auth-provider.js +63 -0
- package/dist/src/mcp/google-auth-provider.js.map +1 -0
- package/dist/src/mcp/google-auth-provider.test.d.ts +6 -0
- package/dist/src/mcp/google-auth-provider.test.js +54 -0
- package/dist/src/mcp/google-auth-provider.test.js.map +1 -0
- package/dist/src/mcp/oauth-provider.d.ts +142 -0
- package/dist/src/mcp/oauth-provider.js +446 -0
- package/dist/src/mcp/oauth-provider.js.map +1 -0
- package/dist/src/mcp/oauth-provider.test.d.ts +6 -0
- package/dist/src/mcp/oauth-provider.test.js +520 -0
- package/dist/src/mcp/oauth-provider.test.js.map +1 -0
- package/dist/src/mcp/oauth-token-storage.d.ts +81 -0
- package/dist/src/mcp/oauth-token-storage.js +149 -0
- package/dist/src/mcp/oauth-token-storage.js.map +1 -0
- package/dist/src/mcp/oauth-token-storage.test.d.ts +6 -0
- package/dist/src/mcp/oauth-token-storage.test.js +205 -0
- package/dist/src/mcp/oauth-token-storage.test.js.map +1 -0
- package/dist/src/mcp/oauth-utils.d.ts +109 -0
- package/dist/src/mcp/oauth-utils.js +183 -0
- package/dist/src/mcp/oauth-utils.js.map +1 -0
- package/dist/src/mcp/oauth-utils.test.d.ts +6 -0
- package/dist/src/mcp/oauth-utils.test.js +144 -0
- package/dist/src/mcp/oauth-utils.test.js.map +1 -0
- package/dist/src/prompts/mcp-prompts.d.ts +8 -0
- package/dist/src/prompts/mcp-prompts.js +13 -0
- package/dist/src/prompts/mcp-prompts.js.map +1 -0
- package/dist/src/prompts/prompt-registry.d.ts +26 -0
- package/dist/src/prompts/prompt-registry.js +47 -0
- package/dist/src/prompts/prompt-registry.js.map +1 -0
- package/dist/src/services/fileDiscoveryService.test.js +101 -60
- package/dist/src/services/fileDiscoveryService.test.js.map +1 -1
- package/dist/src/services/gitService.js +1 -5
- package/dist/src/services/gitService.js.map +1 -1
- package/dist/src/services/gitService.test.js +68 -92
- package/dist/src/services/gitService.test.js.map +1 -1
- package/dist/src/services/loopDetectionService.d.ts +94 -0
- package/dist/src/services/loopDetectionService.js +318 -0
- package/dist/src/services/loopDetectionService.js.map +1 -0
- package/dist/src/services/loopDetectionService.test.d.ts +6 -0
- package/dist/src/services/loopDetectionService.test.js +266 -0
- package/dist/src/services/loopDetectionService.test.js.map +1 -0
- package/dist/src/services/shellExecutionService.d.ts +70 -0
- package/dist/src/services/shellExecutionService.js +152 -0
- package/dist/src/services/shellExecutionService.js.map +1 -0
- package/dist/src/services/shellExecutionService.test.d.ts +6 -0
- package/dist/src/services/shellExecutionService.test.js +258 -0
- package/dist/src/services/shellExecutionService.test.js.map +1 -0
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.d.ts +5 -1
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.js +69 -4
- package/dist/src/telemetry/clearcut-logger/clearcut-logger.js.map +1 -1
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.d.ts +4 -1
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.js +9 -0
- package/dist/src/telemetry/clearcut-logger/event-metadata-key.js.map +1 -1
- package/dist/src/telemetry/constants.d.ts +1 -0
- package/dist/src/telemetry/constants.js +1 -0
- package/dist/src/telemetry/constants.js.map +1 -1
- package/dist/src/telemetry/file-exporters.d.ts +28 -0
- package/dist/src/telemetry/file-exporters.js +62 -0
- package/dist/src/telemetry/file-exporters.js.map +1 -0
- package/dist/src/telemetry/integration.test.circular.d.ts +6 -0
- package/dist/src/telemetry/integration.test.circular.js +53 -0
- package/dist/src/telemetry/integration.test.circular.js.map +1 -0
- package/dist/src/telemetry/loggers.d.ts +3 -1
- package/dist/src/telemetry/loggers.js +34 -2
- package/dist/src/telemetry/loggers.js.map +1 -1
- package/dist/src/telemetry/loggers.test.circular.d.ts +6 -0
- package/dist/src/telemetry/loggers.test.circular.js +100 -0
- package/dist/src/telemetry/loggers.test.circular.js.map +1 -0
- package/dist/src/telemetry/sdk.js +17 -6
- package/dist/src/telemetry/sdk.js.map +1 -1
- package/dist/src/telemetry/types.d.ts +19 -1
- package/dist/src/telemetry/types.js +28 -0
- package/dist/src/telemetry/types.js.map +1 -1
- package/dist/src/telemetry/uiTelemetry.d.ts +1 -0
- package/dist/src/telemetry/uiTelemetry.js +7 -0
- package/dist/src/telemetry/uiTelemetry.js.map +1 -1
- package/dist/src/telemetry/uiTelemetry.test.js +92 -0
- package/dist/src/telemetry/uiTelemetry.test.js.map +1 -1
- package/dist/src/tools/edit.d.ts +7 -12
- package/dist/src/tools/edit.js +34 -32
- package/dist/src/tools/edit.js.map +1 -1
- package/dist/src/tools/edit.test.js +12 -0
- package/dist/src/tools/edit.test.js.map +1 -1
- package/dist/src/tools/glob.d.ts +1 -14
- package/dist/src/tools/glob.js +13 -36
- package/dist/src/tools/glob.js.map +1 -1
- package/dist/src/tools/glob.test.js +11 -7
- package/dist/src/tools/glob.test.js.map +1 -1
- package/dist/src/tools/grep.d.ts +3 -6
- package/dist/src/tools/grep.js +12 -18
- package/dist/src/tools/grep.js.map +1 -1
- package/dist/src/tools/grep.test.js +9 -6
- package/dist/src/tools/grep.test.js.map +1 -1
- package/dist/src/tools/ls.d.ts +6 -14
- package/dist/src/tools/ls.js +47 -40
- package/dist/src/tools/ls.js.map +1 -1
- package/dist/src/tools/mcp-client.d.ts +83 -1
- package/dist/src/tools/mcp-client.js +613 -148
- package/dist/src/tools/mcp-client.js.map +1 -1
- package/dist/src/tools/mcp-client.test.js +211 -616
- package/dist/src/tools/mcp-client.test.js.map +1 -1
- package/dist/src/tools/mcp-tool.d.ts +11 -5
- package/dist/src/tools/mcp-tool.js +34 -10
- package/dist/src/tools/mcp-tool.js.map +1 -1
- package/dist/src/tools/mcp-tool.test.js +74 -24
- package/dist/src/tools/mcp-tool.test.js.map +1 -1
- package/dist/src/tools/memoryTool.js +2 -2
- package/dist/src/tools/memoryTool.js.map +1 -1
- package/dist/src/tools/modifiable-tool.test.js +51 -62
- package/dist/src/tools/modifiable-tool.test.js.map +1 -1
- package/dist/src/tools/read-file.d.ts +3 -3
- package/dist/src/tools/read-file.js +10 -10
- package/dist/src/tools/read-file.js.map +1 -1
- package/dist/src/tools/read-file.test.js +100 -70
- package/dist/src/tools/read-file.test.js.map +1 -1
- package/dist/src/tools/read-many-files.d.ts +6 -10
- package/dist/src/tools/read-many-files.js +74 -43
- package/dist/src/tools/read-many-files.js.map +1 -1
- package/dist/src/tools/read-many-files.test.js +7 -3
- package/dist/src/tools/read-many-files.test.js.map +1 -1
- package/dist/src/tools/shell.d.ts +3 -23
- package/dist/src/tools/shell.js +169 -293
- package/dist/src/tools/shell.js.map +1 -1
- package/dist/src/tools/shell.test.js +255 -333
- package/dist/src/tools/shell.test.js.map +1 -1
- package/dist/src/tools/tool-registry.d.ts +13 -2
- package/dist/src/tools/tool-registry.js +57 -10
- package/dist/src/tools/tool-registry.js.map +1 -1
- package/dist/src/tools/tool-registry.test.js +112 -41
- package/dist/src/tools/tool-registry.test.js.map +1 -1
- package/dist/src/tools/tools.d.ts +37 -2
- package/dist/src/tools/tools.js +25 -2
- package/dist/src/tools/tools.js.map +1 -1
- package/dist/src/tools/web-fetch.js +7 -2
- package/dist/src/tools/web-fetch.js.map +1 -1
- package/dist/src/tools/web-fetch.test.js +1 -0
- package/dist/src/tools/web-fetch.test.js.map +1 -1
- package/dist/src/tools/web-search.js +2 -2
- package/dist/src/tools/web-search.js.map +1 -1
- package/dist/src/tools/write-file.d.ts +0 -8
- package/dist/src/tools/write-file.js +14 -23
- package/dist/src/tools/write-file.js.map +1 -1
- package/dist/src/utils/bfsFileSearch.d.ts +2 -0
- package/dist/src/utils/bfsFileSearch.js +4 -1
- package/dist/src/utils/bfsFileSearch.js.map +1 -1
- package/dist/src/utils/bfsFileSearch.test.js +108 -105
- package/dist/src/utils/bfsFileSearch.test.js.map +1 -1
- package/dist/src/utils/browser.d.ts +13 -0
- package/dist/src/utils/browser.js +49 -0
- package/dist/src/utils/browser.js.map +1 -0
- package/dist/src/utils/editCorrector.js +4 -4
- package/dist/src/utils/editCorrector.js.map +1 -1
- package/dist/src/utils/editCorrector.test.js +1 -1
- package/dist/src/utils/editor.js +16 -10
- package/dist/src/utils/editor.js.map +1 -1
- package/dist/src/utils/editor.test.js +128 -28
- package/dist/src/utils/editor.test.js.map +1 -1
- package/dist/src/utils/errorReporting.d.ts +1 -1
- package/dist/src/utils/errorReporting.js +2 -2
- package/dist/src/utils/errorReporting.js.map +1 -1
- package/dist/src/utils/errorReporting.test.js +44 -38
- package/dist/src/utils/errorReporting.test.js.map +1 -1
- package/dist/src/utils/errors.js +4 -4
- package/dist/src/utils/errors.js.map +1 -1
- package/dist/src/utils/fileUtils.d.ts +4 -4
- package/dist/src/utils/fileUtils.js +33 -17
- package/dist/src/utils/fileUtils.js.map +1 -1
- package/dist/src/utils/fileUtils.test.js +37 -37
- package/dist/src/utils/fileUtils.test.js.map +1 -1
- package/dist/src/utils/formatters.d.ts +6 -0
- package/dist/src/utils/formatters.js +16 -0
- package/dist/src/utils/formatters.js.map +1 -0
- package/dist/src/utils/getFolderStructure.d.ts +3 -2
- package/dist/src/utils/getFolderStructure.js +27 -28
- package/dist/src/utils/getFolderStructure.js.map +1 -1
- package/dist/src/utils/getFolderStructure.test.js +169 -187
- package/dist/src/utils/getFolderStructure.test.js.map +1 -1
- package/dist/src/utils/gitIgnoreParser.js +4 -7
- package/dist/src/utils/gitIgnoreParser.js.map +1 -1
- package/dist/src/utils/gitIgnoreParser.test.js +70 -61
- package/dist/src/utils/gitIgnoreParser.test.js.map +1 -1
- package/dist/src/utils/memoryDiscovery.d.ts +2 -1
- package/dist/src/utils/memoryDiscovery.js +11 -5
- package/dist/src/utils/memoryDiscovery.js.map +1 -1
- package/dist/src/utils/memoryDiscovery.test.js +160 -371
- package/dist/src/utils/memoryDiscovery.test.js.map +1 -1
- package/dist/src/utils/partUtils.d.ts +14 -0
- package/dist/src/utils/partUtils.js +65 -0
- package/dist/src/utils/partUtils.js.map +1 -0
- package/dist/src/utils/partUtils.test.d.ts +6 -0
- package/dist/src/utils/partUtils.test.js +130 -0
- package/dist/src/utils/partUtils.test.js.map +1 -0
- package/dist/src/utils/paths.d.ts +11 -0
- package/dist/src/utils/paths.js +17 -1
- package/dist/src/utils/paths.js.map +1 -1
- package/dist/src/utils/quotaErrorDetection.js +2 -11
- package/dist/src/utils/quotaErrorDetection.js.map +1 -1
- package/dist/src/utils/retry.d.ts +6 -0
- package/dist/src/utils/retry.js +2 -2
- package/dist/src/utils/retry.js.map +1 -1
- package/dist/src/utils/safeJsonStringify.d.ts +13 -0
- package/dist/src/utils/safeJsonStringify.js +25 -0
- package/dist/src/utils/safeJsonStringify.js.map +1 -0
- package/dist/src/utils/safeJsonStringify.test.d.ts +6 -0
- package/dist/src/utils/safeJsonStringify.test.js +61 -0
- package/dist/src/utils/safeJsonStringify.test.js.map +1 -0
- package/dist/src/utils/schemaValidator.d.ts +1 -1
- package/dist/src/utils/schemaValidator.js +6 -3
- package/dist/src/utils/schemaValidator.js.map +1 -1
- package/dist/src/utils/shell-utils.d.ts +44 -0
- package/dist/src/utils/shell-utils.js +243 -0
- package/dist/src/utils/shell-utils.js.map +1 -0
- package/dist/src/utils/shell-utils.test.d.ts +6 -0
- package/dist/src/utils/shell-utils.test.js +450 -0
- package/dist/src/utils/shell-utils.test.js.map +1 -0
- package/dist/src/utils/summarizer.d.ts +1 -1
- package/dist/src/utils/summarizer.js +11 -39
- package/dist/src/utils/summarizer.js.map +1 -1
- package/dist/src/utils/summarizer.test.js +1 -1
- package/dist/src/utils/systemEncoding.d.ts +40 -0
- package/dist/src/utils/systemEncoding.js +149 -0
- package/dist/src/utils/systemEncoding.js.map +1 -0
- package/dist/src/utils/systemEncoding.test.d.ts +6 -0
- package/dist/src/utils/systemEncoding.test.js +368 -0
- package/dist/src/utils/systemEncoding.test.js.map +1 -0
- package/dist/src/utils/textUtils.d.ts +13 -0
- package/dist/src/utils/textUtils.js +28 -0
- package/dist/src/utils/textUtils.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +4 -3
- package/dist/google-gemini-cli-core-0.1.11.tgz +0 -0
- package/dist/src/core/geminiRequest.test.js +0 -72
- package/dist/src/core/geminiRequest.test.js.map +0 -1
- /package/dist/src/{core/geminiRequest.test.d.ts → ide/ideContext.test.d.ts} +0 -0
|
@@ -7,10 +7,16 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
|
7
7
|
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
8
8
|
import { SSEClientTransport, } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
9
9
|
import { StreamableHTTPClientTransport, } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
10
|
+
import { ListPromptsResultSchema, GetPromptResultSchema, } from '@modelcontextprotocol/sdk/types.js';
|
|
10
11
|
import { parse } from 'shell-quote';
|
|
12
|
+
import { AuthProviderType } from '../config/config.js';
|
|
13
|
+
import { GoogleCredentialProvider } from '../mcp/google-auth-provider.js';
|
|
11
14
|
import { DiscoveredMCPTool } from './mcp-tool.js';
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
15
|
+
import { mcpToTool } from '@google/genai';
|
|
16
|
+
import { MCPOAuthProvider } from '../mcp/oauth-provider.js';
|
|
17
|
+
import { OAuthUtils } from '../mcp/oauth-utils.js';
|
|
18
|
+
import { MCPOAuthTokenStorage } from '../mcp/oauth-token-storage.js';
|
|
19
|
+
import { getErrorMessage } from '../utils/errors.js';
|
|
14
20
|
export const MCP_DEFAULT_TIMEOUT_MSEC = 10 * 60 * 1000; // default to 10 minutes
|
|
15
21
|
/**
|
|
16
22
|
* Enum representing the connection status of an MCP server
|
|
@@ -39,11 +45,15 @@ export var MCPDiscoveryState;
|
|
|
39
45
|
/**
|
|
40
46
|
* Map to track the status of each MCP server within the core package
|
|
41
47
|
*/
|
|
42
|
-
const
|
|
48
|
+
const serverStatuses = new Map();
|
|
43
49
|
/**
|
|
44
50
|
* Track the overall MCP discovery state
|
|
45
51
|
*/
|
|
46
52
|
let mcpDiscoveryState = MCPDiscoveryState.NOT_STARTED;
|
|
53
|
+
/**
|
|
54
|
+
* Map to track which MCP servers have been discovered to require OAuth
|
|
55
|
+
*/
|
|
56
|
+
export const mcpServerRequiresOAuth = new Map();
|
|
47
57
|
const statusChangeListeners = [];
|
|
48
58
|
/**
|
|
49
59
|
* Add a listener for MCP server status changes
|
|
@@ -64,7 +74,7 @@ export function removeMCPStatusChangeListener(listener) {
|
|
|
64
74
|
* Update the status of an MCP server
|
|
65
75
|
*/
|
|
66
76
|
function updateMCPServerStatus(serverName, status) {
|
|
67
|
-
|
|
77
|
+
serverStatuses.set(serverName, status);
|
|
68
78
|
// Notify all listeners
|
|
69
79
|
for (const listener of statusChangeListeners) {
|
|
70
80
|
listener(serverName, status);
|
|
@@ -74,13 +84,13 @@ function updateMCPServerStatus(serverName, status) {
|
|
|
74
84
|
* Get the current status of an MCP server
|
|
75
85
|
*/
|
|
76
86
|
export function getMCPServerStatus(serverName) {
|
|
77
|
-
return
|
|
87
|
+
return serverStatuses.get(serverName) || MCPServerStatus.DISCONNECTED;
|
|
78
88
|
}
|
|
79
89
|
/**
|
|
80
90
|
* Get all MCP server statuses
|
|
81
91
|
*/
|
|
82
92
|
export function getAllMCPServerStatuses() {
|
|
83
|
-
return new Map(
|
|
93
|
+
return new Map(serverStatuses);
|
|
84
94
|
}
|
|
85
95
|
/**
|
|
86
96
|
* Get the current MCP discovery state
|
|
@@ -88,33 +98,169 @@ export function getAllMCPServerStatuses() {
|
|
|
88
98
|
export function getMCPDiscoveryState() {
|
|
89
99
|
return mcpDiscoveryState;
|
|
90
100
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
101
|
+
/**
|
|
102
|
+
* Parse www-authenticate header to extract OAuth metadata URI.
|
|
103
|
+
*
|
|
104
|
+
* @param wwwAuthenticate The www-authenticate header value
|
|
105
|
+
* @returns The resource metadata URI if found, null otherwise
|
|
106
|
+
*/
|
|
107
|
+
function _parseWWWAuthenticate(wwwAuthenticate) {
|
|
108
|
+
// Parse header like: Bearer realm="MCP Server", resource_metadata_uri="https://..."
|
|
109
|
+
const resourceMetadataMatch = wwwAuthenticate.match(/resource_metadata_uri="([^"]+)"/);
|
|
110
|
+
return resourceMetadataMatch ? resourceMetadataMatch[1] : null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Extract WWW-Authenticate header from error message string.
|
|
114
|
+
* This is a more robust approach than regex matching.
|
|
115
|
+
*
|
|
116
|
+
* @param errorString The error message string
|
|
117
|
+
* @returns The www-authenticate header value if found, null otherwise
|
|
118
|
+
*/
|
|
119
|
+
function extractWWWAuthenticateHeader(errorString) {
|
|
120
|
+
// Try multiple patterns to extract the header
|
|
121
|
+
const patterns = [
|
|
122
|
+
/www-authenticate:\s*([^\n\r]+)/i,
|
|
123
|
+
/WWW-Authenticate:\s*([^\n\r]+)/i,
|
|
124
|
+
/"www-authenticate":\s*"([^"]+)"/i,
|
|
125
|
+
/'www-authenticate':\s*'([^']+)'/i,
|
|
126
|
+
];
|
|
127
|
+
for (const pattern of patterns) {
|
|
128
|
+
const match = errorString.match(pattern);
|
|
129
|
+
if (match) {
|
|
130
|
+
return match[1].trim();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Handle automatic OAuth discovery and authentication for a server.
|
|
137
|
+
*
|
|
138
|
+
* @param mcpServerName The name of the MCP server
|
|
139
|
+
* @param mcpServerConfig The MCP server configuration
|
|
140
|
+
* @param wwwAuthenticate The www-authenticate header value
|
|
141
|
+
* @returns True if OAuth was successfully configured and authenticated, false otherwise
|
|
142
|
+
*/
|
|
143
|
+
async function handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate) {
|
|
94
144
|
try {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
145
|
+
console.log(`🔐 '${mcpServerName}' requires OAuth authentication`);
|
|
146
|
+
// Always try to parse the resource metadata URI from the www-authenticate header
|
|
147
|
+
let oauthConfig;
|
|
148
|
+
const resourceMetadataUri = OAuthUtils.parseWWWAuthenticateHeader(wwwAuthenticate);
|
|
149
|
+
if (resourceMetadataUri) {
|
|
150
|
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(resourceMetadataUri);
|
|
151
|
+
}
|
|
152
|
+
else if (mcpServerConfig.url) {
|
|
153
|
+
// Fallback: try to discover OAuth config from the base URL for SSE
|
|
154
|
+
const sseUrl = new URL(mcpServerConfig.url);
|
|
155
|
+
const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
|
|
156
|
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
|
157
|
+
}
|
|
158
|
+
else if (mcpServerConfig.httpUrl) {
|
|
159
|
+
// Fallback: try to discover OAuth config from the base URL for HTTP
|
|
160
|
+
const httpUrl = new URL(mcpServerConfig.httpUrl);
|
|
161
|
+
const baseUrl = `${httpUrl.protocol}//${httpUrl.host}`;
|
|
162
|
+
oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
|
163
|
+
}
|
|
164
|
+
if (!oauthConfig) {
|
|
165
|
+
console.error(`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
// OAuth configuration discovered - proceed with authentication
|
|
169
|
+
// Create OAuth configuration for authentication
|
|
170
|
+
const oauthAuthConfig = {
|
|
171
|
+
enabled: true,
|
|
172
|
+
authorizationUrl: oauthConfig.authorizationUrl,
|
|
173
|
+
tokenUrl: oauthConfig.tokenUrl,
|
|
174
|
+
scopes: oauthConfig.scopes || [],
|
|
175
|
+
};
|
|
176
|
+
// Perform OAuth authentication
|
|
177
|
+
console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
|
|
178
|
+
await MCPOAuthProvider.authenticate(mcpServerName, oauthAuthConfig);
|
|
179
|
+
console.log(`OAuth authentication successful for server '${mcpServerName}'`);
|
|
180
|
+
return true;
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
console.error(`Failed to handle automatic OAuth for server '${mcpServerName}': ${getErrorMessage(error)}`);
|
|
184
|
+
return false;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Create a transport with OAuth token for the given server configuration.
|
|
189
|
+
*
|
|
190
|
+
* @param mcpServerName The name of the MCP server
|
|
191
|
+
* @param mcpServerConfig The MCP server configuration
|
|
192
|
+
* @param accessToken The OAuth access token
|
|
193
|
+
* @returns The transport with OAuth token, or null if creation fails
|
|
194
|
+
*/
|
|
195
|
+
async function createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken) {
|
|
196
|
+
try {
|
|
197
|
+
if (mcpServerConfig.httpUrl) {
|
|
198
|
+
// Create HTTP transport with OAuth token
|
|
199
|
+
const oauthTransportOptions = {
|
|
200
|
+
requestInit: {
|
|
201
|
+
headers: {
|
|
202
|
+
...mcpServerConfig.headers,
|
|
203
|
+
Authorization: `Bearer ${accessToken}`,
|
|
204
|
+
},
|
|
205
|
+
},
|
|
105
206
|
};
|
|
207
|
+
return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), oauthTransportOptions);
|
|
106
208
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
209
|
+
else if (mcpServerConfig.url) {
|
|
210
|
+
// Create SSE transport with OAuth token in Authorization header
|
|
211
|
+
return new SSEClientTransport(new URL(mcpServerConfig.url), {
|
|
212
|
+
requestInit: {
|
|
213
|
+
headers: {
|
|
214
|
+
...mcpServerConfig.headers,
|
|
215
|
+
Authorization: `Bearer ${accessToken}`,
|
|
216
|
+
},
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
return null;
|
|
111
221
|
}
|
|
112
222
|
catch (error) {
|
|
113
|
-
|
|
223
|
+
console.error(`Failed to create OAuth transport for server '${mcpServerName}': ${getErrorMessage(error)}`);
|
|
224
|
+
return null;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Discovers tools from all configured MCP servers and registers them with the tool registry.
|
|
229
|
+
* It orchestrates the connection and discovery process for each server defined in the
|
|
230
|
+
* configuration, as well as any server specified via a command-line argument.
|
|
231
|
+
*
|
|
232
|
+
* @param mcpServers A record of named MCP server configurations.
|
|
233
|
+
* @param mcpServerCommand An optional command string for a dynamically specified MCP server.
|
|
234
|
+
* @param toolRegistry The central registry where discovered tools will be registered.
|
|
235
|
+
* @returns A promise that resolves when the discovery process has been attempted for all servers.
|
|
236
|
+
*/
|
|
237
|
+
export async function discoverMcpTools(mcpServers, mcpServerCommand, toolRegistry, promptRegistry, debugMode) {
|
|
238
|
+
mcpDiscoveryState = MCPDiscoveryState.IN_PROGRESS;
|
|
239
|
+
try {
|
|
240
|
+
mcpServers = populateMcpServerCommand(mcpServers, mcpServerCommand);
|
|
241
|
+
const discoveryPromises = Object.entries(mcpServers).map(([mcpServerName, mcpServerConfig]) => connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode));
|
|
242
|
+
await Promise.all(discoveryPromises);
|
|
243
|
+
}
|
|
244
|
+
finally {
|
|
114
245
|
mcpDiscoveryState = MCPDiscoveryState.COMPLETED;
|
|
115
|
-
throw error;
|
|
116
246
|
}
|
|
117
247
|
}
|
|
248
|
+
/** Visible for Testing */
|
|
249
|
+
export function populateMcpServerCommand(mcpServers, mcpServerCommand) {
|
|
250
|
+
if (mcpServerCommand) {
|
|
251
|
+
const cmd = mcpServerCommand;
|
|
252
|
+
const args = parse(cmd, process.env);
|
|
253
|
+
if (args.some((arg) => typeof arg !== 'string')) {
|
|
254
|
+
throw new Error('failed to parse mcpServerCommand: ' + cmd);
|
|
255
|
+
}
|
|
256
|
+
// use generic server name 'mcp'
|
|
257
|
+
mcpServers['mcp'] = {
|
|
258
|
+
command: args[0],
|
|
259
|
+
args: args.slice(1),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
return mcpServers;
|
|
263
|
+
}
|
|
118
264
|
/**
|
|
119
265
|
* Connects to an MCP server and discovers available tools, registering them with the tool registry.
|
|
120
266
|
* This function handles the complete lifecycle of connecting to a server, discovering tools,
|
|
@@ -125,46 +271,129 @@ export async function discoverMcpTools(mcpServers, mcpServerCommand, toolRegistr
|
|
|
125
271
|
* @param toolRegistry The registry to register discovered tools with
|
|
126
272
|
* @returns Promise that resolves when discovery is complete
|
|
127
273
|
*/
|
|
128
|
-
async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry) {
|
|
129
|
-
// Initialize the server status as connecting
|
|
274
|
+
export async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry, promptRegistry, debugMode) {
|
|
130
275
|
updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTING);
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
276
|
+
try {
|
|
277
|
+
const mcpClient = await connectToMcpServer(mcpServerName, mcpServerConfig, debugMode);
|
|
278
|
+
try {
|
|
279
|
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.CONNECTED);
|
|
280
|
+
mcpClient.onerror = (error) => {
|
|
281
|
+
console.error(`MCP ERROR (${mcpServerName}):`, error.toString());
|
|
282
|
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
|
|
137
283
|
};
|
|
284
|
+
await discoverPrompts(mcpServerName, mcpClient, promptRegistry);
|
|
285
|
+
const tools = await discoverTools(mcpServerName, mcpServerConfig, mcpClient);
|
|
286
|
+
for (const tool of tools) {
|
|
287
|
+
toolRegistry.registerTool(tool);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
catch (error) {
|
|
291
|
+
mcpClient.close();
|
|
292
|
+
throw error;
|
|
138
293
|
}
|
|
139
|
-
transport = new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
|
|
140
294
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
295
|
+
catch (error) {
|
|
296
|
+
console.error(`Error connecting to MCP server '${mcpServerName}': ${getErrorMessage(error)}`);
|
|
297
|
+
updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* Discovers and sanitizes tools from a connected MCP client.
|
|
302
|
+
* It retrieves function declarations from the client, filters out disabled tools,
|
|
303
|
+
* generates valid names for them, and wraps them in `DiscoveredMCPTool` instances.
|
|
304
|
+
*
|
|
305
|
+
* @param mcpServerName The name of the MCP server.
|
|
306
|
+
* @param mcpServerConfig The configuration for the MCP server.
|
|
307
|
+
* @param mcpClient The active MCP client instance.
|
|
308
|
+
* @returns A promise that resolves to an array of discovered and enabled tools.
|
|
309
|
+
* @throws An error if no enabled tools are found or if the server provides invalid function declarations.
|
|
310
|
+
*/
|
|
311
|
+
export async function discoverTools(mcpServerName, mcpServerConfig, mcpClient) {
|
|
312
|
+
try {
|
|
313
|
+
const mcpCallableTool = mcpToTool(mcpClient);
|
|
314
|
+
const tool = await mcpCallableTool.tool();
|
|
315
|
+
if (!Array.isArray(tool.functionDeclarations)) {
|
|
316
|
+
throw new Error(`Server did not return valid function declarations.`);
|
|
147
317
|
}
|
|
148
|
-
|
|
318
|
+
const discoveredTools = [];
|
|
319
|
+
for (const funcDecl of tool.functionDeclarations) {
|
|
320
|
+
if (!isEnabled(funcDecl, mcpServerName, mcpServerConfig)) {
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
discoveredTools.push(new DiscoveredMCPTool(mcpCallableTool, mcpServerName, funcDecl.name, funcDecl.description ?? '', funcDecl.parametersJsonSchema ?? { type: 'object', properties: {} }, mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC, mcpServerConfig.trust));
|
|
324
|
+
}
|
|
325
|
+
return discoveredTools;
|
|
149
326
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
327
|
+
catch (error) {
|
|
328
|
+
throw new Error(`Error discovering tools: ${error}`);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Discovers and logs prompts from a connected MCP client.
|
|
333
|
+
* It retrieves prompt declarations from the client and logs their names.
|
|
334
|
+
*
|
|
335
|
+
* @param mcpServerName The name of the MCP server.
|
|
336
|
+
* @param mcpClient The active MCP client instance.
|
|
337
|
+
*/
|
|
338
|
+
export async function discoverPrompts(mcpServerName, mcpClient, promptRegistry) {
|
|
339
|
+
try {
|
|
340
|
+
const response = await mcpClient.request({ method: 'prompts/list', params: {} }, ListPromptsResultSchema);
|
|
341
|
+
for (const prompt of response.prompts) {
|
|
342
|
+
promptRegistry.registerPrompt({
|
|
343
|
+
...prompt,
|
|
344
|
+
serverName: mcpServerName,
|
|
345
|
+
invoke: (params) => invokeMcpPrompt(mcpServerName, mcpClient, prompt.name, params),
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
catch (error) {
|
|
350
|
+
// It's okay if this fails, not all servers will have prompts.
|
|
351
|
+
// Don't log an error if the method is not found, which is a common case.
|
|
352
|
+
if (error instanceof Error &&
|
|
353
|
+
!error.message?.includes('Method not found')) {
|
|
354
|
+
console.error(`Error discovering prompts from ${mcpServerName}: ${getErrorMessage(error)}`);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Invokes a prompt on a connected MCP client.
|
|
360
|
+
*
|
|
361
|
+
* @param mcpServerName The name of the MCP server.
|
|
362
|
+
* @param mcpClient The active MCP client instance.
|
|
363
|
+
* @param promptName The name of the prompt to invoke.
|
|
364
|
+
* @param promptParams The parameters to pass to the prompt.
|
|
365
|
+
* @returns A promise that resolves to the result of the prompt invocation.
|
|
366
|
+
*/
|
|
367
|
+
export async function invokeMcpPrompt(mcpServerName, mcpClient, promptName, promptParams) {
|
|
368
|
+
try {
|
|
369
|
+
const response = await mcpClient.request({
|
|
370
|
+
method: 'prompts/get',
|
|
371
|
+
params: {
|
|
372
|
+
name: promptName,
|
|
373
|
+
arguments: promptParams,
|
|
157
374
|
},
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
});
|
|
375
|
+
}, GetPromptResultSchema);
|
|
376
|
+
return response;
|
|
161
377
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
378
|
+
catch (error) {
|
|
379
|
+
if (error instanceof Error &&
|
|
380
|
+
!error.message?.includes('Method not found')) {
|
|
381
|
+
console.error(`Error invoking prompt '${promptName}' from ${mcpServerName} ${promptParams}: ${getErrorMessage(error)}`);
|
|
382
|
+
}
|
|
383
|
+
throw error;
|
|
167
384
|
}
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* Creates and connects an MCP client to a server based on the provided configuration.
|
|
388
|
+
* It determines the appropriate transport (Stdio, SSE, or Streamable HTTP) and
|
|
389
|
+
* establishes a connection. It also applies a patch to handle request timeouts.
|
|
390
|
+
*
|
|
391
|
+
* @param mcpServerName The name of the MCP server, used for logging and identification.
|
|
392
|
+
* @param mcpServerConfig The configuration specifying how to connect to the server.
|
|
393
|
+
* @returns A promise that resolves to a connected MCP `Client` instance.
|
|
394
|
+
* @throws An error if the connection fails or the configuration is invalid.
|
|
395
|
+
*/
|
|
396
|
+
export async function connectToMcpServer(mcpServerName, mcpServerConfig, debugMode) {
|
|
168
397
|
const mcpClient = new Client({
|
|
169
398
|
name: 'gemini-cli-mcp-client',
|
|
170
399
|
version: '0.0.1',
|
|
@@ -181,114 +410,350 @@ async function connectAndDiscover(mcpServerName, mcpServerConfig, toolRegistry)
|
|
|
181
410
|
};
|
|
182
411
|
}
|
|
183
412
|
try {
|
|
184
|
-
await
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
url: mcpServerConfig.url,
|
|
195
|
-
httpUrl: mcpServerConfig.httpUrl,
|
|
196
|
-
cwd: mcpServerConfig.cwd,
|
|
197
|
-
timeout: mcpServerConfig.timeout,
|
|
198
|
-
trust: mcpServerConfig.trust,
|
|
199
|
-
// Exclude args, env, and headers which may contain sensitive data
|
|
200
|
-
};
|
|
201
|
-
let errorString = `failed to start or connect to MCP server '${mcpServerName}' ` +
|
|
202
|
-
`${JSON.stringify(safeConfig)}; \n${error}`;
|
|
203
|
-
if (process.env.SANDBOX) {
|
|
204
|
-
errorString += `\nMake sure it is available in the sandbox`;
|
|
413
|
+
const transport = await createTransport(mcpServerName, mcpServerConfig, debugMode);
|
|
414
|
+
try {
|
|
415
|
+
await mcpClient.connect(transport, {
|
|
416
|
+
timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
|
417
|
+
});
|
|
418
|
+
return mcpClient;
|
|
419
|
+
}
|
|
420
|
+
catch (error) {
|
|
421
|
+
await transport.close();
|
|
422
|
+
throw error;
|
|
205
423
|
}
|
|
206
|
-
console.error(errorString);
|
|
207
|
-
// Update status to disconnected
|
|
208
|
-
updateMCPServerStatus(mcpServerName, MCPServerStatus.DISCONNECTED);
|
|
209
|
-
return;
|
|
210
424
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
425
|
+
catch (error) {
|
|
426
|
+
// Check if this is a 401 error that might indicate OAuth is required
|
|
427
|
+
const errorString = String(error);
|
|
428
|
+
if (errorString.includes('401') &&
|
|
429
|
+
(mcpServerConfig.httpUrl || mcpServerConfig.url)) {
|
|
430
|
+
mcpServerRequiresOAuth.set(mcpServerName, true);
|
|
431
|
+
// Only trigger automatic OAuth discovery for HTTP servers or when OAuth is explicitly configured
|
|
432
|
+
// For SSE servers, we should not trigger new OAuth flows automatically
|
|
433
|
+
const shouldTriggerOAuth = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
|
|
434
|
+
if (!shouldTriggerOAuth) {
|
|
435
|
+
// For SSE servers without explicit OAuth config, if a token was found but rejected, report it accurately.
|
|
436
|
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
|
437
|
+
if (credentials) {
|
|
438
|
+
const hasStoredTokens = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
|
439
|
+
// Pass client ID if available
|
|
440
|
+
clientId: credentials.clientId,
|
|
441
|
+
});
|
|
442
|
+
if (hasStoredTokens) {
|
|
443
|
+
console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
|
|
444
|
+
`Please re-authenticate using: /mcp auth ${mcpServerName}`);
|
|
445
|
+
}
|
|
446
|
+
else {
|
|
447
|
+
console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
|
448
|
+
`Please authenticate using: /mcp auth ${mcpServerName}`);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
|
452
|
+
`Please authenticate using: /mcp auth ${mcpServerName}`);
|
|
225
453
|
}
|
|
226
|
-
//
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
454
|
+
// Try to extract www-authenticate header from the error
|
|
455
|
+
let wwwAuthenticate = extractWWWAuthenticateHeader(errorString);
|
|
456
|
+
// If we didn't get the header from the error string, try to get it from the server
|
|
457
|
+
if (!wwwAuthenticate && mcpServerConfig.url) {
|
|
458
|
+
console.log(`No www-authenticate header in error, trying to fetch it from server...`);
|
|
459
|
+
try {
|
|
460
|
+
const response = await fetch(mcpServerConfig.url, {
|
|
461
|
+
method: 'HEAD',
|
|
462
|
+
headers: {
|
|
463
|
+
Accept: 'text/event-stream',
|
|
464
|
+
},
|
|
465
|
+
signal: AbortSignal.timeout(5000),
|
|
466
|
+
});
|
|
467
|
+
if (response.status === 401) {
|
|
468
|
+
wwwAuthenticate = response.headers.get('www-authenticate');
|
|
469
|
+
if (wwwAuthenticate) {
|
|
470
|
+
console.log(`Found www-authenticate header from server: ${wwwAuthenticate}`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
catch (fetchError) {
|
|
475
|
+
console.debug(`Failed to fetch www-authenticate header: ${getErrorMessage(fetchError)}`);
|
|
476
|
+
}
|
|
234
477
|
}
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
478
|
+
if (wwwAuthenticate) {
|
|
479
|
+
console.log(`Received 401 with www-authenticate header: ${wwwAuthenticate}`);
|
|
480
|
+
// Try automatic OAuth discovery and authentication
|
|
481
|
+
const oauthSuccess = await handleAutomaticOAuth(mcpServerName, mcpServerConfig, wwwAuthenticate);
|
|
482
|
+
if (oauthSuccess) {
|
|
483
|
+
// Retry connection with OAuth token
|
|
484
|
+
console.log(`Retrying connection to '${mcpServerName}' with OAuth token...`);
|
|
485
|
+
// Get the valid token - we need to create a proper OAuth config
|
|
486
|
+
// The token should already be available from the authentication process
|
|
487
|
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
|
488
|
+
if (credentials) {
|
|
489
|
+
const accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
|
490
|
+
// Pass client ID if available
|
|
491
|
+
clientId: credentials.clientId,
|
|
492
|
+
});
|
|
493
|
+
if (accessToken) {
|
|
494
|
+
// Create transport with OAuth token
|
|
495
|
+
const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
|
|
496
|
+
if (oauthTransport) {
|
|
497
|
+
try {
|
|
498
|
+
await mcpClient.connect(oauthTransport, {
|
|
499
|
+
timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
|
500
|
+
});
|
|
501
|
+
// Connection successful with OAuth
|
|
502
|
+
return mcpClient;
|
|
503
|
+
}
|
|
504
|
+
catch (retryError) {
|
|
505
|
+
console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
|
|
506
|
+
throw retryError;
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else {
|
|
510
|
+
console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
|
|
511
|
+
throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
else {
|
|
515
|
+
console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
|
|
516
|
+
throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
else {
|
|
520
|
+
console.error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
|
|
521
|
+
throw new Error(`Failed to get credentials for server '${mcpServerName}' after successful OAuth authentication`);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
console.error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
|
|
526
|
+
throw new Error(`Failed to handle automatic OAuth for server '${mcpServerName}'`);
|
|
527
|
+
}
|
|
240
528
|
}
|
|
241
529
|
else {
|
|
242
|
-
|
|
530
|
+
// No www-authenticate header found, but we got a 401
|
|
531
|
+
// Only try OAuth discovery for HTTP servers or when OAuth is explicitly configured
|
|
532
|
+
// For SSE servers, we should not trigger new OAuth flows automatically
|
|
533
|
+
const shouldTryDiscovery = mcpServerConfig.httpUrl || mcpServerConfig.oauth?.enabled;
|
|
534
|
+
if (!shouldTryDiscovery) {
|
|
535
|
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
|
536
|
+
if (credentials) {
|
|
537
|
+
const hasStoredTokens = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
|
538
|
+
// Pass client ID if available
|
|
539
|
+
clientId: credentials.clientId,
|
|
540
|
+
});
|
|
541
|
+
if (hasStoredTokens) {
|
|
542
|
+
console.log(`Stored OAuth token for SSE server '${mcpServerName}' was rejected. ` +
|
|
543
|
+
`Please re-authenticate using: /mcp auth ${mcpServerName}`);
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
console.log(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
|
547
|
+
`Please authenticate using: /mcp auth ${mcpServerName}`);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
throw new Error(`401 error received for SSE server '${mcpServerName}' without OAuth configuration. ` +
|
|
551
|
+
`Please authenticate using: /mcp auth ${mcpServerName}`);
|
|
552
|
+
}
|
|
553
|
+
// For SSE servers, try to discover OAuth configuration from the base URL
|
|
554
|
+
console.log(`🔍 Attempting OAuth discovery for '${mcpServerName}'...`);
|
|
555
|
+
if (mcpServerConfig.url) {
|
|
556
|
+
const sseUrl = new URL(mcpServerConfig.url);
|
|
557
|
+
const baseUrl = `${sseUrl.protocol}//${sseUrl.host}`;
|
|
558
|
+
try {
|
|
559
|
+
// Try to discover OAuth configuration from the base URL
|
|
560
|
+
const oauthConfig = await OAuthUtils.discoverOAuthConfig(baseUrl);
|
|
561
|
+
if (oauthConfig) {
|
|
562
|
+
console.log(`Discovered OAuth configuration from base URL for server '${mcpServerName}'`);
|
|
563
|
+
// Create OAuth configuration for authentication
|
|
564
|
+
const oauthAuthConfig = {
|
|
565
|
+
enabled: true,
|
|
566
|
+
authorizationUrl: oauthConfig.authorizationUrl,
|
|
567
|
+
tokenUrl: oauthConfig.tokenUrl,
|
|
568
|
+
scopes: oauthConfig.scopes || [],
|
|
569
|
+
};
|
|
570
|
+
// Perform OAuth authentication
|
|
571
|
+
console.log(`Starting OAuth authentication for server '${mcpServerName}'...`);
|
|
572
|
+
await MCPOAuthProvider.authenticate(mcpServerName, oauthAuthConfig);
|
|
573
|
+
// Retry connection with OAuth token
|
|
574
|
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
|
575
|
+
if (credentials) {
|
|
576
|
+
const accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
|
577
|
+
// Pass client ID if available
|
|
578
|
+
clientId: credentials.clientId,
|
|
579
|
+
});
|
|
580
|
+
if (accessToken) {
|
|
581
|
+
// Create transport with OAuth token
|
|
582
|
+
const oauthTransport = await createTransportWithOAuth(mcpServerName, mcpServerConfig, accessToken);
|
|
583
|
+
if (oauthTransport) {
|
|
584
|
+
try {
|
|
585
|
+
await mcpClient.connect(oauthTransport, {
|
|
586
|
+
timeout: mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC,
|
|
587
|
+
});
|
|
588
|
+
// Connection successful with OAuth
|
|
589
|
+
return mcpClient;
|
|
590
|
+
}
|
|
591
|
+
catch (retryError) {
|
|
592
|
+
console.error(`Failed to connect with OAuth token: ${getErrorMessage(retryError)}`);
|
|
593
|
+
throw retryError;
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
else {
|
|
597
|
+
console.error(`Failed to create OAuth transport for server '${mcpServerName}'`);
|
|
598
|
+
throw new Error(`Failed to create OAuth transport for server '${mcpServerName}'`);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
else {
|
|
602
|
+
console.error(`Failed to get OAuth token for server '${mcpServerName}'`);
|
|
603
|
+
throw new Error(`Failed to get OAuth token for server '${mcpServerName}'`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
else {
|
|
607
|
+
console.error(`Failed to get stored credentials for server '${mcpServerName}'`);
|
|
608
|
+
throw new Error(`Failed to get stored credentials for server '${mcpServerName}'`);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
else {
|
|
612
|
+
console.error(`❌ Could not configure OAuth for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
|
|
613
|
+
throw new Error(`OAuth configuration failed for '${mcpServerName}'. Please authenticate manually with /mcp auth ${mcpServerName}`);
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
catch (discoveryError) {
|
|
617
|
+
console.error(`❌ OAuth discovery failed for '${mcpServerName}' - please authenticate manually with /mcp auth ${mcpServerName}`);
|
|
618
|
+
throw discoveryError;
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
else {
|
|
622
|
+
console.error(`❌ '${mcpServerName}' requires authentication but no OAuth configuration found`);
|
|
623
|
+
throw new Error(`MCP server '${mcpServerName}' requires authentication. Please configure OAuth or check server settings.`);
|
|
624
|
+
}
|
|
243
625
|
}
|
|
244
|
-
|
|
245
|
-
|
|
626
|
+
}
|
|
627
|
+
else {
|
|
628
|
+
// Handle other connection errors
|
|
629
|
+
// Create a concise error message
|
|
630
|
+
const errorMessage = error.message || String(error);
|
|
631
|
+
const isNetworkError = errorMessage.includes('ENOTFOUND') ||
|
|
632
|
+
errorMessage.includes('ECONNREFUSED');
|
|
633
|
+
let conciseError;
|
|
634
|
+
if (isNetworkError) {
|
|
635
|
+
conciseError = `Cannot connect to '${mcpServerName}' - server may be down or URL incorrect`;
|
|
246
636
|
}
|
|
247
|
-
|
|
248
|
-
|
|
637
|
+
else {
|
|
638
|
+
conciseError = `Connection failed for '${mcpServerName}': ${errorMessage}`;
|
|
249
639
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
toolNameForModel = toolNameForModel.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
253
|
-
const existingTool = toolRegistry.getTool(toolNameForModel);
|
|
254
|
-
if (existingTool) {
|
|
255
|
-
toolNameForModel = mcpServerName + '__' + toolNameForModel;
|
|
640
|
+
if (process.env.SANDBOX) {
|
|
641
|
+
conciseError += ` (check sandbox availability)`;
|
|
256
642
|
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
643
|
+
throw new Error(conciseError);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
/** Visible for Testing */
|
|
648
|
+
export async function createTransport(mcpServerName, mcpServerConfig, debugMode) {
|
|
649
|
+
if (mcpServerConfig.authProviderType === AuthProviderType.GOOGLE_CREDENTIALS) {
|
|
650
|
+
const provider = new GoogleCredentialProvider(mcpServerConfig);
|
|
651
|
+
const transportOptions = {
|
|
652
|
+
authProvider: provider,
|
|
653
|
+
};
|
|
654
|
+
if (mcpServerConfig.httpUrl) {
|
|
655
|
+
return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
|
|
656
|
+
}
|
|
657
|
+
else if (mcpServerConfig.url) {
|
|
658
|
+
return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
|
|
659
|
+
}
|
|
660
|
+
throw new Error('No URL configured for Google Credentials MCP server');
|
|
661
|
+
}
|
|
662
|
+
// Check if we have OAuth configuration or stored tokens
|
|
663
|
+
let accessToken = null;
|
|
664
|
+
let hasOAuthConfig = mcpServerConfig.oauth?.enabled;
|
|
665
|
+
if (hasOAuthConfig && mcpServerConfig.oauth) {
|
|
666
|
+
accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, mcpServerConfig.oauth);
|
|
667
|
+
if (!accessToken) {
|
|
668
|
+
console.error(`MCP server '${mcpServerName}' requires OAuth authentication. ` +
|
|
669
|
+
`Please authenticate using the /mcp auth command.`);
|
|
670
|
+
throw new Error(`MCP server '${mcpServerName}' requires OAuth authentication. ` +
|
|
671
|
+
`Please authenticate using the /mcp auth command.`);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
else {
|
|
675
|
+
// Check if we have stored OAuth tokens for this server (from previous authentication)
|
|
676
|
+
const credentials = await MCPOAuthTokenStorage.getToken(mcpServerName);
|
|
677
|
+
if (credentials) {
|
|
678
|
+
accessToken = await MCPOAuthProvider.getValidToken(mcpServerName, {
|
|
679
|
+
// Pass client ID if available
|
|
680
|
+
clientId: credentials.clientId,
|
|
681
|
+
});
|
|
682
|
+
if (accessToken) {
|
|
683
|
+
hasOAuthConfig = true;
|
|
684
|
+
console.log(`Found stored OAuth token for server '${mcpServerName}'`);
|
|
262
685
|
}
|
|
263
|
-
sanitizeParameters(funcDecl.parameters);
|
|
264
|
-
toolRegistry.registerTool(new DiscoveredMCPTool(mcpCallableTool, mcpServerName, toolNameForModel, funcDecl.description ?? '', funcDecl.parameters ?? { type: Type.OBJECT, properties: {} }, funcDecl.name, mcpServerConfig.timeout ?? MCP_DEFAULT_TIMEOUT_MSEC, mcpServerConfig.trust));
|
|
265
686
|
}
|
|
266
687
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
//
|
|
270
|
-
if (
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
688
|
+
if (mcpServerConfig.httpUrl) {
|
|
689
|
+
const transportOptions = {};
|
|
690
|
+
// Set up headers with OAuth token if available
|
|
691
|
+
if (hasOAuthConfig && accessToken) {
|
|
692
|
+
transportOptions.requestInit = {
|
|
693
|
+
headers: {
|
|
694
|
+
...mcpServerConfig.headers,
|
|
695
|
+
Authorization: `Bearer ${accessToken}`,
|
|
696
|
+
},
|
|
697
|
+
};
|
|
274
698
|
}
|
|
275
|
-
|
|
276
|
-
|
|
699
|
+
else if (mcpServerConfig.headers) {
|
|
700
|
+
transportOptions.requestInit = {
|
|
701
|
+
headers: mcpServerConfig.headers,
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
return new StreamableHTTPClientTransport(new URL(mcpServerConfig.httpUrl), transportOptions);
|
|
277
705
|
}
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
706
|
+
if (mcpServerConfig.url) {
|
|
707
|
+
const transportOptions = {};
|
|
708
|
+
// Set up headers with OAuth token if available
|
|
709
|
+
if (hasOAuthConfig && accessToken) {
|
|
710
|
+
transportOptions.requestInit = {
|
|
711
|
+
headers: {
|
|
712
|
+
...mcpServerConfig.headers,
|
|
713
|
+
Authorization: `Bearer ${accessToken}`,
|
|
714
|
+
},
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
else if (mcpServerConfig.headers) {
|
|
718
|
+
transportOptions.requestInit = {
|
|
719
|
+
headers: mcpServerConfig.headers,
|
|
720
|
+
};
|
|
291
721
|
}
|
|
722
|
+
return new SSEClientTransport(new URL(mcpServerConfig.url), transportOptions);
|
|
723
|
+
}
|
|
724
|
+
if (mcpServerConfig.command) {
|
|
725
|
+
const transport = new StdioClientTransport({
|
|
726
|
+
command: mcpServerConfig.command,
|
|
727
|
+
args: mcpServerConfig.args || [],
|
|
728
|
+
env: {
|
|
729
|
+
...process.env,
|
|
730
|
+
...(mcpServerConfig.env || {}),
|
|
731
|
+
},
|
|
732
|
+
cwd: mcpServerConfig.cwd,
|
|
733
|
+
stderr: 'pipe',
|
|
734
|
+
});
|
|
735
|
+
if (debugMode) {
|
|
736
|
+
transport.stderr.on('data', (data) => {
|
|
737
|
+
const stderrStr = data.toString().trim();
|
|
738
|
+
console.debug(`[DEBUG] [MCP STDERR (${mcpServerName})]: `, stderrStr);
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
return transport;
|
|
742
|
+
}
|
|
743
|
+
throw new Error(`Invalid configuration: missing httpUrl (for Streamable HTTP), url (for SSE), and command (for stdio).`);
|
|
744
|
+
}
|
|
745
|
+
/** Visible for testing */
|
|
746
|
+
export function isEnabled(funcDecl, mcpServerName, mcpServerConfig) {
|
|
747
|
+
if (!funcDecl.name) {
|
|
748
|
+
console.warn(`Discovered a function declaration without a name from MCP server '${mcpServerName}'. Skipping.`);
|
|
749
|
+
return false;
|
|
750
|
+
}
|
|
751
|
+
const { includeTools, excludeTools } = mcpServerConfig;
|
|
752
|
+
// excludeTools takes precedence over includeTools
|
|
753
|
+
if (excludeTools && excludeTools.includes(funcDecl.name)) {
|
|
754
|
+
return false;
|
|
292
755
|
}
|
|
756
|
+
return (!includeTools ||
|
|
757
|
+
includeTools.some((tool) => tool === funcDecl.name || tool.startsWith(`${funcDecl.name}(`)));
|
|
293
758
|
}
|
|
294
759
|
//# sourceMappingURL=mcp-client.js.map
|