dolphin-mcp

repository·main·Indexed 19 days ago

https://github.com/quixiai/dolphin-mcp

A flexible Python library and CLI tool for interacting with Model Context Protocol (MCP) servers. It enables natural language interaction by bridging LLMs (OpenAI, Anthropic, Ollama, LMStudio) with MCP servers to perform tool-based tasks and data manipulation. Features include the dolphin-mcp-cli for terminal-based queries, the MCPAgent for orchestrating multiple servers, and support for both stdio-based (MCPClient) and SSE-based (SSEMCPClient) connections.

Tokens
8.1K
Snippets
25
Records
32
Agent score
67%

What's inside dolphin-mcp

  1. How Dolphin MCP works

    main

    Dolphin MCP acts as a bridge between LLMs and MCP servers. The workflow is as follows:

    1. Configuration: The client loads mcp_config.json and connects to all specified MCP servers.
    2. Tool Discovery: It retrieves the list of available tools from every connected server.
    3. Querying: The user's query and the list of available tools are sent to the LLM (OpenAI, Anthropic, Ollama, or LMStudio).
    4. Tool Execution: If the LLM requests a tool call, the library routes the request to the correct MCP server, executes it, and returns the result to the LLM.
    5. Response: This loop continues until the LLM can provide a final conversational response based on the tool outputs.
  2. Install Dolphin MCP

    main

    You can install Dolphin MCP either via PyPI (recommended) or from source.

    Install from PyPI

    Install the library and the dolphin-mcp-cli command-line tool using pip:

    pip install dolphin-mcp

    Install from Source

    1. Clone the repository:
      git clone https://github.com/cognitivecomputations/dolphin-mcp.git
      cd dolphin-mcp
    2. Install in development mode:
      pip install -e .
    3. Set up environment variables:
      cp .env.example .env
      Edit the .env file to include your OPENAI_API_KEY.
    4. (Optional) Set up the demo SQLite database:
      python setup_db.py
  3. Configure MCP Servers via mcp_config.json

    main

    To connect to MCP servers, define them in a mcp_config.json file. Each server entry requires a command and can include args and env variables.

    Example structure:

    {
      "mcpServers": {
        "server1": {
          "command": "command-to-start-server",
          "args": ["arg1", "arg2"],
          "env": {
            "ENV_VAR1": "value1"
          }
        }
      }
    }
    {
      "mcpServers": {
        "server1": {
          "command": "command-to-start-server",
          "args": ["arg1", "arg2"],
          "env": {
            "ENV_VAR1": "value1",
            "ENV_VAR2": "value2"
          }
        },
        "server2": {
          "command": "another-server-command",
          "args": ["--option", "value"]
        }
      }
    }
  4. How tool use works with the LMStudio provider

    main

    The LMStudio provider enables tool use by wrapping MCP function definitions into Python functions that the LM Studio SDK can execute via model.act().

    Workflow

    1. Function Wrapping: The provider takes all_functions (JSON schemas) and dynamically creates Python function wrappers using create_python_function_standard_docstring.
    2. Name Parsing: It expects MCP function names to follow a server_tool format (e.g., weather_get_forecast). It splits these to provide a simplified name to LM Studio while retaining the full name for Dolphin MCP tracking.
    3. Execution: If functions are provided, the provider calls model.act(). This method handles the loop of model reasoning and tool execution.
    4. Capture: As tools are called, the dynamic wrappers capture the arguments and generate a tool_call object (including a unique id and JSON-stringified arguments) which is appended to a shared list returned to the user.
    5. Fallback: If no valid functions can be prepared, the provider falls back to regular chat inference using model.respond().
  5. Configure LLM Providers via .env

    main

    Dolphin MCP uses a .env file to manage LLM provider credentials and settings. The following keys are supported:

    • OPENAI_API_KEY: Your OpenAI API key.
    • OPENAI_MODEL: The model to use (e.g., gpt-4o).
    • OPENAI_BASE_URL: (Optional) A custom base URL for OpenAI-compatible APIs. Uncomment this in your .env file to modify it.
    OPENAI_API_KEY=your_openai_api_key_here
    OPENAI_MODEL=gpt-4o
    # OPENAI_BASE_URL=https://api.openai.com/v1
  6. Use dolphin-mcp-cli with Filesystem and Fetch MCP

    main

    You can combine multiple MCP servers (like filesystem and fetch) to perform complex tasks that require reading local files and retrieving web content.

    In this workflow, the model reads a local text file containing a list of stocks, fetches recent news from a URL, and then analyzes the news to provide investment advice based on the sentiment found in the fetched content.

    dolphin-mcp-cli --mcp-config examples/filesystem-fetch-mcp.json --model gpt-4o "Read ./examples/stocklist.txt and fetch https://finance.yahoo.com/topic/stock-market-news/. If there is positive news about any of the stocks in the list, advise me to buy that stock.  if there is negative news about any of the stocks in the list, advise me to sell that stock."
  7. Use dolphin-mcp-cli with SQLite MCP

    main

    You can use the dolphin-mcp-cli to interact with a SQLite database by providing an MCP configuration file. This allows the model to explore tables, run queries, and perform data analysis.

    In the example below, the CLI is used to explore a database and generate a story based on a random row retrieved from the dolphin_species table.

    dolphin-mcp-cli --mcp-config examples/sqlite-mcp.json --model dolphin "Explore the database, and choose one random row - and write a story about it"
  8. Use run_interaction in Python

    main

    You can integrate Dolphin MCP into your own Python applications using the run_interaction function. This function is asynchronous and handles connecting to MCP servers, tool discovery, and LLM interaction.

    Parameters:

    • user_query (str): The natural language query.
    • model_name (str, optional): The name of the model to use.
    • config_path (str, optional): Path to the MCP configuration file (defaults to mcp_config.json).
    • quiet_mode (bool, optional): Whether to suppress intermediate output (defaults to False).
    import asyncio
    from dolphin_mcp import run_interaction
    
    async def main():
        result = await run_interaction(
            user_query="What dolphin species are endangered?",
            model_name="gpt-4o",
            config_path="mcp_config.json",
            quiet_mode=False
        )
        print(result)
    
    asyncio.run(main())
  9. Configure LMStudio model selection

    main

    When using the LMStudio provider, you can specify which model to use via the model_cfg dictionary passed to generate_with_lmstudio.

    • Specific Model: Provide the name of the model as defined in LM Studio using the model key.
    • Default Model: If the model key is omitted or set to None, the provider will attempt to use the default model currently selected in your LM Studio instance.
    # To use a specific model
    model_cfg = {"model": "mistral-7b-instruct"}
    
    # To use the default LMStudio model
    model_cfg = {}
  10. Configure Anthropic provider via environment variables

    main

    The Anthropic provider in Dolphin MCP can be tuned using the following environment variables:

    • ANTHROPIC_RATE_LIMIT_SECONDS: Sets the minimum delay between requests in seconds. Defaults to 60.
    • ANTHROPIC_CACHING_ENABLED: Enables or disables Anthropic's ephemeral caching. Defaults to true.
    • ANTHROPIC_API_KEY: The API key for your Anthropic account.
  11. Configure the OpenAI provider

    main

    When using the OpenAI provider, you can control the connection and generation parameters via the model_cfg dictionary or environment variables.

    Configuration Keys (model_cfg)

    KeyTypeDescription
    modelstrRequired. The OpenAI model name (e.g., gpt-4o).
    apiKeystrThe API key. If not provided, the provider looks for the OPENAI_API_KEY environment variable.
    apiBasestrThe base URL for the OpenAI API. Use this if you are using a proxy or a compatible alternative service.
    temperaturefloatControls randomness.
    top_pfloatNucleus sampling parameter.
    max_tokensintLimits the length of the generated response.

    Environment Variables

    • OPENAI_API_KEY: Used as a fallback if apiKey is not specified in the model_cfg.
  12. Configure Azure OpenAI environment variables

    main

    To use the Azure OpenAI provider, you must set the following environment variables. The provider requires these to construct the API request URL and authenticate with the Azure endpoint.

    Required environment variables:

    • AZURE_OPENAI_API_KEY: Your Azure OpenAI API key.
    • AZURE_OPENAI_API_ENDPOINT: The base URL for your Azure OpenAI resource (e.g., https://your-resource.openai.azure.com/).
    • AZURE_OPENAI_DEPLOYMENT_ID: The specific deployment ID of the model you wish to use.
    • AZURE_OPENAI_API_VERSION: The API version string (e.g., 2023-05-15).