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

作者:API传播员 · 2025-10-21 · 阅读时间:5分钟

Dolphin-MCP 是一个开源实现,扩展了 Anthropic 的模型上下文协议(MCP),支持多种语言模型(除 Claude 外)。通过 Dolphin-MCP,开发者可以利用 MCP 架构高效管理 GPT 模型的上下文和工具执行能力。本文将带您逐步了解安装、配置、基础使用及高级优化。


一. 技术愿景

Dolphin-MCP 作为 MCP 协议与 LLM API 的转换层,主要功能包括:

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

二. 先决条件

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

  • 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
  1. 创建并激活虚拟环境
  • Windows
python -m venv venv
venvScriptsactivate
  • macOS/Linux
python3 -m venv venv
source venv/bin/activate
  1. 安装依赖项
pip install -r requirements.txt
  1. 以开发模式安装
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:简单对话

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:使用工具(Web 搜索 + 代码执行)

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("""
您是一名 AI 助手,可以访问以下工具:
- Web_Search:在互联网上搜索信息
- Code_Execution:安全执行 Python 代码
""")

response = conversation.add_user_message("纽约天气如何?以及 Python 如何计算阶乘?")
print(response.content)
print("工具执行结果:")
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"
  }
}

七. 自定义工具示例:计算器

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}
            return str(eval(expression, {"__builtins__": {}}, safe_env))
        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())

八. 性能优化

  • 使用异步连接池管理多会话
  • 调整请求超时时间和连接池大小
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 为开发者提供了灵活、开源的 MCP 与 OpenAI 模型集成方案,支持多 LLM 提供商,实现一致接口并扩展工具能力。按照本指南,您可以快速上手并充分利用 GPT 系列模型进行高级应用开发。


原文链接: Dolphin-MCP 与 OpenAI API 集成指南