# 优刻得模型服务平台支持MCP（含快速上手教程）

> 作者/来源: UCloud官方/历史归档
> 发布时间: 2025-04-10T00:59:00.000Z
> 分类: AI专区
> 标签: MCP协议, 模型服务平台, 快速上手
> 原文链接: http://117.50.162.249:3000/yun/articles/2637

---

数据是AI大模型的 “燃料”，当MCP协议成为事实标准后，更丰富的数据能够让模型学习到更多的知识和模式，从而提升大模型的性能和表现。

**近日，优刻得UModelVerse模型服务平台通过升级服务能力，接入QwQ模型****并提供Function Call的原生能力，正式支持了MCP协议，以标准化的接口和交互方式，大大简化了模型与数据源的连接流程。**

**什么是MCP？**

Anthropic开源的MCP（Model Context Protocol）协议，为连接AI系统与数据源提供了一个通用的、开放的标准，成功用单一协议取代了以往碎片化的集成方式，成为全球AI开发者热议的焦点。

![](https://ucloud-blog.cn-bj.ufileos.com/articles/wechat/images/494efaa7dd35fc9e.png)

*MCP协议架构主要包含数据传输层、接口适配层、安全认证层等关键组件，各组件协同工作，确保数据交互既高效又安全。

**简单来说，MCP是一个为LLM搭建起与外部数据源及工具直接对话的桥梁，聚焦于解决当前AI模型发展深受制约的数据孤岛难题。**MCP要求通信格式严格遵循JSON-RPC2.0标准，让不同的数据服务商、工具提供者以及前端应用，在与LLM沟通时能够畅通无阻。从此，LLM仿佛拥有了一个 “万能转接头”，只要各类资源能够符合MCP这套标准，无论是数据、文件系统、开发工具，还是Web和浏览器自动化程序，甚至是各种社区生态能力，都能与LLM实现万物互联，为AI应用赋予强大的协作工作能力。

**使用UModelVerse模型快速接入MCP Server**

MCP server是MCP架构中的关键组件，提供资源（Resources）、工具（Tools）、提示（Prompts）三大功能。这些功能使MCP server能够为AI应用提供丰富的上下文信息和操作能力，从而增强LLM的实用性和灵活性。

为了帮助开发者更好地理解和应用MCP协议，优刻得在此提供一个实现MCP Server的简易示例：

1. 安装nodejs

链接地址🔗：https://nodejs.org/zh-cn

2. 安装必要依赖

pip install mcp

pip install openai

3. 运行代码

以下代码可以作为模版使用，但需注意使用您实际的**UModelVerse平台API_KEY**。

- 我们选择无需密钥即可使用的MCP Server web-search。

- 若您是windows系统，请打开注释# command="cmd.exe", args=["/c", "npx", "-y", "@mzxrai/mcp-webresearch@latest"]

向上滑动查看

import asyncio

import json

from typing import Optional

from contextlib import AsyncExitStack

from openai import OpenAI

from mcp import ClientSession, StdioServerParameters

from mcp.client.stdio import stdio_client

openai_client = OpenAI(

    base_url="https://api.modelverse.cn/v1",  # modelverse的API地址（无需更改）

    api_key="<您的api_key>",  # 控制台创建API Key  https://console.ucloud.cn/modelverse/experience

)

model_name = "Qwen/QwQ-32B"  # 模型名称（无需更改）

class MCPClient:

    def __init__(self):

        """初始化 MCP 客户端"""

        self.exit_stack = AsyncExitStack()

        self.client = openai_client

        # 初始化 client

        self.session: Optional[ClientSession] = None

        self.exit_stack = AsyncExitStack()

    async def connect_to_server(self):

        # 使用无需密钥的MCP Server

        server_params = StdioServerParameters(

            # mac os系统使用下面的命令

            command="npx",

            args=["-y", "@mzxrai/mcp-webresearch@latest"],

            # windows 系统使用下面命令

            # command="cmd.exe", args=["/c", "npx", "-y", "@mzxrai/mcp-webresearch@latest"],

        )

        # 启动 MCP 服务器并建立通信

        stdio_transport = await self.exit_stack.enter_async_context(

            stdio_client(server_params)

        )

        self.stdio, self.write = stdio_transport

        self.session = await self.exit_stack.enter_async_context(

            ClientSession(self.stdio, self.write)

        )

        await self.session.initialize()

        # 列出 MCP 服务器上的工具

        list_tools_resp = await self.session.list_tools()

        list_prompt_resp = await self.session.list_prompts()

        list_resource_resp = await self.session.list_resources()

        self.session.get_prompt

        tools = list_tools_resp.tools

        print(

            "\n已连接到服务器，支持以下tools:",

            [tool.name for tool in tools],

            "以下prompts:",

            [prompt.name for prompt in list_prompt_resp.prompts],

            "以下resources:",

            [resource.name for resource in list_resource_resp.resources],

        )

    async def process_prompt(self, query: str) -> str:

        """

        使用大模型处理查询并调用可用的 MCP 工具 (tool Calling)

        """

        messages = [{"role": "user", "content": query}]

        list_tools_resp = await self.session.list_tools()

        self.session.complete

        available_tools = [

            {

                "type": "function",

                "function": {

                    "name": tool.name,

                    "description": tool.description,

                    "parameters": tool.inputSchema,

                },

            }

            for tool in list_tools_resp.tools

        ]

        resp = self.client.chat.completions.create(

            model=model_name, messages=messages, tools=available_tools

        )

        # 处理返回的内容

        content = resp.choices[0]

        if content.finish_reason == "tool_calls":

            # 如何是需要使用工具，就解析工具

            tool_call = content.message.tool_calls[0]

            tool_name = tool_call.function.name

            tool_args = json.loads(tool_call.function.arguments)

            # 执行工具

            result = await self.session.call_tool(tool_name, tool_args)

            print(f"\n\n[Calling tool {tool_name} with args {tool_args}]\n\n")

            # 将模型返回的调用哪个工具数据和工具执行完成后的数据都存入messages中

            messages.append(

                {

                    "role": "tool",

                    "content": result.content[0].text,

                    "tool_call_id": tool_call.id,

                }

            )

            # 将上面的结果再返回给大模型用于生产最终的结果

            resp = self.client.chat.completions.create(

                messages=messages, model=model_name, tools=available_tools

            )

            return resp.choices[0].message.content

        return content.message.content

    async def chat_loop(self):

        """运行交互式聊天循环"""

        print("\n🤖 MCP Host已启动！输入 'exit' 退出")

        while True:

            try:

                prompt = input("\n你: ").strip()

                if prompt.lower() == "exit":

                    break

                response = await self.process_prompt(prompt)

                print(f"\n🤖 ModelVerse QwQ-32B: {response}")

            except Exception as e:

                print(f"\n⚠️ 发生错误: {str(e)}")

    async def cleanup(self):

        """清理资源"""

        await self.exit_stack.aclose()

async def main():

    client = MCPClient()

    try:

        await client.connect_to_server()

        await client.chat_loop()

    finally:

        await client.cleanup()

if __name__ == "__main__":

    asyncio.run(main())

4. 连接效果

实际用户请求：“请帮我阅读并总结网页-UCloud文档中心（https://docs.ucloud.cn/modelverse/api_doc/chat）”

![](https://ucloud-blog.cn-bj.ufileos.com/articles/wechat/images/32df63338d6f908f.png)

优刻得模型服务平台支持MCP协议后，可进一步降低开发者重复开发的工作量和行业准入门槛，使其能够迅速共享和复用资源，实现AI应用的拓展。

优刻得深耕智算领域，基于技术创新实践降低行业门槛、推动技术融合和解决实际问题，全面契合国家对人工智能和数字经济发展的要求。跟随技术的发展步伐，优刻得将继续秉持创新精神，不断探索、突破，为推动AI发展与国家科技进步贡献更多力量。

如需更多帮助，欢迎扫描下方二维码

联系线上客服咨询指导！