Spaces:
Running
Running
File size: 10,854 Bytes
aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 d63a244 aad94d8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 |
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import type { Tool } from "@modelcontextprotocol/sdk/types.js";
import type {
MCPServerConfig,
MCPServerConnection,
MCPClientState,
MCPToolResult,
} from "../types/mcp.js";
import { MCP_CLIENT_CONFIG, STORAGE_KEYS } from "../config/constants";
export class MCPClientService {
private clients: Map<string, Client> = new Map();
private connections: Map<string, MCPServerConnection> = new Map();
private listeners: Array<(state: MCPClientState) => void> = [];
constructor() {
// Load saved server configurations from localStorage
this.loadServerConfigs();
}
// Add state change listener
addStateListener(listener: (state: MCPClientState) => void) {
this.listeners.push(listener);
}
// Remove state change listener
removeStateListener(listener: (state: MCPClientState) => void) {
const index = this.listeners.indexOf(listener);
if (index > -1) {
this.listeners.splice(index, 1);
}
}
// Notify all listeners of state changes
private notifyStateChange() {
const state = this.getState();
this.listeners.forEach((listener) => listener(state));
}
// Get current MCP client state
getState(): MCPClientState {
const servers: Record<string, MCPServerConnection> = {};
for (const [id, connection] of this.connections) {
servers[id] = connection;
}
return {
servers,
isLoading: false,
error: undefined,
};
}
// Load server configurations from localStorage
private loadServerConfigs() {
try {
const stored = localStorage.getItem(STORAGE_KEYS.MCP_SERVERS);
if (stored) {
const configs: MCPServerConfig[] = JSON.parse(stored);
configs.forEach((config) => {
const connection: MCPServerConnection = {
config,
isConnected: false,
tools: [],
lastError: undefined,
lastConnected: undefined,
};
this.connections.set(config.id, connection);
});
}
} catch (error) {
// Silently handle missing or corrupted config
}
}
// Save server configurations to localStorage
private saveServerConfigs() {
try {
const configs = Array.from(this.connections.values()).map(
(conn) => conn.config
);
localStorage.setItem(STORAGE_KEYS.MCP_SERVERS, JSON.stringify(configs));
} catch (error) {
// Handle storage errors gracefully
throw new Error(`Failed to save server configuration: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Add a new MCP server
async addServer(config: MCPServerConfig): Promise<void> {
const connection: MCPServerConnection = {
config,
isConnected: false,
tools: [],
lastError: undefined,
lastConnected: undefined,
};
this.connections.set(config.id, connection);
this.saveServerConfigs();
this.notifyStateChange();
// Auto-connect if enabled
if (config.enabled) {
await this.connectToServer(config.id);
}
}
// Remove an MCP server
async removeServer(serverId: string): Promise<void> {
// Disconnect first if connected
await this.disconnectFromServer(serverId);
// Remove from our maps
this.connections.delete(serverId);
this.clients.delete(serverId);
this.saveServerConfigs();
this.notifyStateChange();
}
// Connect to an MCP server
async connectToServer(serverId: string): Promise<void> {
const connection = this.connections.get(serverId);
if (!connection) {
throw new Error(`Server ${serverId} not found`);
}
if (connection.isConnected) {
return; // Already connected
}
try {
// Create client
const client = new Client(
{
name: MCP_CLIENT_CONFIG.NAME,
version: MCP_CLIENT_CONFIG.VERSION,
},
{
capabilities: {
tools: {},
},
}
);
// Create transport based on config
let transport;
const url = new URL(connection.config.url);
// Prepare headers for authentication
const headers: Record<string, string> = {};
if (connection.config.auth) {
switch (connection.config.auth.type) {
case "bearer":
if (connection.config.auth.token) {
headers[
"Authorization"
] = `Bearer ${connection.config.auth.token}`;
}
break;
case "basic":
if (
connection.config.auth.username &&
connection.config.auth.password
) {
const credentials = btoa(
`${connection.config.auth.username}:${connection.config.auth.password}`
);
headers["Authorization"] = `Basic ${credentials}`;
}
break;
case "oauth":
if (connection.config.auth.token) {
headers[
"Authorization"
] = `Bearer ${connection.config.auth.token}`;
}
break;
}
}
switch (connection.config.transport) {
case "websocket": {
// Convert HTTP/HTTPS URLs to WS/WSS
const wsUrl = new URL(connection.config.url);
wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
transport = new WebSocketClientTransport(wsUrl);
// Note: WebSocket auth headers would need to be passed differently
// For now, auth is only supported on HTTP-based transports
break;
}
case "streamable-http":
transport = new StreamableHTTPClientTransport(url, {
requestInit:
Object.keys(headers).length > 0 ? { headers } : undefined,
});
break;
case "sse":
transport = new SSEClientTransport(url, {
requestInit:
Object.keys(headers).length > 0 ? { headers } : undefined,
});
break;
default:
throw new Error(
`Unsupported transport: ${connection.config.transport}`
);
}
// Set up error handling
client.onerror = (error) => {
connection.lastError = error.message;
connection.isConnected = false;
this.notifyStateChange();
};
// Connect to the server
await client.connect(transport);
// List available tools
const toolsResult = await client.listTools();
// Update connection state
connection.isConnected = true;
connection.tools = toolsResult.tools;
connection.lastError = undefined;
connection.lastConnected = new Date();
// Store client reference
this.clients.set(serverId, client);
this.notifyStateChange();
} catch (error) {
connection.isConnected = false;
connection.lastError =
error instanceof Error ? error.message : "Connection failed";
this.notifyStateChange();
throw error;
}
}
// Disconnect from an MCP server
async disconnectFromServer(serverId: string): Promise<void> {
const client = this.clients.get(serverId);
const connection = this.connections.get(serverId);
if (client) {
try {
await client.close();
} catch (error) {
// Handle disconnect error silently
}
this.clients.delete(serverId);
}
if (connection) {
connection.isConnected = false;
connection.tools = [];
this.notifyStateChange();
}
}
// Get all tools from all connected servers
getAllTools(): Tool[] {
const allTools: Tool[] = [];
for (const connection of this.connections.values()) {
if (connection.isConnected && connection.config.enabled) {
allTools.push(...connection.tools);
}
}
return allTools;
}
// Call a tool on an MCP server
async callTool(
serverId: string,
toolName: string,
args: Record<string, unknown>
): Promise<MCPToolResult> {
const client = this.clients.get(serverId);
const connection = this.connections.get(serverId);
if (!client || !connection?.isConnected) {
throw new Error(`Not connected to server ${serverId}`);
}
try {
const result = await client.callTool({
name: toolName,
arguments: args,
});
return {
content: Array.isArray(result.content) ? result.content : [],
isError: Boolean(result.isError),
};
} catch (error) {
throw new Error(`Tool execution failed (${toolName}): ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Test connection to a server without saving it
async testConnection(config: MCPServerConfig): Promise<boolean> {
try {
const client = new Client(
{
name: MCP_CLIENT_CONFIG.TEST_CLIENT_NAME,
version: MCP_CLIENT_CONFIG.VERSION,
},
{
capabilities: {
tools: {},
},
}
);
let transport;
const url = new URL(config.url);
switch (config.transport) {
case "websocket": {
const wsUrl = new URL(config.url);
wsUrl.protocol = wsUrl.protocol === "https:" ? "wss:" : "ws:";
transport = new WebSocketClientTransport(wsUrl);
break;
}
case "streamable-http":
transport = new StreamableHTTPClientTransport(url);
break;
case "sse":
transport = new SSEClientTransport(url);
break;
default:
throw new Error(`Unsupported transport: ${config.transport}`);
}
await client.connect(transport);
await client.close();
return true;
} catch (error) {
throw new Error(`Connection test failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
}
}
// Connect to all enabled servers
async connectAll(): Promise<void> {
const promises = Array.from(this.connections.entries())
.filter(
([, connection]) => connection.config.enabled && !connection.isConnected
)
.map(([serverId]) =>
this.connectToServer(serverId).catch(() => {
// Handle auto-connection error silently
})
);
await Promise.all(promises);
}
// Disconnect from all servers
async disconnectAll(): Promise<void> {
const promises = Array.from(this.connections.keys()).map((serverId) =>
this.disconnectFromServer(serverId)
);
await Promise.all(promises);
}
}
|