Files
taiji-pda-v0/lib/api-client.ts
T

1103 lines
29 KiB
TypeScript

// API client for Taiji AI Platform
// Base URLs for different services
const API_BASE_URLS = {
dataIngestion: process.env.NEXT_PUBLIC_DATA_INGESTION_URL || "http://localhost:8001",
mcpServer: process.env.NEXT_PUBLIC_MCP_SERVER_URL || "http://localhost:8002", // MCP Server 映射到主机端口 8002
gateway: process.env.NEXT_PUBLIC_API_GATEWAY_URL || "http://localhost:80",
}
// Helper function to get auth token
function getAuthToken(): string | null {
if (typeof window !== "undefined") {
return localStorage.getItem("auth_token")
}
return null
}
// Helper function to get API key
function getApiKey(): string | null {
if (typeof window !== "undefined") {
return localStorage.getItem("api_key")
}
return null
}
// Helper function to build headers
function buildHeaders(contentType = "application/json"): HeadersInit {
const headers: HeadersInit = {
Accept: "application/json",
}
if (contentType) {
headers["Content-Type"] = contentType
}
const token = getAuthToken()
const apiKey = getApiKey()
if (token) {
headers.Authorization = `Bearer ${token}`
} else if (apiKey) {
headers["X-API-Key"] = apiKey
}
return headers
}
// API Response types
export interface APIResponse<T = any> {
success: boolean
data?: T
message?: string
error?: {
code?: string
message?: string
}
}
// Helper function to handle API responses
async function handleResponse<T = any>(response: Response): Promise<T> {
if (!response.ok) {
const error = await response.json().catch(() => ({ detail: response.statusText }))
throw new Error((error as any).detail || `HTTP error! status: ${response.status}`)
}
return response.json() as Promise<T>
}
// Helper function to check if backend is reachable
async function checkBackendReachable(url: string): Promise<boolean> {
try {
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 5000) // 5 second timeout
const response = await fetch(url, {
method: "HEAD",
signal: controller.signal,
})
clearTimeout(timeoutId)
return response.ok || response.status < 500
} catch {
return false
}
}
export class TaijiAPIClient {
// ==================== 认证模块 API ====================
// Base URL: http://localhost:8002/api/auth
/**
* 用户登录
*/
static async login(
email: string,
password: string,
role: "user" | "channel" | "admin" | "provider" = "user",
): Promise<APIResponse<{ token: string; refreshToken?: string; user?: any }>> {
try {
// 检查后端服务是否可达
const isReachable = await checkBackendReachable(API_BASE_URLS.mcpServer)
if (!isReachable) {
throw new Error(
`无法连接到后端服务 (${API_BASE_URLS.mcpServer})。请确保 MCP Server 正在运行。`,
)
}
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/login`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, role }),
signal: AbortSignal.timeout(10000), // 10 second timeout
})
const data = await handleResponse<APIResponse<{ token: string; refreshToken?: string; user?: any }>>(response)
if (data.success && data.data?.token && typeof window !== "undefined") {
localStorage.setItem("auth_token", data.data.token)
if (data.data.refreshToken) {
localStorage.setItem("refresh_token", data.data.refreshToken)
}
if (data.data.user) {
localStorage.setItem("user", JSON.stringify(data.data.user))
}
}
return data
} catch (error: any) {
// 处理网络错误
if (error.name === "AbortError" || error.message?.includes("timeout")) {
throw new Error("请求超时,请检查网络连接或后端服务状态")
}
if (error.message?.includes("Failed to fetch") || error.name === "TypeError") {
throw new Error(
`无法连接到后端服务 (${API_BASE_URLS.mcpServer})。请确保 MCP Server 正在运行。`,
)
}
throw error
}
}
/**
* 用户登出
*/
static async logout() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/logout`, {
method: "POST",
headers: buildHeaders(),
})
if (typeof window !== "undefined") {
localStorage.removeItem("auth_token")
localStorage.removeItem("refresh_token")
localStorage.removeItem("user")
localStorage.removeItem("api_key")
}
return handleResponse(response)
}
/**
* 刷新Token
*/
static async refreshToken(): Promise<APIResponse<{ token: string; refreshToken?: string }>> {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/refresh`, {
method: "POST",
headers: buildHeaders(),
})
const data = await handleResponse<APIResponse<{ token: string; refreshToken?: string }>>(response)
if (data.success && data.data?.token && typeof window !== "undefined") {
localStorage.setItem("auth_token", data.data.token)
if (data.data.refreshToken) {
localStorage.setItem("refresh_token", data.data.refreshToken)
}
}
return data
}
/**
* 修改密码
*/
static async changePassword(oldPassword: string, newPassword: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/password`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify({ old_password: oldPassword, new_password: newPassword }),
})
return handleResponse(response)
}
/**
* 获取API密钥信息
*/
static async getApiKeyInfo() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/keys/info`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 重新生成API密钥
*/
static async regenerateApiKey(): Promise<APIResponse<{ apiKey: string; message?: string }>> {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/auth/keys/regenerate`, {
method: "POST",
headers: buildHeaders(),
})
const data = await handleResponse<APIResponse<{ apiKey: string; message?: string }>>(response)
if (data.success && data.data?.apiKey && typeof window !== "undefined") {
localStorage.setItem("api_key", data.data.apiKey)
}
return data
}
// ==================== 用户侧平台 API ====================
// Base URL: http://localhost:8002/api/user
/**
* 获取仪表板统计
*/
static async getUserDashboardStats() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/dashboard/stats`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取Agent活动数据
*/
static async getUserAgentActivity(period: "7d" | "30d" | "90d" = "7d") {
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/user/agents/activity?period=${period}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
/**
* 选择网关类型
*/
static async selectGateway(gatewayType: "MCP" | "A2A" | "API") {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/gateway/select`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify({ gatewayType }),
})
return handleResponse(response)
}
/**
* 创建网关API
*/
static async createGatewayAPI(name: string, method: "json" | "url", content: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/gateway/api/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify({ name, method, content }),
})
return handleResponse(response)
}
/**
* 获取网关API列表
*/
static async getGatewayAPIs() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/gateway/apis`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取网关监控数据
*/
static async getGatewayMonitoring() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/gateway/monitoring`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 生成工具
*/
static async generateTool(data: {
name: string
description: string
frameworkTemplate: string
gateway: string
agentCount: number
cpu: number
memory: number
maxScale: number
model: string
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/tools/generate`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 创建数据模板
*/
static async createDataTemplate(data: {
name: string
type: "json_api" | "cloud_storage"
config: any
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/data-templates/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取平台Agent列表
*/
static async getPlatformAgents() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/agents/platform`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 部署Agent
*/
static async deployAgent(data: {
agentId: string
instances: number
model: string
gateway: "MCP" | "A2A" | "API"
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/agents/deploy`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 创建工作流
*/
static async createWorkflow(data: {
name: string
description?: string
gateway: "MCP" | "A2A" | "API"
nodes: Array<{
agentId: string
agentType: "platform" | "custom"
agentName: string
order: number
}>
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/workflows/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取余额信息
*/
static async getBillingBalance() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/billing/balance`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 充值余额
*/
static async rechargeBalance(amount: number, paymentMethod: "alipay" | "wechat" | "card" = "alipay") {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/user/billing/recharge`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify({ amount, paymentMethod }),
})
return handleResponse(response)
}
/**
* 获取计费历史
*/
static async getBillingHistory(params: {
startTime: string
endTime: string
customerName?: string
minCalls?: number
maxCalls?: number
export?: "excel" | "csv" | "pdf"
page?: number
pageSize?: number
}) {
const queryParams = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
queryParams.append(key, value.toString())
}
})
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/user/billing/history?${queryParams}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
// ==================== 渠道合作伙伴 API ====================
// Base URL: http://localhost:8002/api/channel
/**
* 获取租户列表
*/
static async getChannelTenants() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 创建租户
*/
static async createChannelTenant(data: {
name: string
email: string
password: string
subscriptionTier: "free" | "pro" | "enterprise"
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 分配租户资源
*/
static async allocateTenantResources(
tenantId: string,
data: {
agents?: Array<{ agentId: string; quantity: number }>
models?: Array<{ modelName: string; rpm: number; tpm: number }>
customAgentResources?: { cpu: number; memory: number }
},
) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/resources`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 更新租户计费设置
*/
static async updateTenantBilling(tenantId: string, data: { subscriptionTier?: string; discount?: number }) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/billing`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 为租户充值
*/
static async rechargeTenant(tenantId: string, amount: number) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/recharge`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify({ amount }),
})
return handleResponse(response)
}
/**
* 设置租户授信额度
*/
static async setTenantCreditLimit(tenantId: string, creditLimit: number) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/tenants/${tenantId}/credit`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify({ creditLimit }),
})
return handleResponse(response)
}
/**
* 申请资源
*/
static async applyForResources(data: {
type: "model" | "agent"
modelName?: string
rpm?: number
tpm?: number
agentType?: string
quantity?: number
reason: string
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/channel/resources/apply`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取渠道计费统计
*/
static async getChannelBillingStats(params: {
startTime: string
endTime: string
tenantName?: string
minCalls?: number
maxCalls?: number
export?: "excel" | "csv" | "pdf"
}) {
const queryParams = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
queryParams.append(key, value.toString())
}
})
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/channel/billing/stats?${queryParams}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
// ==================== 超级管理员 API ====================
// Base URL: http://localhost:8002/api/admin
/**
* 获取平台统计
*/
static async getAdminDashboardStats() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/dashboard/stats`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取渠道列表
*/
static async getAdminChannels() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/channels`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 创建渠道
*/
static async createAdminChannel(data: {
name: string
email: string
password: string
commissionRate: number
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/channels/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 统一管理渠道资源
*/
static async manageChannelResources(
channelId: string,
data: {
models?: string[]
agents?: Array<{ agentId: string; quantity: number }>
customAgentResources?: { cpu: number; memory: number }
channelCredit?: number
},
) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/channels/${channelId}/resources`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取所有申请
*/
static async getAdminApplications() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/channels/applications`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 审批申请
*/
static async reviewApplication(applicationId: string, approved: boolean, reason?: string) {
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/admin/channels/applications/${applicationId}/review`,
{
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify({ approved, reason }),
},
)
return handleResponse(response)
}
/**
* 获取所有模型供应商
*/
static async getAdminModelProviders() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/resources/models`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取所有Agent资源
*/
static async getAdminAgentResources() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/resources/agents`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 监控Agent健康状态
*/
static async getAdminAgentMonitoring() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/admin/monitoring/agents`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取三维度计费统计
*/
static async getAdminBillingOverview(params: {
startTime: string
endTime: string
channelName?: string
tenantName?: string
minCalls?: number
maxCalls?: number
export?: "excel" | "csv" | "pdf"
}) {
const queryParams = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined) {
queryParams.append(key, value.toString())
}
})
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/admin/billing/overview?${queryParams}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
// ==================== 供应商管理 API ====================
// Base URL: http://localhost:8002/api/providers
/**
* 获取模型供应商列表
*/
static async getModelProviders() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 创建模型供应商
*/
static async createModelProvider(data: {
name: string
provider: "openai" | "anthropic" | "azure" | "google" | "aws"
apiUrl: string
apiKey: string
supportedModels: string[]
rpm: number
tpm: number
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models/create`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取供应商详情
*/
static async getProviderDetails(providerId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models/${providerId}`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 更新供应商配置
*/
static async updateProvider(providerId: string, data: {
name?: string
provider?: string
apiUrl?: string
apiKey?: string
supportedModels?: string[]
rpm?: number
tpm?: number
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models/${providerId}`, {
method: "PUT",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 删除供应商
*/
static async deleteProvider(providerId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models/${providerId}`, {
method: "DELETE",
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 测试供应商连接
*/
static async testProviderConnection(providerId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/providers/models/${providerId}/test`, {
method: "POST",
headers: buildHeaders(),
})
return handleResponse(response)
}
// ==================== Data Ingestion 服务 API ====================
// Base URL: http://localhost:8001
/**
* 健康检查
*/
static async getHealth() {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/health`)
return handleResponse(response)
}
/**
* 同步 RapidAPI
*/
static async syncRapidAPI(category?: string, limit = 100) {
const params = new URLSearchParams()
if (category) params.append("category", category)
params.append("limit", limit.toString())
const response = await fetch(`${API_BASE_URLS.dataIngestion}/rapidapi/sync?${params}`, {
method: "POST",
})
return handleResponse(response)
}
/**
* 测试 RapidAPI 端点
*/
static async testRapidAPI(data: {
endpoint: string
method: string
params?: any
headers?: any
}) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/rapidapi/test`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 解析 OpenAPI 规范
*/
static async parseOpenAPI(url: string) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/openapi/parse?url=${encodeURIComponent(url)}`, {
method: "POST",
})
return handleResponse(response)
}
/**
* APILLAMA 处理 API 文档
*/
static async processAPILLAMA(
apiDoc: any,
context?: any,
outputFormat: "pydantic" | "json_schema" | "openapi" = "json_schema",
options?: {
include_examples?: boolean
enhance_descriptions?: boolean
validate_schema?: boolean
},
) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/apillama/process`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify({
api_doc: apiDoc,
context,
output_format: outputFormat,
...options,
}),
})
return handleResponse(response)
}
/**
* 从 API 端点生成工具定义 (Data Ingestion 服务)
*/
static async generateToolFromEndpoint(data: {
url: string
method: string
name: string
description: string
parameters?: Array<{
name: string
type: string
location?: "query" | "path" | "header" | "body"
description?: string
required?: boolean
}>
request_body?: any
responses?: any
security?: any[]
tags?: string[]
deprecated?: boolean
}) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/tools/generate`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取工具列表
*/
static async getTools(category?: string, limit = 100, offset = 0) {
const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() })
if (category) params.append("category", category)
const response = await fetch(`${API_BASE_URLS.dataIngestion}/tools?${params}`)
return handleResponse(response)
}
/**
* 获取特定工具定义
*/
static async getTool(toolName: string) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/tools/${toolName}`)
return handleResponse(response)
}
/**
* 删除工具
*/
static async deleteTool(toolName: string) {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/tools/${toolName}`, {
method: "DELETE",
})
return handleResponse(response)
}
/**
* 获取统计信息
*/
static async getStats() {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/stats`)
return handleResponse(response)
}
/**
* 清除缓存
*/
static async clearCache() {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/cache/clear`, {
method: "POST",
})
return handleResponse(response)
}
/**
* 获取 Prometheus Metrics
*/
static async getMetrics() {
const response = await fetch(`${API_BASE_URLS.dataIngestion}/metrics`)
return response.text()
}
// ==================== MCP Server 服务 API ====================
// Base URL: http://localhost:8000
/**
* MCP Server 健康检查
*/
static async getMCPHealth() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/health`)
return handleResponse(response)
}
/**
* 注册 Agent
*/
static async registerAgent(data: {
name: string
description: string
role?: string
goal?: string
tools?: string[]
config?: any
capabilities?: string[]
}) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(data),
})
return handleResponse(response)
}
/**
* 获取 Agent 列表
*/
static async getAgents(skip = 0, limit = 100) {
const params = new URLSearchParams({ skip: skip.toString(), limit: limit.toString() })
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents?${params}`)
return handleResponse(response)
}
/**
* 获取特定 Agent
*/
static async getAgent(agentId: string) {
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/${agentId}`)
return handleResponse(response)
}
/**
* 执行 Agent 工具
*/
static async executeAgentTool(agentId: string, data: {
jsonrpc?: string
id?: string
method: string
params: {
tool: { name: string; function_name?: string }
arguments: any
context?: any
}
}) {
// 构建请求体,如果data中已有jsonrpc和id则使用,否则使用默认值
const requestBody = {
jsonrpc: data.jsonrpc || "2.0",
id: data.id || `req-${Date.now()}`,
method: data.method,
params: data.params,
}
const response = await fetch(`${API_BASE_URLS.mcpServer}/agents/${agentId}/execute`, {
method: "POST",
headers: buildHeaders(),
body: JSON.stringify(requestBody),
})
return handleResponse(response)
}
/**
* 获取工具列表 (MCP Server)
*/
static async getMCPTools() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/tools`)
return handleResponse(response)
}
/**
* 获取 MCP Prometheus Metrics
*/
static async getMCPMetrics() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/metrics`)
return response.text()
}
/**
* 获取系统性能指标
*/
static async getMonitoringMetrics() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/v1/monitoring/metrics`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取服务统计信息
*/
static async getMonitoringStats(service: "all" | "agents" | "executions" | "tools" | "users" = "all") {
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/v1/monitoring/stats?service=${service}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
/**
* 获取性能趋势数据
*/
static async getMonitoringTrends(params: {
metric?: "executions" | "eu_consumption"
period?: "24h" | "7d" | "30d"
interval?: "1h" | "6h" | "1d"
}) {
const queryParams = new URLSearchParams()
Object.entries(params).forEach(([key, value]) => {
if (value) {
queryParams.append(key, value)
}
})
const response = await fetch(
`${API_BASE_URLS.mcpServer}/api/v1/monitoring/trends?${queryParams}`,
{
headers: buildHeaders(),
},
)
return handleResponse(response)
}
/**
* 获取系统告警
*/
static async getMonitoringAlerts(severity?: "info" | "warning" | "critical") {
const params = severity ? `?severity=${severity}` : ""
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/v1/monitoring/alerts${params}`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
/**
* 获取监控仪表盘聚合
*/
static async getMonitoringDashboard() {
const response = await fetch(`${API_BASE_URLS.mcpServer}/api/v1/monitoring/dashboard`, {
headers: buildHeaders(),
})
return handleResponse(response)
}
// ==================== WebSocket API ====================
/**
* 创建 Agent WebSocket 连接
*/
static createAgentWebSocket(agentIdOrName: string) {
const wsUrl = API_BASE_URLS.mcpServer.replace("http", "ws")
return new WebSocket(`${wsUrl}/ws/${agentIdOrName}`)
}
}