3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MCPでMySQLに接続しAI Agentを作ってみる

Posted at

実現したいこと

  • ローカルのMySQL DBにAI Client (Claude Desktop)を接続したい
  • 接続の方法はMCP(Model Context Protocol)を利用したい

実現方法

  • MCPサーバーはmysql_mcp_serverを利用
  • uvを利用してローカルに仮想Python実行環境を構築
  • python v3.13.2を利用

成果物

  • Claudeとの会話キャプチャ: DBの内容を踏まえて回答してくれる
    image.png
    image.png

実現方法

  1. mysql_mcp_serverをローカルにクローン

    powershell
    git clone https://github.com/designcomputer/mysql_mcp_server.git
    
  2. python仮想環境を構築

    powershell
    python -m venv venv
    
  3. 仮想環境をアクティベート

    powershell
    venv\Scripts\activate
    
  4. MCP接続に必要なライブラリを仮想環境にインストール

    powershell
    pip install -r requirements.txt
    

    requrement.txtの中身:

    mcp>=1.0.0
    mysql-connector-python>=9.1.0
    
  5. 環境変数としてMySQLへの接続情報を設定(以下はWindows例)

    powershell
    (venv) PS mysql_mcp_server> $env:MYSQL_USER="<DB user name>"   
    (venv) PS mysql_mcp_server> $env:MYSQL_PASSWORD="<user passsword>" 
    (venv) PS mysql_mcp_server> $env:MYSQL_DATABASE="<database name>"  
    
  6. MCPサーバの起動

    powershell
    uv --directory <Path to mysql_mcp_server folder> run server.py
    
  7. Claude DesktopのConfigファイルにMySQLへの接続情報を追加

    claude_desktop_config.json
    {
        "mcpServers": {
            "mysql": {
                "command": "uv",
                "args": [
                    "--directory", 
                    "Path to /mysql_mcp_server/ folder",
                    "run",
                    "server.py"
                ],
                "env": {
                    "MYSQL_HOST": "<MySQL hostname>",
                    "MYSQL_PORT": "3306",
                    "MYSQL_USER": "<DB user name>",
                    "MYSQL_PASSWORD": "<user passsword>",
                    "MYSQL_DATABASE": "<database name>"
                }
            }
        }
    }
    
  8. Claude Desktop Appを起動する。トンカチのマークを選択し、今回追加したexecute_sqlが表示されていればOK。
    image.png

    image.png

ハマりポイント

  • 仮想Python環境にも環境変数としてDBへの接続情報を入力することを忘れていた。
  • Claude Desktop App側のConfigファイルを修正したら一度アプリを終了して再度立ち上げる必要があった。
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?