use std::str::FromStr;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use super::{McpProtocol, mcp_router_model::McpServerConfig};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpConfig {
#[serde(rename = "mcpId")]
pub mcp_id: String,
#[serde(rename = "mcpJsonConfig")]
pub mcp_json_config: Option<String>,
#[serde(default = "default_mcp_type", rename = "mcpType")]
pub mcp_type: McpType,
#[serde(default = "default_mcp_protocol", rename = "clientProtocol")]
pub client_protocol: McpProtocol,
#[serde(skip_serializing, skip_deserializing)]
pub server_config: Option<McpServerConfig>,
}
fn default_mcp_protocol() -> McpProtocol {
McpProtocol::Sse
}
fn default_mcp_type() -> McpType {
McpType::OneShot
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, ToSchema)]
pub enum McpType {
Persistent,
#[default]
OneShot,
}
impl FromStr for McpType {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"persistent" => Ok(McpType::Persistent),
"oneShot" => Ok(McpType::OneShot),
_ => Err(anyhow::anyhow!("无效的 MCP 类型: {}", s)),
}
}
}
impl McpConfig {
pub fn new(
mcp_id: String,
mcp_json_config: Option<String>,
mcp_type: McpType,
client_protocol: McpProtocol,
) -> Self {
Self {
mcp_id,
mcp_json_config,
mcp_type,
client_protocol,
server_config: None,
}
}
pub fn from_json(json: &str) -> Result<Self> {
let config: McpConfig = serde_json::from_str(json)?;
Ok(config)
}
pub fn from_json_with_server(
mcp_id: String,
mcp_json_config: String,
mcp_type: McpType,
client_protocol: McpProtocol,
) -> Result<Self> {
let mcp_json_server_parameters =
crate::model::McpJsonServerParameters::from(mcp_json_config.clone());
let server_config = mcp_json_server_parameters
.try_get_first_mcp_server()
.context("Failed to parse MCP server config")?;
Ok(Self {
mcp_id,
mcp_json_config: Some(mcp_json_config),
mcp_type,
client_protocol,
server_config: Some(server_config),
})
}
}