mcp_server_app.py
Overview
mcp_server_app.py is a Flask-based RESTful API module dedicated to managing MCP (Multi-Cloud Platform) servers within the InfiniFlow application. The file provides endpoints for CRUD (Create, Read, Update, Delete) operations on MCP server entities, importing/exporting MCP servers, listing and caching tools associated with MCP servers, and testing connectivity and functionality of MCP servers and their tools.
The module acts as a controller layer interacting with the database services (MCPServerService, TenantService), utility functions for request validation and response formatting, and the MCPToolCallSession for communicating with MCP tools.
Detailed Description of Components
Flask Blueprint and Decorators
The routes are registered under a Flask blueprint or app instance named manager (assumed imported or declared elsewhere).
@login_requiredensures that all endpoints require authenticated users.@validate_request(...) decorators enforce presence of required JSON keys in the incoming requests.
Endpoint Functions
list_mcp() -> Response
Route: /list (POST)
Purpose: List MCP servers belonging to the current logged-in user with optional filtering, pagination, and sorting.
Parameters (via URL query):
keywords: String, search keyword to filter MCP servers by name or other attributes.page: Integer, page number for pagination.page_size: Integer, number of items per page.orderby: String, field to sort by (default:"create_time").desc: Boolean string, whether to sort descending (default:"true").
Request JSON Body:
mcp_ids: List of MCP server IDs to filter by (optional).
Returns:
JSON response with keys:
"mcp_servers": List of MCP servers matching criteria."total": Total count of matched MCP servers.
Example Usage:
POST /list?keywords=test&page=1&page_size=10&orderby=name&desc=false
Content-Type: application/json
{
"mcp_ids": ["id1", "id2"]
}
detail() -> Response
Route: /detail (GET)
Purpose: Fetch MCP server details by MCP server ID.
Parameters (via URL query):
mcp_id: String, identifier of the MCP server.
Returns:
JSON response with MCP server details or
NOT_FOUNDif not found.
create() -> Response
Route: /create (POST)
Purpose: Create a new MCP server for the current user.
Required JSON fields: "name", "url", "server_type" (validated by @validate_request)
Input JSON fields:
name: String, MCP server name (max 255 bytes).url: String, MCP server URL.server_type: String, must be inVALID_MCP_SERVER_TYPES.headers: JSON object, optional HTTP headers for MCP server calls.variables: JSON object, optional variables for MCP server.timeout: Float, optional timeout for tool retrieval (default 10 seconds).
Process:
Validates input, uniqueness of name for tenant, and server type.
Parses
headersandvariables.Generates UUID for the new MCP server.
Verifies tenant existence.
Retrieves tools from MCP server via
get_mcp_toolsfor validation.Inserts the new MCP server record.
Returns:
JSON response with created MCP server data on success.
Error messages on validation failure or exceptions.
update() -> Response
Route: /update (POST)
Purpose: Update an existing MCP server owned by the current user.
Required JSON fields: "mcp_id" (validated)
Input JSON fields (optional):
name,url,server_type,headers,variables,timeout
Process:
Validates MCP server ownership and existence.
Performs similar validation as
create().Updates MCP server record using
filter_update.Returns updated MCP server data.
rm() -> Response
Route: /rm (POST)
Purpose: Delete MCP servers by IDs for the current user.
Required JSON fields: "mcp_ids" (list of MCP server IDs)
Returns:
Success boolean or error message.
import_multiple() -> Response
Route: /import (POST)
Purpose: Bulk import MCP servers from a provided dictionary of server configurations.
Required JSON fields: "mcpServers" (dictionary keyed by server name)
Behavior:
Validates each server configuration for required fields (
type,url).Checks and resolves name duplication by appending suffixes.
Validates tool availability per server.
Inserts servers and collects per-server import results.
Returns:
List of per-server import results with success status and messages.
export_multiple() -> Response
Route: /export (POST)
Purpose: Export MCP server configurations by IDs owned by the current user.
Required JSON fields: "mcp_ids" (list)
Returns:
Dictionary of MCP server configurations keyed by server name.
list_tools() -> Response
Route: /list_tools (POST)
Purpose: Retrieve the list of tools available from specified MCP servers.
Required JSON fields: "mcp_ids" (list)
Behavior:
For each MCP server ID, creates an
MCPToolCallSessionand fetches tools with timeout.Merges cached tool enabled state with fetched tool info.
Closes all sessions after completion.
Returns:
Dictionary keyed by MCP server ID, each containing a list of tool descriptions.
test_tool() -> Response
Route: /test_tool (POST)
Purpose: Test execution of a specific tool on a specified MCP server.
Required JSON fields: "mcp_id", "tool_name", "arguments"
Behavior:
Validates MCP server ownership.
Calls the tool with provided arguments using
MCPToolCallSession.Returns the tool call result.
cache_tool() -> Response
Route: /cache_tools (POST)
Purpose: Cache tool metadata for a MCP server to speed up future tool listings.
Required JSON fields: "mcp_id", "tools" (list of tool dicts)
Behavior:
Updates MCP server's
variables["tools"]with the provided tool info.
test_mcp() -> Response
Route: /test_mcp (POST)
Purpose: Test MCP server connectivity and retrieve tools without saving the MCP server.
Required JSON fields: "url", "server_type"
Behavior:
Creates a temporary MCPServer instance.
Uses
MCPToolCallSessionto retrieve tools with timeout.Returns list of tools with enabled flag set to True.
Important Implementation Details and Algorithms
Validation and Error Handling:
Each endpoint validates inputs strictly using decorators and inline checks, returning detailed error messages withget_data_error_result.Tool Retrieval and Caching:
Tool metadata is retrieved throughMCPToolCallSession, which handles the communication protocol with MCP servers. Tool info is cached inside thevariablesfield of MCP server records to avoid repeated network calls.Name Deduplication in Import:
When importing multiple MCP servers, the code automatically renames servers with duplicate names by appending incremental suffixes (_0,_1, etc.) to avoid conflicts within the same tenant.Session Management:
MCP tool call sessions are explicitly closed after use viaclose_multiple_mcp_toolcall_sessionsto release resources. The documentation notes that these are blocking calls and suggests potential async/background improvements.Tenant Isolation:
Most operations filter MCP servers by the tenant ID of the current user (current_user.id) to ensure multi-tenant security and data separation.
Interaction with Other System Components
Database Services:
MCPServerService: Provides CRUD operations and queries for MCPServer model objects.TenantService: Validates tenant existence.
Models:
MCPServer: ORM model representing MCP server entities.
Utilities:
get_uuid(): Generates unique IDs.get_json_result(),get_data_error_result(),server_error_response(): Standardized response formatting.validate_request: Request JSON validation decorator.get_float(),safe_json_parse(): Safe parsing helpers.get_mcp_tools(): Retrieves available tools from MCP servers.
MCP Tool Communication:
MCPToolCallSession: Encapsulates the logic to call MCP tools remotely.close_multiple_mcp_toolcall_sessions: Cleans up MCP tool call sessions.
Authentication:
flask_login.current_userand@login_requiredprotect endpoints to authenticated users.
Visual Diagram
classDiagram
class MCPServerService {
+get_servers(user_id, mcp_ids, offset, limit, orderby, desc, keywords)
+get_or_none(id, tenant_id)
+get_by_name_and_tenant(name, tenant_id)
+get_by_id(id)
+insert(**kwargs)
+filter_update(filters, data)
+delete_by_ids(mcp_ids)
}
class TenantService {
+get_by_id(id)
}
class MCPServer {
+id: str
+name: str
+url: str
+server_type: str
+variables: dict
+headers: dict
+to_dict()
}
class MCPToolCallSession {
+__init__(mcp_server, variables)
+get_tools(timeout)
+tool_call(tool_name, arguments, timeout)
}
class FlaskEndpoints {
+list_mcp()
+detail()
+create()
+update()
+rm()
+import_multiple()
+export_multiple()
+list_tools()
+test_tool()
+cache_tool()
+test_mcp()
}
FlaskEndpoints --> MCPServerService : uses
FlaskEndpoints --> TenantService : uses
FlaskEndpoints --> MCPServer : uses
FlaskEndpoints --> MCPToolCallSession : uses
Summary
mcp_server_app.py is a critical backend module for managing MCP servers in InfiniFlow. It provides robust REST API endpoints to create, read, update, delete, import/export MCP servers, manage their tools, and test connections. The module integrates tightly with database services, authentication, and a specialized tool calling session to interact with MCP server toolsets, while ensuring tenant isolation and input validation.
This module serves as the bridge between frontend MCP server management UI and the underlying MCP server infrastructure and metadata.