Using MCP Servers with OpenRouter
使用 OpenRouter 的 MCP 服务器
MCP servers are a popular way of providing LLMs with tool calling abilities, and are an alternative to using OpenAI-compatible tool calling.
MCP 服务器是为 LLM 提供工具调用能力的一种流行方式,也是使用 OpenAI 兼容工具调用的一种替代方法。
By converting MCP (Anthropic) tool definitions to OpenAI-compatible tool definitions, you can use MCP servers with OpenRouter.
通过将 MCP(Anthropic)工具定义转换为与 OpenAI 兼容的工具定义,您可以在 OpenRouter 中使用 MCP 服务器。
In this example, we’ll use Anthropic’s MCP client SDK to interact with the File System MCP, all with OpenRouter under the hood.
在本示例中,我们将使用 Anthropic 的 MCP 客户端 SDK 与文件系统 MCP 进行交互,所有这些都在引擎盖下使用 OpenRouter。
Note that interacting with MCP servers is more complex than calling a REST
endpoint. The MCP protocol is stateful and requires session management. The
example below uses the MCP client SDK, but is still somewhat complex.
请注意,与 MCP 服务器交互比调用 REST 端点更为复杂。MCP 协议是有状态的,需要会话管理。下面的示例使用了 MCP 客户端 SDK,但仍然有些复杂。
First, some setup. In order to run this you will need to pip install the packages, and create a .env
file with OPENAI_API_KEY set. This example also assumes the directory /Applications
exists.
首先是一些设置。要运行此示例,您需要通过 pip 安装软件包,并创建一个设置了 OPENAI_API_KEY 的 .env
文件。本示例还假设 /Applications
目录存在。
Next, our helper function to convert MCP tool definitions to OpenAI tool definitions:
接下来,我们将使用辅助函数将 MCP 工具定义转换为 OpenAI 工具定义:
And, the MCP client itself; a regrettable ~100 lines of code. Note that the SERVER_CONFIG is hard-coded into the client, but of course could be parameterized for other MCP servers.
还有,MCP 客户端本身;令人遗憾的是,它只有 ~100 行代码。请注意,SERVER_CONFIG 是硬编码到客户端中的,但当然也可以为其他 MCP 服务器设置参数。
Assembling all of the above code into mcp-client.py, you get a client that behaves as follows (some outputs truncated for brevity):
将上述代码全部编入 mcp-client.py,就能得到如下客户端(为简洁起见,部分输出被截断):