import { get, post, put, del } from '@/utils/request' export interface MCPService { id: string tenant_id?: number name: string description: string usage_instructions?: string enabled: boolean transport_type: 'sse' | 'http-streamable' | 'stdio' url?: string // Optional: required for SSE/HTTP Streamable headers?: Record auth_config?: { // Authentication strategy. Empty/absent means none. "oauth" enables the // per-user OAuth2 authorization-code flow (zero-config: discovery + // dynamic client registration). auth_type?: '' | 'api_key' | 'bearer' | 'oauth' // Secret fields (api_key, token) are NEVER returned by the server in // this shape — they live behind the /credentials subresource. The // optional-property typing remains so create-mode payloads can still // carry them in the initial POST body. api_key?: string // Header name carrying api_key when auth_type is "api_key". Non-secret; // empty defaults to "X-API-Key". Lets services expecting the key in a // different header (e.g. raw token in "Authorization") work. api_key_header?: string token?: string custom_headers?: Record // OAuth-only, non-secret configuration. scopes?: string[] auth_server_metadata_url?: string // OAuth client registered with the authorization server ahead of time. // Empty means dynamic client registration. Non-secret. client_id?: string // Secret of client_id. Like api_key it is never returned; edits go // through the /credentials subresource. client_secret?: string } advanced_config?: { timeout?: number retry_count?: number retry_delay?: number } stdio_config?: { command: 'uvx' | 'npx' // Command: uvx or npx args: string[] // Command arguments array } env_vars?: Record // Environment variables for stdio transport is_builtin?: boolean // Whether this is a builtin MCP service // Per-field "configured?" map embedded on the main response (server-side // dto.MCPServiceResponse.Credentials). Drives the CredentialResource card // without a follow-up GET. Absent for builtin services. credentials?: Record created_at?: string updated_at?: string catalog?: { tool_count: number stale: boolean synced_at: string } } export interface MCPTool { name: string description: string inputSchema: Record require_approval?: boolean enabled?: boolean } export interface MCPToolApprovalRow { id: string tenant_id?: number service_id: string tool_name: string require_approval: boolean enabled: boolean } export interface MCPResource { uri: string name: string description?: string mimeType?: string } export interface MCPTestResult { success: boolean message?: string description?: string // Set when the server requires OAuth (RFC 9728) but the service was not // configured for it — the UI guides the user to switch to OAuth 2.0. oauth_required?: boolean tools?: MCPTool[] resources?: MCPResource[] } // List all MCP services /** Locates a shared agent's source workspace, same parameters as a chat request. */ export interface MCPAgentScope { agentId?: string /** Set only for a shared agent; left empty for this workspace's own agents. */ sourceTenantId?: string | number } // Lists MCP services. // // With a shared agent, the result is the services THAT agent can be @mentioned // with: they live in its owner's workspace and none of their ids match anything // in the caller's. Those rows also carry a narrowed field set — no URL, // headers or credential metadata, which describe how the owner wired the // service up — since the picker needs nothing more. export async function listMCPServices(agent?: MCPAgentScope): Promise { const params: Record = {} if (agent?.agentId && agent?.sourceTenantId) { params.agent_id = agent.agentId params.agent_source_tenant_id = String(agent.sourceTenantId) } const response: any = await get('/api/v1/mcp-services', { params }) return response.data || [] } // Get a single MCP service by ID export async function getMCPService(id: string): Promise { const response: any = await get(`/api/v1/mcp-services/${id}`) return response.data } // Create a new MCP service export async function createMCPService(data: Partial): Promise { const response: any = await post('/api/v1/mcp-services', data) return response.data } // Update an existing MCP service export async function updateMCPService(id: string, data: Partial): Promise { const response: any = await put(`/api/v1/mcp-services/${id}`, data) return response.data } // Delete an MCP service export async function deleteMCPService(id: string): Promise { await del(`/api/v1/mcp-services/${id}`) } // Test MCP service connection export async function testMCPService(id: string): Promise { const response: any = await post(`/api/v1/mcp-services/${id}/test`, {}) // 后端返回格式: { success: true, data: MCPTestResult } // response interceptor 已经返回了 data,所以 response 就是 { success: true, data: {...} } if (response && response.data) { return response.data } // 如果格式不对,尝试直接返回 response(可能是直接返回的数据) return response } // Get tools from an MCP service export async function getMCPServiceTools(id: string): Promise { const response: any = await get(`/api/v1/mcp-services/${id}/tools`) return response.data || [] } // Get resources from an MCP service export async function getMCPServiceResources(id: string): Promise { const response: any = await get(`/api/v1/mcp-services/${id}/resources`) return response.data || [] } /** Persisted per-tool human-approval flags (issue #1173) */ export async function getMCPToolApprovals(serviceId: string): Promise { const response: any = await get(`/api/v1/mcp-services/${serviceId}/tool-approvals`) return response.data || [] } export async function setMCPToolApproval(serviceId: string, toolName: string, requireApproval: boolean): Promise { await put(`/api/v1/mcp-services/${serviceId}/tool-approvals/${encodeURIComponent(toolName)}`, { require_approval: requireApproval }) } export async function setMCPToolEnabled(serviceId: string, toolName: string, enabled: boolean): Promise { await put(`/api/v1/mcp-services/${serviceId}/tool-approvals/${encodeURIComponent(toolName)}`, { enabled }) } // ---------------------------------------------------------------------------- // Credential subresource (issue #988 follow-up). // // Secrets travel through a dedicated /credentials endpoint instead of the // main MCP PUT body. "Is this configured?" metadata is embedded on the main // MCPService response (MCPService.credentials), so there is no GET on this // endpoint — only PUT (write) and DELETE (clear). Both trigger an MCP // client reconnect server-side. // ---------------------------------------------------------------------------- export type McpCredentialField = 'api_key' | 'token' | 'client_secret' export interface CredentialFieldMetadata { configured: boolean } export interface McpCredentialsResponse { fields: Record } export async function putMCPCredentials( serviceId: string, body: Partial> ): Promise { const response: any = await put(`/api/v1/mcp-services/${serviceId}/credentials`, body) return (response.data ?? response) as McpCredentialsResponse } export async function deleteMCPCredentialField( serviceId: string, field: McpCredentialField ): Promise { await del(`/api/v1/mcp-services/${serviceId}/credentials/${field}`) } // ---------------------------------------------------------------------------- // Per-user OAuth2 authorization-code flow. // // The user authorizes a service once; the backend stores their access/refresh // token (per tenant + user + service) and refreshes it transparently. The // callback is a public backend route that the third-party authorization // server redirects to. // ---------------------------------------------------------------------------- // Path of the public backend OAuth callback (registered outside /mcp-services // to avoid a route conflict, and allow-listed for no-auth in the backend). export const MCP_OAUTH_CALLBACK_PATH = '/api/v1/mcp-oauth/callback' export interface MCPOAuthAuthorization { authorizationUrl: string authorizationAttempt: string } export type MCPOAuthTokenState = 'authorized' | 'refreshable' | 'reauth_required' | 'pending' export interface MCPOAuthStatus { authorized: boolean state: MCPOAuthTokenState refresh_available: boolean expires_at?: string } // Begin authorization for the current user. The attempt id binds polling to // this popup, so an older stored token cannot be mistaken for fresh consent. export async function getMCPOAuthAuthorizeURL( serviceId: string, body: { redirect_uri: string; frontend_redirect?: string } ): Promise { const response: any = await post(`/api/v1/mcp-services/${serviceId}/oauth/authorize-url`, body) const data = response.data ?? response return { authorizationUrl: data?.authorization_url ?? '', authorizationAttempt: data?.authorization_attempt ?? '', } } // Whether the current user has authorized this service. export async function getMCPOAuthStatus( serviceId: string, authorizationAttempt?: string, ): Promise { const query = authorizationAttempt ? `?authorization_attempt=${encodeURIComponent(authorizationAttempt)}` : '' const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status${query}`) return Boolean((response.data ?? response)?.authorized) } // Full lifecycle status for management surfaces. Expired access tokens with a // refresh token are "refreshable", not falsely presented as already usable. export async function getMCPOAuthAuthorizationStatus(serviceId: string): Promise { const response: any = await get(`/api/v1/mcp-services/${serviceId}/oauth/status`) const data = response.data ?? response return { authorized: Boolean(data?.authorized), state: data?.state ?? 'reauth_required', refresh_available: Boolean(data?.refresh_available), expires_at: data?.expires_at, } } // Revoke the current user's token (forces re-authorization). export async function revokeMCPOAuthToken(serviceId: string): Promise { await del(`/api/v1/mcp-services/${serviceId}/oauth/token`) } export async function resolveToolApproval( pendingId: string, body: { decision: 'approve' | 'reject'; modified_args?: Record; reason?: string; allow_in_session?: boolean } ): Promise<{ resumed: boolean }> { const res: any = await post(`/api/v1/agent/tool-approvals/${encodeURIComponent(pendingId)}`, body) // resumed: the run had been suspended and now continues on the server; // the client must re-attach to the message's stream. return { resumed: Boolean(res?.resumed) } } // A remembered "allow for this conversation" approval. export interface AgentGrant { id: string scope: string scope_id: string grant_key: string label: string created_at: string last_used_at?: string } // The current user's grants in a conversation, including those approved in // its delegated sub-tasks. export async function listAgentGrants(sessionId: string): Promise { const res: any = await get(`/api/v1/agent/grants?session_id=${encodeURIComponent(sessionId)}`) return Array.isArray(res?.data) ? res.data : [] } export async function revokeAgentGrant(id: string): Promise { await del(`/api/v1/agent/grants/${encodeURIComponent(id)}`) } // Answer a prompt the agent raised (ask_user, tool approval) with the kind's // response object. export async function resolveAgentPrompt( promptId: string, kind: string, response: Record, ): Promise<{ resumed: boolean }> { const res: any = await post(`/api/v1/agent/prompts/${encodeURIComponent(promptId)}`, { kind, response }) return { resumed: Boolean(res?.resumed) } } // Resume an agent run that paused on an in-conversation MCP OAuth prompt. // Call after the per-user authorization popup completes; the backend verifies // the token exists before unblocking the paused tool call. export async function resolveMCPOAuth( pendingId: string, body: { service_id: string; decision?: 'authorize' | 'cancel' } ): Promise { await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}`, body) } export async function cancelMCPOAuth(pendingId: string): Promise { await post(`/api/v1/agent/mcp-oauth-resolutions/${encodeURIComponent(pendingId)}/cancel`, {}) } // Persisted directory: GET never opens an upstream MCP connection. export interface MCPMetadata { service_id: string tools: MCPTool[] instructions: string server_name: string server_version: string server_description: string synced_at: string stale: boolean } export async function getMCPMetadata(id: string): Promise { const response: any = await get(`/api/v1/mcp-services/${id}/metadata`) return response.data ?? null } export async function refreshMCPMetadata(id: string): Promise { const response: any = await post(`/api/v1/mcp-services/${id}/metadata/refresh`, {}) return response.data } export async function generateMCPUsageInstructions(id: string, language: string): Promise { const response: any = await post(`/api/v1/mcp-services/${id}/usage-instructions/generate`, { language }, { timeout: 65000 }) return response.data.usage_instructions }