Dolphin-MCP 技术指南:OpenAI API 集成与高级使用

作者:API传播员 · 2025-10-21 · 阅读时间:5分钟
Dolphin-MCP 是一个开源实现,扩展了 Anthropic 的模型上下文协议,支持多种语言模型。本指南详细介绍了如何配置和使用 Dolphin-MCP 与 OpenAI API 集成,包括安装步骤、配置方法、基本和高级使用示例,以及性能优化技巧,帮助开发者充分利用 GPT 模型的能力。

简介

Dolphin-MCP 是一个开源实现,它扩展了 Claude 之外的多种语言模型。本技术指南将向您展示如何配置和使用 Dolphin-MCP,特别是结合 OpenAI API,使您能够通过 MCP 架构充分利用 GPT 模型的能力。


技术愿景

Dolphin-MCP 作为 MCP 规范与多个 LLM API 之间的转换层,主要实现以下功能:

  • 将 MCP 协议消息转换为 OpenAI API 格式。
  • 处理不同模型之间的令牌映射差异。
  • 管理对话的状态和历史记录。
  • 提供与模型无关的工具执行能力。

先决条件

在开始之前,请确保您具备以下条件:

  • Python 3.8 或更高版本。
  • PIP(Python 包管理器)。
  • 有效的 OpenAI API 密钥。
  • 已安装 Git。
  • 对 LLM 和 API 概念有基本了解。

安装步骤

  1. 克隆 Dolphin-MCP 仓库:

    git clone https://github.com/cognitivecomputations/dolphin-mcp.git
    cd dolphin-mcp
  2. 创建虚拟环境并激活:

    • 在 Windows 上:

      python -m venv venv
      venvScriptsactivate
    • 在 macOS/Linux 上:

      python3 -m venv venv
      source venv/bin/activate
  3. 安装依赖项:

    pip install -r requirements.txt
  4. 以开发模式安装包:

    pip install -e .

配置

1. 环境变量配置

在项目根目录中创建一个 .env 文件,内容如下:

openai_api_key=sk-your-openai-api-key
mcp_model=gpt-4-0125-preview
mcp_provider=openai

2. 创建配置文件

创建一个 config.json 文件,内容如下:

{
  "provider": "OpenAI",
  "model_settings": {
    "model": "gpt-4-0125-preview",
    "temperature": 0.7,
    "max_tokens": 2048
  },
  "api_config": {
    "api_key": "sk-your-openai-api-key",
    "base_url": "https://api.openai.com/v1",
    "timeout": 120
  }
}

基本使用示例

示例 1:简单对话

以下代码展示了如何使用 Dolphin-MCP 创建一个简单的对话:

from dolphin_mcp import DolphinMCP

# 初始化客户端
mcp_client = DolphinMCP.from_config('./config.json')# 创建对话
conversation = mcp_client.create_conversation()# 添加系统消息
conversation.add_system_message("您是一个有用的人工智能助手,专门从事 Python 编程。")# 发送用户消息并获取响应
response = conversation.add_user_message("如何在 Python 中实现二叉搜索树?")# 打印响应
print(response.content)

示例 2:使用 OpenAI 工具

以下代码展示了如何注册工具并在对话中使用这些工具:

from dolphin_mcp import DolphinMCP
from dolphin_mcp.tools import WebSearchTool, CodeExecutionTool

# 初始化客户端
mcp_client = DolphinMCP.from_config('./config.json')# 注册工具
mcp_client.register_tool(WebSearchTool(api_key="your-web-search-api-key"))
mcp_client.register_tool(CodeExecutionTool())# 创建对话并启用工具
conversation = mcp_client.create_conversation()
conversation.add_system_message("""
您是一名人工智能助手,可以访问以下工具:
- Web_Search:在互联网上搜索当前信息
- Code_Execution:在隔离环境中安全运行 Python 代码
请在适当情况下使用这些工具提供准确和有用的答案。
""")# 用户查询
response = conversation.add_user_message("纽约目前的天气如何?此外,如何在 Python 中计算数字的阶乘?")# 打印响应
print(response.content)# 打印工具执行结果
print("n工具执行结果:")
for tool_name, tool_result in response.tool_results.items():
    print(f"{tool_name}: {tool_result}")

高级配置

使用与 OpenAI 兼容的端点

如果您希望使用与 自托管模型),可以修改配置文件如下:

{
  "provider": "OpenAI",
  "model_settings": {
    "model": "your-custom-model",
    "temperature": 0.7,
    "max_tokens": 2048
  },
  "api_config": {
    "api_key": "your-api-key",
    "base_url": "https://your-custom-endpoint.com/v1",
    "api_version": "2023-07-01-preview",
    "api_type": "azure"
  }
}

实现自定义工具

Dolphin-MCP 支持为 OpenAI 模型创建自定义工具。以下是实现一个简单计算器工具的示例:

from dolphin_mcp.tools import BaseTool
import math

class CalculatorTool(BaseTool):
    name = "Calculator"
    description = "执行数学计算"    async def execute(self, expression: str):
        try:# 创建安全的数学环境
            safe_env = {
                "sqrt": math.sqrt,
                "sin": math.sin,
                "cos": math.cos,
                "tan": math.tan,
                "pi": math.pi,
                "e": math.e
            }# 计算表达式
            result = eval(expression, {"__builtins__": {}}, safe_env)
            return str(result)
        except Exception as e:
            return f"计算错误:{str(e)}"    @property
    def parameters(self):
        return {
            "type": "object",
            "properties": {
                "expression": {
                    "type": "string",
                    "description": "要计算的数学表达式"
                }
            },
            "required": ["expression"]
        }# 使用示例
mcp_client = DolphinMCP.from_config('./config.json')
mcp_client.register_tool(CalculatorTool())

性能优化

在生产环境中,您可以通过以下方式优化 Dolphin-MCP 的性能:

  • 使用异步连接池管理多个会话。
  • 调整请求超时时间和连接池大小。

示例代码:

from dolphin_mcp import DolphinMCP
import aiohttp
import asyncio

async def optimize_mcp_usage():
    async with aiohttp.ClientSession() as session:
        mcp_client = DolphinMCP.from_config(
            './config.json',
            session=session,
            request_timeout=60,
            connection_pool_size=10
        )        tasks = []
        for i in range(5):
            conversation = mcp_client.create_conversation()
            conversation.add_system_message("您是一个有用的助手。")
            tasks.append(conversation.add_user_message_async(f"问题 {i}: 什么是机器学习?"))        responses = await asyncio.gather(*tasks)
        for i, response in enumerate(responses):
            print(f"响应 {i}: {response.content[:100]}...")# 运行优化
asyncio.run(optimize_mcp_usage())

结论

Dolphin-MCP 提供了一种灵活且开源的方式,将 OpenAI 模型与 MCP 协议集成。通过该工具,开发者可以在不同 LLM 提供商之间实现一致的接口,摆脱对单一供应商的依赖。按照本指南的步骤,您可以快速上手并充分利用 GPT 模型的强大功能。

原文链接: http://anakin.ai/de/blog/how-to-use-mcp-with-openais-api-using-dolphin-mcp-es/