Spaces:
Sleeping
Sleeping
File size: 7,815 Bytes
07af8f3 |
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 |
import axios, { AxiosRequestConfig } from 'axios';
import {
CloudServer,
CloudTool,
MCPRouterResponse,
MCPRouterListServersResponse,
MCPRouterListToolsResponse,
MCPRouterCallToolResponse,
} from '../types/index.js';
import { loadOriginalSettings } from '../config/index.js';
// MCPRouter API default base URL
const DEFAULT_MCPROUTER_API_BASE = 'https://api.mcprouter.to/v1';
// Get MCPRouter API config from system configuration
const getMCPRouterConfig = () => {
const settings = loadOriginalSettings();
const mcpRouterConfig = settings.systemConfig?.mcpRouter;
return {
apiKey: mcpRouterConfig?.apiKey || process.env.MCPROUTER_API_KEY || '',
referer: mcpRouterConfig?.referer || process.env.MCPROUTER_REFERER || 'https://www.mcphubx.com',
title: mcpRouterConfig?.title || process.env.MCPROUTER_TITLE || 'MCPHub',
baseUrl:
mcpRouterConfig?.baseUrl || process.env.MCPROUTER_API_BASE || DEFAULT_MCPROUTER_API_BASE,
};
};
// Get axios config with MCPRouter headers
const getAxiosConfig = (): AxiosRequestConfig => {
const mcpRouterConfig = getMCPRouterConfig();
return {
headers: {
Authorization: mcpRouterConfig.apiKey ? `Bearer ${mcpRouterConfig.apiKey}` : '',
'HTTP-Referer': mcpRouterConfig.referer || 'https://www.mcphubx.com',
'X-Title': mcpRouterConfig.title || 'MCPHub',
'Content-Type': 'application/json',
},
};
};
// List all available cloud servers
export const getCloudServers = async (): Promise<CloudServer[]> => {
try {
const axiosConfig = getAxiosConfig();
const mcpRouterConfig = getMCPRouterConfig();
const response = await axios.post<MCPRouterResponse<MCPRouterListServersResponse>>(
`${mcpRouterConfig.baseUrl}/list-servers`,
{},
axiosConfig,
);
const data = response.data;
if (data.code !== 0) {
throw new Error(data.message || 'Failed to fetch servers');
}
return data.data.servers || [];
} catch (error) {
console.error('Error fetching cloud market servers:', error);
throw error;
}
};
// Get a specific cloud server by name
export const getCloudServerByName = async (name: string): Promise<CloudServer | null> => {
try {
const servers = await getCloudServers();
return servers.find((server) => server.name === name || server.config_name === name) || null;
} catch (error) {
console.error(`Error fetching cloud server ${name}:`, error);
throw error;
}
};
// List tools for a specific cloud server
export const getCloudServerTools = async (serverKey: string): Promise<CloudTool[]> => {
try {
const axiosConfig = getAxiosConfig();
const mcpRouterConfig = getMCPRouterConfig();
if (
!axiosConfig.headers?.['Authorization'] ||
axiosConfig.headers['Authorization'] === 'Bearer '
) {
throw new Error('MCPROUTER_API_KEY_NOT_CONFIGURED');
}
const response = await axios.post<MCPRouterResponse<MCPRouterListToolsResponse>>(
`${mcpRouterConfig.baseUrl}/list-tools`,
{
server: serverKey,
},
axiosConfig,
);
const data = response.data;
if (data.code !== 0) {
throw new Error(data.message || 'Failed to fetch tools');
}
return data.data.tools || [];
} catch (error) {
console.error(`Error fetching tools for server ${serverKey}:`, error);
throw error;
}
};
// Call a tool on a cloud server
export const callCloudServerTool = async (
serverName: string,
toolName: string,
args: Record<string, any>,
): Promise<MCPRouterCallToolResponse> => {
try {
const axiosConfig = getAxiosConfig();
const mcpRouterConfig = getMCPRouterConfig();
if (
!axiosConfig.headers?.['Authorization'] ||
axiosConfig.headers['Authorization'] === 'Bearer '
) {
throw new Error('MCPROUTER_API_KEY_NOT_CONFIGURED');
}
const response = await axios.post<MCPRouterResponse<MCPRouterCallToolResponse>>(
`${mcpRouterConfig.baseUrl}/call-tool`,
{
server: serverName,
name: toolName,
arguments: args,
},
axiosConfig,
);
const data = response.data;
if (data.code !== 0) {
throw new Error(data.message || 'Failed to call tool');
}
return data.data;
} catch (error) {
console.error(`Error calling tool ${toolName} on server ${serverName}:`, error);
throw error;
}
};
// Get all categories from cloud servers
export const getCloudCategories = async (): Promise<string[]> => {
try {
const servers = await getCloudServers();
const categories = new Set<string>();
servers.forEach((server) => {
// Extract categories from content or description
// This is a simple implementation, you might want to parse the content more sophisticatedly
if (server.content) {
const categoryMatches = server.content.match(/category[:\s]*([^,\n]+)/gi);
if (categoryMatches) {
categoryMatches.forEach((match) => {
const category = match.replace(/category[:\s]*/i, '').trim();
if (category) categories.add(category);
});
}
}
});
return Array.from(categories).sort();
} catch (error) {
console.error('Error fetching cloud market categories:', error);
throw error;
}
};
// Get all tags from cloud servers
export const getCloudTags = async (): Promise<string[]> => {
try {
const servers = await getCloudServers();
const tags = new Set<string>();
servers.forEach((server) => {
// Extract tags from content or description
if (server.content) {
const tagMatches = server.content.match(/tag[s]?[:\s]*([^,\n]+)/gi);
if (tagMatches) {
tagMatches.forEach((match) => {
const tag = match.replace(/tag[s]?[:\s]*/i, '').trim();
if (tag) tags.add(tag);
});
}
}
});
return Array.from(tags).sort();
} catch (error) {
console.error('Error fetching cloud market tags:', error);
throw error;
}
};
// Search cloud servers by query
export const searchCloudServers = async (query: string): Promise<CloudServer[]> => {
try {
const servers = await getCloudServers();
const searchTerms = query
.toLowerCase()
.split(' ')
.filter((term) => term.length > 0);
if (searchTerms.length === 0) {
return servers;
}
return servers.filter((server) => {
const searchText = [
server.name,
server.title,
server.description,
server.content,
server.author_name,
]
.join(' ')
.toLowerCase();
return searchTerms.some((term) => searchText.includes(term));
});
} catch (error) {
console.error('Error searching cloud market servers:', error);
throw error;
}
};
// Filter cloud servers by category
export const filterCloudServersByCategory = async (category: string): Promise<CloudServer[]> => {
try {
const servers = await getCloudServers();
if (!category) {
return servers;
}
return servers.filter((server) => {
const content = (server.content || '').toLowerCase();
return content.includes(category.toLowerCase());
});
} catch (error) {
console.error('Error filtering cloud market servers by category:', error);
throw error;
}
};
// Filter cloud servers by tag
export const filterCloudServersByTag = async (tag: string): Promise<CloudServer[]> => {
try {
const servers = await getCloudServers();
if (!tag) {
return servers;
}
return servers.filter((server) => {
const content = (server.content || '').toLowerCase();
return content.includes(tag.toLowerCase());
});
} catch (error) {
console.error('Error filtering cloud market servers by tag:', error);
throw error;
}
};
|