fix: linting etc.
This commit is contained in:
parent
6f6c952430
commit
739c04681c
18 changed files with 129 additions and 206 deletions
|
|
@ -1,7 +1,6 @@
|
|||
import { vi } from "vitest";
|
||||
import type { AuthConfig } from "../../auth/workos.js";
|
||||
|
||||
export const isAuthenticated = vi.fn(() => false);
|
||||
export const isAuthenticated = vi.fn(() => Promise.resolve(false));
|
||||
export const isAuthenticatedConfig = vi.fn(() => false);
|
||||
export const isEnvironmentAuthConfig = vi.fn(() => false);
|
||||
export const loadAuthConfig = vi.fn(() => null);
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
autoSelectOrganizationAndConfig,
|
||||
createUpdatedAuthConfig,
|
||||
} from "./orgSelection.js";
|
||||
import type { AuthenticatedConfig } from "./workos.js";
|
||||
import { AuthenticatedConfig } from "./workos-types.js";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("fs");
|
||||
|
|
|
|||
|
|
@ -3,10 +3,11 @@ import * as path from "path";
|
|||
|
||||
import chalk from "chalk";
|
||||
|
||||
import type { AuthConfig, AuthenticatedConfig } from "../auth/workos.js";
|
||||
import type { AuthConfig } from "../auth/workos.js";
|
||||
import { saveAuthConfig } from "../auth/workos.js";
|
||||
import { getApiClient } from "../config.js";
|
||||
import { env } from "../env.js";
|
||||
import { AuthenticatedConfig } from "./workos-types.js";
|
||||
|
||||
/**
|
||||
* Creates an updated AuthenticatedConfig with a new organization ID and optional config URI
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
import chalk from "chalk";
|
||||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { getApiClient } from "../config.js";
|
||||
|
||||
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
|
||||
import { ensureOrganization } from "./workos.js";
|
||||
import type { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos.js";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("../config.js", () => ({
|
||||
|
|
|
|||
38
extensions/cli/src/auth/workos-types.ts
Normal file
38
extensions/cli/src/auth/workos-types.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
/**
|
||||
* Device authorization response from WorkOS
|
||||
*/
|
||||
export interface DeviceAuthorizationResponse {
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete: string;
|
||||
expires_in: number;
|
||||
interval: number;
|
||||
}
|
||||
|
||||
// Represents an authenticated user's configuration
|
||||
export interface AuthenticatedConfig {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
|
||||
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
|
||||
modelName?: string; // Name of the selected model
|
||||
}
|
||||
|
||||
// Represents configuration when using environment variable auth
|
||||
export interface EnvironmentAuthConfig {
|
||||
/**
|
||||
* This userId?: undefined; field a trick to help TypeScript differentiate between
|
||||
* AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
|
||||
* a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
|
||||
* type guards are involved.
|
||||
*/
|
||||
userId?: undefined;
|
||||
accessToken: string;
|
||||
organizationId: string | null; // Can be set via --org flag in headless mode
|
||||
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
|
||||
modelName?: string; // Name of the selected model
|
||||
}
|
||||
|
|
@ -4,11 +4,8 @@ import { getApiClient } from "../config.js";
|
|||
import { safeStderr } from "../init.js";
|
||||
import { gracefulExit } from "../util/exit.js";
|
||||
|
||||
import type {
|
||||
AuthConfig,
|
||||
AuthenticatedConfig,
|
||||
EnvironmentAuthConfig,
|
||||
} from "./workos.js";
|
||||
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
|
||||
import type { AuthConfig } from "./workos.js";
|
||||
import { saveAuthConfig } from "./workos.js";
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import { slugToUri } from "./uriUtils.js";
|
||||
import { AuthenticatedConfig, EnvironmentAuthConfig } from "./workos-types.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
EnvironmentAuthConfig,
|
||||
getAccessToken,
|
||||
getAssistantSlug,
|
||||
getOrganizationId,
|
||||
|
|
|
|||
|
|
@ -3,13 +3,15 @@ import * as os from "os";
|
|||
import * as path from "path";
|
||||
|
||||
import chalk from "chalk";
|
||||
// Polyfill fetch for Node < 18
|
||||
import nodeFetch from "node-fetch";
|
||||
import open from "open";
|
||||
|
||||
import { logger } from "src/util/logger.js";
|
||||
|
||||
import { getApiClient } from "../config.js";
|
||||
// eslint-disable-next-line import/order
|
||||
import { env } from "../env.js";
|
||||
|
||||
if (!globalThis.fetch) {
|
||||
globalThis.fetch = nodeFetch as unknown as typeof globalThis.fetch;
|
||||
}
|
||||
|
|
@ -21,33 +23,6 @@ function getAuthConfigPath() {
|
|||
return path.join(continueHome, "auth.json");
|
||||
}
|
||||
|
||||
// Represents an authenticated user's configuration
|
||||
export interface AuthenticatedConfig {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
accessToken: string;
|
||||
refreshToken: string;
|
||||
expiresAt: number;
|
||||
organizationId: string | null | undefined; // null means personal organization, undefined triggers auto-selection
|
||||
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
|
||||
modelName?: string; // Name of the selected model
|
||||
}
|
||||
|
||||
// Represents configuration when using environment variable auth
|
||||
export interface EnvironmentAuthConfig {
|
||||
/**
|
||||
* This userId?: undefined; field a trick to help TypeScript differentiate between
|
||||
* AuthenticatedConfig and EnvironmentAuthConfig. Otherwise AuthenticatedConfig is
|
||||
* a possible subtype of EnvironmentAuthConfig and TypeScript gets confused where
|
||||
* type guards are involved.
|
||||
*/
|
||||
userId?: undefined;
|
||||
accessToken: string;
|
||||
organizationId: string | null; // Can be set via --org flag in headless mode
|
||||
configUri?: string; // Optional config URI (file:// or slug://owner/slug)
|
||||
modelName?: string; // Name of the selected model
|
||||
}
|
||||
|
||||
// Union type representing the possible authentication states
|
||||
export type AuthConfig = AuthenticatedConfig | EnvironmentAuthConfig | null;
|
||||
|
||||
|
|
@ -115,9 +90,13 @@ import {
|
|||
persistModelName,
|
||||
} from "../util/modelPersistence.js";
|
||||
|
||||
import { logger } from "src/util/logger.js";
|
||||
import { autoSelectOrganizationAndConfig } from "./orgSelection.js";
|
||||
import { pathToUri, slugToUri, uriToPath, uriToSlug } from "./uriUtils.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
DeviceAuthorizationResponse,
|
||||
EnvironmentAuthConfig,
|
||||
} from "./workos-types.js";
|
||||
import {
|
||||
handleCliOrgForAuthenticatedConfig,
|
||||
handleCliOrgForEnvironmentAuth,
|
||||
|
|
@ -274,7 +253,6 @@ export async function isAuthenticated(): Promise<boolean> {
|
|||
return false;
|
||||
}
|
||||
|
||||
// Environment auth is always valid
|
||||
if (isEnvironmentAuthConfig(config)) {
|
||||
return true;
|
||||
}
|
||||
|
|
@ -284,7 +262,7 @@ export async function isAuthenticated(): Promise<boolean> {
|
|||
const refreshed = await refreshToken(config.refreshToken);
|
||||
return isAuthenticatedConfig(refreshed);
|
||||
} catch (e) {
|
||||
logger.error("Failed to refresh auto token");
|
||||
logger.error("Failed to refresh auto token", e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -292,18 +270,6 @@ export async function isAuthenticated(): Promise<boolean> {
|
|||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Device authorization response from WorkOS
|
||||
*/
|
||||
interface DeviceAuthorizationResponse {
|
||||
device_code: string;
|
||||
user_code: string;
|
||||
verification_uri: string;
|
||||
verification_uri_complete: string;
|
||||
expires_in: number;
|
||||
interval: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Request device authorization from WorkOS
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -208,7 +208,7 @@ async function loadFromSource(
|
|||
}
|
||||
} catch (error) {
|
||||
// If we're trying user assistants and it fails, fall back to default agent
|
||||
if (source.type === "user-assistant" || source.type === "cli-flag") {
|
||||
if (source.type === "user-assistant") {
|
||||
console.warn(
|
||||
chalk.yellow(
|
||||
"Failed to load user assistants, falling back to default agent",
|
||||
|
|
|
|||
|
|
@ -5,8 +5,8 @@ import * as path from "path";
|
|||
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos-types.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
|
|
|
|||
|
|
@ -7,8 +7,8 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
|||
|
||||
import { AuthService } from "src/services/AuthService.js";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos-types.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
|
|
|
|||
|
|
@ -4,8 +4,8 @@ import * as path from "path";
|
|||
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { AuthenticatedConfig } from "src/auth/workos-types.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
getModelName,
|
||||
loadAuthConfig,
|
||||
saveAuthConfig,
|
||||
|
|
|
|||
|
|
@ -1,17 +1,17 @@
|
|||
import { describe, expect, test, beforeEach, vi } from "vitest";
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
// Mock the workos module
|
||||
vi.mock("../auth/workos.js");
|
||||
|
||||
// Import the workos functions we need to mock
|
||||
import {
|
||||
loadAuthConfig,
|
||||
ensureOrganization,
|
||||
isAuthenticated,
|
||||
listUserOrganizations,
|
||||
loadAuthConfig,
|
||||
login,
|
||||
logout,
|
||||
ensureOrganization,
|
||||
saveAuthConfig,
|
||||
listUserOrganizations,
|
||||
} from "../auth/workos.js";
|
||||
|
||||
import { AuthService } from "./AuthService.js";
|
||||
|
|
@ -35,7 +35,7 @@ describe("AuthService", () => {
|
|||
describe("State Management", () => {
|
||||
test("should initialize with unauthenticated state", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
|
|
@ -48,7 +48,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should initialize with authenticated state", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
|
||||
const state = await service.initialize();
|
||||
|
||||
|
|
@ -64,7 +64,7 @@ describe("AuthService", () => {
|
|||
test("should update state after successful login", async () => {
|
||||
// Initialize first
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
await service.initialize();
|
||||
|
||||
// Mock successful login
|
||||
|
|
@ -93,7 +93,7 @@ describe("AuthService", () => {
|
|||
test("should clear state after logout", async () => {
|
||||
// Initialize with authenticated state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.logout();
|
||||
|
|
@ -112,7 +112,7 @@ describe("AuthService", () => {
|
|||
// Initialize with auth but no org
|
||||
const authWithoutOrg = { ...mockAuthConfig, organizationId: null };
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(authWithoutOrg);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
// Mock ensure organization
|
||||
|
|
@ -129,7 +129,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should throw error if not authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.ensureOrganization()).rejects.toThrow(
|
||||
|
|
@ -139,7 +139,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should pass organization slug to ensureOrganization in headless mode", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const updatedConfig = { ...mockAuthConfig, organizationId: "org-456" };
|
||||
|
|
@ -161,7 +161,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should handle personal organization slug", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const personalConfig = { ...mockAuthConfig, organizationId: null };
|
||||
|
|
@ -183,7 +183,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should work without organization slug parameter", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(ensureOrganization).mockResolvedValue(mockAuthConfig);
|
||||
|
|
@ -206,7 +206,7 @@ describe("AuthService", () => {
|
|||
describe("switchOrganization()", () => {
|
||||
test("should update state with new organization", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.switchOrganization("org-456");
|
||||
|
|
@ -227,7 +227,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should handle null organization", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const state = await service.switchOrganization(null);
|
||||
|
|
@ -238,7 +238,7 @@ describe("AuthService", () => {
|
|||
test("should throw error if not file-based auth", async () => {
|
||||
const tokenOnlyAuth = { accessToken: "token" } as any;
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(tokenOnlyAuth);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
await expect(service.switchOrganization("org-456")).rejects.toThrow(
|
||||
|
|
@ -250,7 +250,7 @@ describe("AuthService", () => {
|
|||
describe("getAvailableOrganizations()", () => {
|
||||
test("should return organizations when authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
const mockOrgs = [
|
||||
|
|
@ -265,7 +265,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should return null when not authenticated", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
await service.initialize();
|
||||
|
||||
const orgs = await service.getAvailableOrganizations();
|
||||
|
|
@ -274,7 +274,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should handle errors gracefully", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockRejectedValue(
|
||||
|
|
@ -297,7 +297,7 @@ describe("AuthService", () => {
|
|||
describe("hasMultipleOrganizations()", () => {
|
||||
test("should return true when multiple orgs available", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([
|
||||
|
|
@ -311,7 +311,7 @@ describe("AuthService", () => {
|
|||
|
||||
test("should return false when no orgs available", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
await service.initialize();
|
||||
|
||||
vi.mocked(listUserOrganizations).mockResolvedValue([]);
|
||||
|
|
@ -324,12 +324,12 @@ describe("AuthService", () => {
|
|||
describe("refresh()", () => {
|
||||
test("should reload auth state from disk", async () => {
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
await service.initialize();
|
||||
|
||||
// Update mock to return authenticated state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(mockAuthConfig);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(true);
|
||||
|
||||
const state = await service.refresh();
|
||||
|
||||
|
|
@ -345,7 +345,7 @@ describe("AuthService", () => {
|
|||
test("should emit stateChanged on login", async () => {
|
||||
// Initialize with no auth config to simulate logged out state
|
||||
vi.mocked(loadAuthConfig).mockReturnValue(null);
|
||||
vi.mocked(isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(isAuthenticated).mockResolvedValue(false);
|
||||
await service.initialize();
|
||||
|
||||
const listener = vi.fn();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { AuthenticatedConfig } from "src/auth/workos-types.js";
|
||||
import {
|
||||
AuthenticatedConfig,
|
||||
login as doLogin,
|
||||
logout as doLogout,
|
||||
ensureOrganization,
|
||||
|
|
|
|||
|
|
@ -1,26 +1,22 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import {
|
||||
SSEClientTransport,
|
||||
SseError,
|
||||
} from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import {
|
||||
StreamableHTTPClientTransport,
|
||||
StreamableHTTPError,
|
||||
} from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import {
|
||||
HttpMcpServer,
|
||||
SseMcpServer,
|
||||
StdioMcpServer,
|
||||
} from "node_modules/@continuedev/config-yaml/dist/schemas/mcp/index.js";
|
||||
|
||||
import { isAuthenticated, loadAuthConfig } from "src/auth/workos.js";
|
||||
|
||||
import { get } from "../util/apiClient.js";
|
||||
import { getErrorString } from "../util/error.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { isAuthenticated, loadAuthConfig } from "src/auth/workos.js";
|
||||
import { BaseService, ServiceWithDependencies } from "./BaseService.js";
|
||||
import { isAuthError } from "./mcpUtils.js";
|
||||
import { serviceContainer } from "./ServiceContainer.js";
|
||||
import {
|
||||
MCPConnectionInfo,
|
||||
|
|
@ -29,20 +25,6 @@ import {
|
|||
SERVICE_NAMES,
|
||||
} from "./types.js";
|
||||
|
||||
// 405 is technically "not allowed" but some servers like Sanity don't return the correct error
|
||||
// Since we're using mcp library there's a good chance 405 means auth issue and doesn't hurt to retry with auth
|
||||
function isAuthError(error: unknown) {
|
||||
return (
|
||||
(error instanceof SseError && error.code === 401) ||
|
||||
(error instanceof SseError && error.code === 405) ||
|
||||
(error instanceof StreamableHTTPError && error.code === 401) ||
|
||||
(error instanceof StreamableHTTPError && error.code === 405) ||
|
||||
(error instanceof Error && error.message.includes("401")) ||
|
||||
(error instanceof Error && error.message.includes("405")) ||
|
||||
(error instanceof Error && error.message.includes("Unauthorized"))
|
||||
);
|
||||
}
|
||||
|
||||
interface ServerConnection extends MCPConnectionInfo {
|
||||
client: Client | null;
|
||||
}
|
||||
|
|
@ -88,34 +70,18 @@ export class MCPService
|
|||
): Promise<MCPServiceState> {
|
||||
this.isHeadless = isHeadless;
|
||||
|
||||
logger.debug("Initializing MCPService", {
|
||||
configName: assistant.name,
|
||||
serverCount: assistant.mcpServers?.length || 0,
|
||||
});
|
||||
|
||||
await this.shutdownConnections();
|
||||
|
||||
this.assistant = assistant;
|
||||
this.connections.clear();
|
||||
|
||||
if (assistant.mcpServers?.length) {
|
||||
logger.debug("Starting MCP server connections", {
|
||||
serverCount: assistant.mcpServers.length,
|
||||
});
|
||||
}
|
||||
const connectionPromises = assistant.mcpServers?.map(async (config) => {
|
||||
if (config) {
|
||||
return await this.connectServer(config);
|
||||
}
|
||||
});
|
||||
|
||||
const connectionInit = Promise.all(connectionPromises ?? []).then(
|
||||
(connections) => {
|
||||
logger.debug("MCP connections established", {
|
||||
connectionCount: connections.length,
|
||||
});
|
||||
},
|
||||
);
|
||||
const connectionInit = Promise.all(connectionPromises ?? []);
|
||||
if (isHeadless || hasAgentFile) {
|
||||
await connectionInit;
|
||||
|
||||
|
|
@ -221,16 +187,9 @@ export class MCPService
|
|||
throw error;
|
||||
}
|
||||
|
||||
logger.debug("Got 401 error on MCP operation, attempting token refresh", {
|
||||
name: serverName,
|
||||
});
|
||||
|
||||
// Check if user is signed in
|
||||
const isAuthed = await isAuthenticated();
|
||||
if (!isAuthed) {
|
||||
logger.debug("User not signed in, cannot refresh OAuth token", {
|
||||
name: serverName,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
|
|
@ -265,28 +224,12 @@ export class MCPService
|
|||
if (response.data.hasCredentials && response.data.accessToken) {
|
||||
token = response.data.accessToken;
|
||||
this.apiKeyCache.set(serverName, token);
|
||||
logger.debug("Successfully retrieved OAuth token for MCP server", {
|
||||
name: serverName,
|
||||
});
|
||||
} else {
|
||||
logger.debug("No OAuth token available for MCP server", {
|
||||
name: serverName,
|
||||
configured: response.data.configured,
|
||||
hasCredentials: response.data.hasCredentials,
|
||||
expired: response.data.expired,
|
||||
});
|
||||
}
|
||||
} catch (fetchError) {
|
||||
logger.debug("Error fetching OAuth token for MCP server", {
|
||||
name: serverName,
|
||||
error: getErrorString(fetchError),
|
||||
});
|
||||
} catch {
|
||||
logger.debug("Failed to fetch mcp oauth credentials");
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
logger.debug("No OAuth token available for refresh", {
|
||||
name: serverName,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
|
|
@ -327,7 +270,6 @@ export class MCPService
|
|||
public async restartAllServers(): Promise<void> {
|
||||
if (!this.assistant) return;
|
||||
|
||||
logger.debug("Restarting all MCP servers");
|
||||
await this.shutdownConnections();
|
||||
await this.initialize(this.assistant);
|
||||
}
|
||||
|
|
@ -346,8 +288,6 @@ export class MCPService
|
|||
throw new Error(`Server ${serverName} not found in configuration`);
|
||||
}
|
||||
|
||||
logger.debug("Restarting MCP server", { name: serverName });
|
||||
|
||||
const existingConnection = this.connections.get(serverName);
|
||||
if (existingConnection) {
|
||||
if (existingConnection.status === "connected") {
|
||||
|
|
@ -379,11 +319,6 @@ export class MCPService
|
|||
this.updateState();
|
||||
|
||||
const capabilities = client.getServerCapabilities();
|
||||
logger.debug("MCP server capabilities", {
|
||||
name: serverName,
|
||||
hasPrompts: !!capabilities?.prompts,
|
||||
hasTools: !!capabilities?.tools,
|
||||
});
|
||||
|
||||
if (capabilities?.prompts) {
|
||||
try {
|
||||
|
|
@ -397,10 +332,6 @@ export class MCPService
|
|||
return (await conn.client.listPrompts()).prompts;
|
||||
},
|
||||
);
|
||||
logger.debug("Loaded MCP prompts", {
|
||||
name: serverName,
|
||||
count: connection.prompts.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(`Failed to load prompts: ${errorMessage}`);
|
||||
|
|
@ -423,10 +354,6 @@ export class MCPService
|
|||
return (await conn.client.listTools()).tools;
|
||||
},
|
||||
);
|
||||
logger.debug("Loaded MCP tools", {
|
||||
name: serverName,
|
||||
count: connection.tools.length,
|
||||
});
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.warnings.push(`Failed to load tools: ${errorMessage}`);
|
||||
|
|
@ -436,8 +363,6 @@ export class MCPService
|
|||
});
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("MCP server connected successfully", { name: serverName });
|
||||
} catch (error) {
|
||||
const errorMessage = getErrorString(error);
|
||||
connection.status = "error";
|
||||
|
|
@ -464,8 +389,6 @@ export class MCPService
|
|||
* Stop a specific server
|
||||
*/
|
||||
public async stopServer(serverName: string): Promise<void> {
|
||||
logger.debug("Stopping MCP server", { name: serverName });
|
||||
|
||||
const connection = this.connections.get(serverName);
|
||||
if (connection) {
|
||||
await this.shutdownConnection(connection);
|
||||
|
|
@ -514,7 +437,6 @@ export class MCPService
|
|||
this.isShuttingDown = true;
|
||||
|
||||
this.removeAllListeners();
|
||||
logger.debug("Shutting down MCPService");
|
||||
await this.shutdownConnections();
|
||||
}
|
||||
|
||||
|
|
@ -532,19 +454,10 @@ export class MCPService
|
|||
|
||||
if ("command" in serverConfig) {
|
||||
// STDIO: no need to check type, just if command is present
|
||||
logger.debug("Connecting to MCP server", {
|
||||
name: serverConfig.name,
|
||||
command: serverConfig.command,
|
||||
});
|
||||
const transport = this.constructStdioTransport(serverConfig, connection);
|
||||
await client.connect(transport, {});
|
||||
} else {
|
||||
// SSE/HTTP: if type isn't explicit: try http and fall back to sse
|
||||
logger.debug("Connecting to MCP server", {
|
||||
name: serverConfig.name,
|
||||
url: serverConfig.url,
|
||||
});
|
||||
|
||||
try {
|
||||
await this.withTokenRefresh(serverConfig.name, async () => {
|
||||
if (serverConfig.apiKey && !this.apiKeyCache.get(serverConfig.name)) {
|
||||
|
|
@ -560,14 +473,7 @@ export class MCPService
|
|||
try {
|
||||
const transport = this.constructHttpTransport(serverConfig);
|
||||
await client.connect(transport, {});
|
||||
} catch (e) {
|
||||
logger.debug(
|
||||
"MCP Connection: http connection failed, falling back to sse connection",
|
||||
{
|
||||
name: serverConfig.name,
|
||||
error: getErrorString(e),
|
||||
},
|
||||
);
|
||||
} catch {
|
||||
const transport = this.constructSseTransport(serverConfig);
|
||||
await client.connect(transport, {});
|
||||
}
|
||||
|
|
@ -576,9 +482,6 @@ export class MCPService
|
|||
} catch (error: unknown) {
|
||||
// If token refresh didn't work and it's a 401, fall back to mcp-remote
|
||||
if (isAuthError(error) && !this.isHeadless) {
|
||||
logger.debug("Falling back to mcp-remote after 401 error", {
|
||||
name: serverConfig.name,
|
||||
});
|
||||
const transport = this.constructStdioTransport(
|
||||
{
|
||||
name: serverConfig.name,
|
||||
|
|
|
|||
19
extensions/cli/src/services/mcpUtils.ts
Normal file
19
extensions/cli/src/services/mcpUtils.ts
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import { SseError } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
/**
|
||||
* Check if an error is an authentication error that should trigger token refresh
|
||||
* 405 is technically "not allowed" but some servers like Sanity don't return the correct error
|
||||
* Since we're using mcp library there's a good chance 405 means auth issue and doesn't hurt to retry with auth
|
||||
*/
|
||||
export function isAuthError(error: unknown): boolean {
|
||||
return (
|
||||
(error instanceof SseError && error.code === 401) ||
|
||||
(error instanceof SseError && error.code === 405) ||
|
||||
(error instanceof StreamableHTTPError && error.code === 401) ||
|
||||
(error instanceof StreamableHTTPError && error.code === 405) ||
|
||||
(error instanceof Error && error.message.includes("401")) ||
|
||||
(error instanceof Error && error.message.includes("405")) ||
|
||||
(error instanceof Error && error.message.includes("Unauthorized"))
|
||||
);
|
||||
}
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import * as workosModule from "./auth/workos.js";
|
||||
import { services } from "./services/index.js";
|
||||
|
|
@ -57,7 +57,7 @@ describe("handleSlashCommands - /info", () => {
|
|||
|
||||
it("should include version and working directory in output", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service
|
||||
const mockConfigState = {
|
||||
|
|
@ -85,7 +85,7 @@ describe("handleSlashCommands - /info", () => {
|
|||
|
||||
it("should handle authenticated user info", async () => {
|
||||
// Mock auth as authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(true);
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(true);
|
||||
vi.mocked(workosModule.loadAuthConfig).mockReturnValue({
|
||||
userEmail: "test@example.com",
|
||||
userId: "test-user",
|
||||
|
|
@ -112,7 +112,7 @@ describe("handleSlashCommands - /info", () => {
|
|||
|
||||
it("should handle missing model info gracefully", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service with no model info
|
||||
const mockConfigState = {
|
||||
|
|
@ -129,7 +129,7 @@ describe("handleSlashCommands - /info", () => {
|
|||
|
||||
it("should handle config service error", async () => {
|
||||
// Mock auth as not authenticated
|
||||
vi.mocked(workosModule.isAuthenticated).mockReturnValue(false);
|
||||
vi.mocked(workosModule.isAuthenticated).mockResolvedValue(false);
|
||||
|
||||
// Mock config service throwing error
|
||||
vi.mocked(services.config.getState).mockImplementation(() => {
|
||||
|
|
|
|||
|
|
@ -1,14 +1,15 @@
|
|||
import type { AssistantUnrolled } from "@continuedev/config-yaml";
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
vi,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
it,
|
||||
vi,
|
||||
type MockedFunction,
|
||||
} from "vitest";
|
||||
|
||||
import type { AuthConfig, AuthenticatedConfig } from "./auth/workos.js";
|
||||
import { AuthenticatedConfig } from "./auth/workos-types.js";
|
||||
import type { AuthConfig } from "./auth/workos.js";
|
||||
import type { ConfigServiceState } from "./services/types.js";
|
||||
import { handleSlashCommands } from "./slashCommands.js";
|
||||
|
||||
|
|
@ -128,7 +129,7 @@ describe("slashCommands", () => {
|
|||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockReturnValue(false);
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -157,7 +158,7 @@ describe("slashCommands", () => {
|
|||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockReturnValue(true);
|
||||
).mockResolvedValue(true);
|
||||
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
|
||||
{} as AuthConfig,
|
||||
);
|
||||
|
|
@ -199,7 +200,7 @@ describe("slashCommands", () => {
|
|||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockReturnValue(true);
|
||||
).mockResolvedValue(true);
|
||||
(loadAuthConfig as MockedFunction<typeof loadAuthConfig>).mockReturnValue(
|
||||
mockAuthConfig,
|
||||
);
|
||||
|
|
@ -230,7 +231,7 @@ describe("slashCommands", () => {
|
|||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockReturnValue(false);
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
@ -263,7 +264,7 @@ describe("slashCommands", () => {
|
|||
|
||||
(
|
||||
isAuthenticated as MockedFunction<typeof isAuthenticated>
|
||||
).mockReturnValue(false);
|
||||
).mockResolvedValue(false);
|
||||
(
|
||||
services.config.getState as MockedFunction<
|
||||
typeof services.config.getState
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue