一次网关迁移中的 MCP 实践与理解

一次网关迁移中的 MCP 实践与理解

Ingress Nginx 退役 的消息去年(2025)就出了,我们就在考虑公司网关的迁移方案。Kubernetes 对于网关下一代的设计是 Gateway API,恰好阿里云的公众号也经常发布关于 Higress 开源产品的内容,声称其不仅是传统微服务网关,也是新时代的 AI 网关(对于 MCP 协议的更新支持很快),从 ingress-nginx 迁移也很方便(同时支持 Ingress 和 GateWay API),基于此我就尝试把原有的路由修改到 higress 上。

在 k8s 上部署服务并不是难事,如果服务器能直接连接外网,使用 helm 下载简单配置并运行即可;即使不能连接外网,load 加载指定版本镜像,写 yaml 创建 ns、sts、deploy 也是可以的。

不过这些不是本篇内容的重点,部署好 higress 后,我发现貌似还是需要我进 higress-console 对应的 web 页面添加路由。

image-20261023113017792

我司服务器集群的 ns 都有几十个,只考虑基础的每个 ns 里 web 和 gateway 两个 svc,也需要我创建几十条路由,更别提还有一些额外的情况:如音视频服务需要 websocket,xxl-job 等独立服务也需要暴露端口访问。

于是我就找有没有更简单的方案,发现有人去年写了一个 higress-ops-mcp-server 的项目,项目使用 fastmcp 封装了对于 higress 中路由、服务的基本操作,并用 langchain 创建出 agent 支持用户使用自然语言对 higress 进行操作。

MCP 是什么

MCP 解决了AI系统面临的一个根本问题:数据孤岛。即使最先进的AI模型也受限于与外部数据的隔离,难以访问存储在内容库、业务工具和开发环境中的信息。MCP提供了一个统一的协议,替代了分散的集成方式,使AI系统能够更简单、更可靠地访问所需数据。

举个例子:用户问 Agent 我这个项目的 Redis 集群里是否存在 bigkey,Agent 没办法直接连 redis,它会给出一些方案,比如执行下 keys user* 把返回结果贴回来等等,或者用户把 redis 的 host、username、password 给 Agent,Agent 自己写 py 脚本去连接。总之 Agent 获取外部系统信息的手段有限,MCP 可以让 Agent 访问外部的系统。

MCP 里有 Host、Server、Client 几个核心部分,Host 是 Agent 应用本体(Claude、WorkBuddy等),Server 则是指提供能力的外部程序,Client 是 Host 内部维护的与 MCP Server 的连接。Server 本身具备管理资源的能力,Host 通过内部的 Client 跟 Server 通信,Server 根据通信内容操作 Resource。

我们常说的 Stdio、Streamable HTTP 则是指 Client 和 Server 通信的方式。

Stdio 模式下,Host 通过 uv、npx、python 等方式启动一个 server,由于都是在本机,可以使用本地通信。如下图所示:

img

Streamable HTTP 模式下,Server 独立部署(我们平时的 Web 应用 MCP 化后就是一个远程的 MCP Server),Agent 应用创建的 Client 远程调用 MCP Server,如下图所示:

img

需要注意的一点是: MCP 不在乎 Server 如何管理 Resource,即使是 stdio 模式下 server 也可以通过 http 调用 resource 的 api。

写 MCP 并接入 WorkBuddy

目前 MCP 已经是业界标准了,协议内容也已经更新了几版, Claude、Codex、WorkBuddy 都有适配,一方面没有必要再写 langgraph new agent 测试了,另一方面项目的依赖版本也比较早。

于是我重写了 higress-mcp-server 并配置到了 WorkBuddy 上:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
"mcpServers": {
"higress": {
"command": "uv",
"args": [
"run", "--directory", "D:\\Code\\WorkSpace\\Agent\\personal-mcp-repo\\higress-mcp-server",
"higress-mcp-server",
"--higress-url", "http://192.168.41.81:32573"
],
"env": {
"HIGRESS_USERNAME": "admin",
"HIGRESS_PASSWORD": "your-password"
}
}
}
}

这是用上面提到的 Stdio 通信方式实现的,下面是运行效果:

image-20261023132618685

那么接下来我只需要把原 ingress-nginx 的配置文件导出,让 agent 按照原配置文件在 higress 上添加对应的 route 就行了~

其实 MCP 的编写也很简单,就像我们在项目中调用其他服务一样,一般会先写一个对方平台的 client,并在这个 client 里封装好请求时的 auth 信息和 response 解析方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
class HigressClient:
"""Synchronous Higress Console API client with Basic Auth."""

def __init__(self, config: Config):
self._client = httpx.Client(
base_url=config.higress_url.rstrip("/"),
auth=self._build_auth(config),
timeout=REQUEST_TIMEOUT_SECONDS,
)

@staticmethod
def _build_auth(config: Config) -> httpx.Auth:
"""Single auth injection point. Swap to session/cookie auth here in a future version."""
return httpx.BasicAuth(config.username, config.password)

def _process_response(self, response: httpx.Response, method: str, path: str) -> dict[str, Any]:
"""Raise on HTTP errors and success=false; return the data field (or full body)."""
response.raise_for_status()
response_json = response.json()

if response_json.get("success") is False:
error_msg = response_json.get("message", "Unknown API error")
raise ValueError(f"Request API error for {method} {path}: {error_msg}")

return response_json.get("data", response_json)

def get(self, path: str) -> dict[str, Any]:
"""GET a Console API path and return the unwrapped data."""
response = self._client.get(path)
return self._process_response(response, "GET", path)

def post(self, path: str, data: dict[str, Any]) -> dict[str, Any]:
"""POST JSON to a Console API path and return the unwrapped data."""
response = self._client.post(path, json=data)
return self._process_response(response, "POST", path)

def put(self, path: str, data: dict[str, Any]) -> dict[str, Any]:
"""PUT JSON to a Console API path and return the unwrapped data."""
response = self._client.put(path, json=data)
return self._process_response(response, "PUT", path)

# ---- Routes ----

def list_routes(self) -> dict[str, Any] | list[dict[str, Any]]:
"""List all routes."""
return self.get("/v1/routes")

def get_route(self, name: str) -> dict[str, Any] | list[dict[str, Any]]:
"""Get one route by name."""
return self.get(f"/v1/routes/{name}")

def add_route(self, configurations: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:
"""Create a route. Requires name, path and services in configurations."""
if not configurations.get("name"):
raise ValueError("Route name is required")
if not configurations.get("path"):
raise ValueError("Route path configuration is required")
if not configurations.get("services"):
raise ValueError("At least one service is required for the route")
return self.post("/v1/routes", configurations)

def update_route(self, name: str, configurations: dict[str, Any]) -> dict[str, Any] | list[dict[str, Any]]:
"""Update a route by merging configurations into the current ones (avoids overwriting)."""
if not name:
raise ValueError("Route name is required")
route_config = self.get_route(name)
if configurations:
route_config.update(configurations)
return self.put(f"/v1/routes/{name}", route_config)

在真正的对 Agent 暴露的 api 里封装上 client 里的函数(如下面的 list_routes tool 其实就是调了上面 client 的 list_routes 函数):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
logger = logging.getLogger("higress-mcp-server")


def _setup_logging() -> None:
"""Log to stderr only — stdout is the stdio transport channel."""
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
root = logging.getLogger()
root.handlers = [handler]
root.setLevel(logging.INFO)


def _run(call) -> str:
"""Execute a client call, converting any failure into an "Error: ..." text result."""
try:
return json.dumps(call(), ensure_ascii=False)
except (ValueError, httpx.HTTPStatusError, httpx.HTTPError) as e:
logger.warning("Tool call failed: %s", e)
return f"Error: {e}"
except Exception as e: # noqa: BLE001 - tools must never crash the MCP server
logger.exception("Unexpected tool failure")
return f"Error: {e}"


def create_mcp_server(client: HigressClient) -> FastMCP:
"""Create a FastMCP server with all Higress operation tools registered."""
_setup_logging()
mcp = FastMCP("higress-mcp-server")

@mcp.tool
def list_routes() -> str:
"""List all routes configured on the Higress gateway."""
return _run(client.list_routes)

@mcp.tool
def get_route(name: str) -> str:
"""Get detailed configuration of a route by its name."""
return _run(lambda: client.get_route(name))

@mcp.tool
def add_route(configurations: dict[str, Any]) -> str:
"""Create a route. configurations must contain: name (str), path (str), services (list)."""
return _run(lambda: client.add_route(configurations))

@mcp.tool
def update_route(name: str, configurations: dict[str, Any]) -> str:
"""Update an existing route; configurations are merged into the current ones."""
return _run(lambda: client.update_route(name, configurations))

看代码其实和我们正常调用一个三方平台的方式(或者 Function Calling)一样,为什么还要多此一举用 MCP 封装呢?

我认为有以下原因:

  1. 易维护,可移植,可复用:MCP 是 Agent 业界规范,Claude 换 Codex、Hermes 都可以兼容,而且如果有其它平台需要对接 Higress,可以复用而无需维护多处;
  2. 解耦:MCP 解决的是 Agent 如何发现、连接、执行工具的问题,而 Function Calling 解决的是 Agent 如何表达它需要进行工具调用的问题(输出一个 json 表达要调用的工具和参数)。从这个层面看 MCP 更像是 Function Calling 的下游,单独使用 MCP 解耦了 Agent 和业务平台。

有的人可能以为 Stdio 和 Streamable HTTP 是 Server 和 Resource 的通信方式,其实不然,这是 MCP Client 和 MCP Server 的通信方式,中间还有过 SSE 方式,由于不符合传统 请求/响应 的共识(两个端点,一个端点接收消息返回请求已接收,但响应是从 SSE 长连接返回的。传统的都是发请求返回本次请求的响应内容)而且不利于服务提供方的水平拓展(需要粘性会话,因为维持了 SSE 长连接),目前已经舍弃了。


一次网关迁移中的 MCP 实践与理解
https://zhuwenjie0716.github.io/2026/10/26/一次网关迁移中的-MCP-实践与理解/
作者
Wenjie Zhu
发布于
2026年10月26日
许可协议