Skip to main content

mcp_stdio_proxy/model/
mcp_config.rs

1use std::str::FromStr;
2
3use anyhow::{Context, Result};
4use serde::{Deserialize, Serialize};
5
6use super::{McpProtocol, mcp_router_model::McpServerConfig};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct McpConfig {
10    //mcp_id
11    #[serde(rename = "mcpId")]
12    pub mcp_id: String,
13    //mcp_json_config,可能没有
14    #[serde(rename = "mcpJsonConfig")]
15    pub mcp_json_config: Option<String>,
16    //mcp类型,默认为持续运行
17    #[serde(default = "default_mcp_type", rename = "mcpType")]
18    pub mcp_type: McpType,
19    //客户端协议(用于暴露给客户端的API接口类型)
20    #[serde(default = "default_mcp_protocol", rename = "clientProtocol")]
21    pub client_protocol: McpProtocol,
22    // 解析后的服务器配置(可选)
23    #[serde(skip_serializing, skip_deserializing)]
24    pub server_config: Option<McpServerConfig>,
25}
26
27fn default_mcp_protocol() -> McpProtocol {
28    McpProtocol::Sse
29}
30
31fn default_mcp_type() -> McpType {
32    McpType::OneShot
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize, Default)]
36pub enum McpType {
37    // 持续运行
38    Persistent,
39    // 一次性任务
40    #[default]
41    OneShot,
42}
43
44impl FromStr for McpType {
45    type Err = anyhow::Error;
46
47    fn from_str(s: &str) -> Result<Self, Self::Err> {
48        match s {
49            "persistent" => Ok(McpType::Persistent),
50            "oneShot" => Ok(McpType::OneShot),
51            _ => Err(anyhow::anyhow!("无效的 MCP 类型: {}", s)),
52        }
53    }
54}
55
56impl McpConfig {
57    pub fn new(
58        mcp_id: String,
59        mcp_json_config: Option<String>,
60        mcp_type: McpType,
61        client_protocol: McpProtocol,
62    ) -> Self {
63        Self {
64            mcp_id,
65            mcp_json_config,
66            mcp_type,
67            client_protocol,
68            server_config: None,
69        }
70    }
71
72    pub fn from_json(json: &str) -> Result<Self> {
73        let config: McpConfig = serde_json::from_str(json)?;
74        Ok(config)
75    }
76
77    /// 从 JSON 字符串创建并解析服务器配置
78    pub fn from_json_with_server(
79        mcp_id: String,
80        mcp_json_config: String,
81        mcp_type: McpType,
82        client_protocol: McpProtocol,
83    ) -> Result<Self> {
84        let mcp_json_server_parameters =
85            crate::model::McpJsonServerParameters::from(mcp_json_config.clone());
86        let server_config = mcp_json_server_parameters
87            .try_get_first_mcp_server()
88            .context("Failed to parse MCP server config")?;
89
90        Ok(Self {
91            mcp_id,
92            mcp_json_config: Some(mcp_json_config),
93            mcp_type,
94            client_protocol,
95            server_config: Some(server_config),
96        })
97    }
98}