🧞

デジタル庁MCPをCrewAIのAgentから利用してみる

に公開

はじめに

先日デジタル庁が公開したMCPサーバーの実装例 ( https://digital-gov.note.jp/n/n09dfb9fa4e8e )をCrewAIのAgentから利用するサンプルを紹介します。

業務Webアプリ(Pythonサーバー)からMCPを利用することを目指すための第一歩目と思って読んでいただければと思います。
AgentとMCPサーバーの通信プロトコルはstreamable-httpの例です。

ローカルPCで完結します。

システム構成図
システム構成

環境

  • MacOS
  • uv 0.9.7 (0adb44480 2025-10-30)
  • python 3.12.11
  • CrewAI 1.2.1
  • fastmcp 2.13.0.2
  • LLM (Azure OpenAI Serviceなど)

事前準備(MCPサーバーセットアップ)

https://github.com/digital-go-jp/jgrants-mcp-server からソースコードをDLして、ローカルPCで起動できるようにする。手順はREADMEを参照。

環境構築

仮想環境作成

uv venv
source .venv/source/activate

CrewAIインストール

uv tool install crewai

補足: Agent実行時にNo module named 'crewai_tools'のエラーが出た場合、以下を実行すること。(筆者は試行錯誤の過程で入れました。まっさらな状態から環境構築した場合、これを実行しないとエラーになると思います)

uv pip install "crewai-tools[mcp]"

CrewAIのプロジェクト作成(サンプルプロジェクト作成)

crewai create crew mcp_study

実行すると対話形式になるので、情報を入力する。利用するLLMサービスの情報もここで入力する。

CrewAIのサンプルプロジェクトを書き換える

ここが本題。やることは以下。

  • config/tasks.yamlを編集
  • crew.pyを編集
  • main.pyを編集

config/tasks.yamlを編集

それっぽい出力になるように以下に書き換える。reporting_taskは消した。

config/tasks.yaml
research_task:
 description: >
  Conduct a thorough research about {topic}
 expected_output: >
 Easy-to-read and friendly output like one a chatbot would give about {topic} in Japanese
 agent: mcp_user

crew.pyを編集

以下に書き換える。

crew.py
from crewai import Agent, Crew, Process, Task
from crewai.project import CrewBase, agent, crew, task
from crewai.agents.agent_builder.base_agent import BaseAgent

from typing import List

@CrewBase
class McpStudy():
    """McpStudy crew"""

    agents: List[BaseAgent]
    tasks: List[Task]

    mcp_server_params = [
    {
        "url": "http://localhost:8000/mcp", # MCPサーバーのエンドポイントを指定する
        "transport": "streamable-http"
    },
  ]

    @agent
    def mcp_user(self) -> Agent:
        return Agent(
            role="Research Analyst",
            goal="Research and analyze information",
            backstory="Expert researcher with access to external tools",
            tools=self.get_mcp_tools() # 補足あり!
        )

    @task
    def research_task(self) -> Task:
        return Task(
            config=self.tasks_config['research_task'], # type: ignore[index]
        )

    @crew
    def crew(self) -> Crew:
        """Creates the McpStudy crew"""

        return Crew(
            agents=self.agents, # Automatically created by the @agent decorator
            tasks=self.tasks, # Automatically created by the @task decorator
            process=Process.sequential,
            verbose=True,
            # process=Process.hierarchical, # In case you wanna use that instead https://docs.crewai.com/how-to/Hierarchical/
        )
    

参考URL:https://docs.crewai.com/en/mcp/overview

【補足】
こちらについて。

tools=self.get_mcp_tools()

McpStudyクラスの中でget_mcp_tools関数を定義してないので、このコードで動くの?と思う方いるかもしれません。デコレータが全く分からなかったので筆者もそうでした。
McpStudyクラスは、@CrewBaseというデコレータでCrewBaseクラスに機能追加したクラスとなっていて、CrewBaseMetaクラスのget_mcp_tools関数を使っていると理解してます。

crewAI/lib/crewai/src/crewai/project/crew_base.pyの634行目あたりの記述などを読むとよいです。

class CrewBase(metaclass=_CrewBaseType):
    """Class decorator that applies CrewBaseMeta metaclass.

    Applies CrewBaseMeta metaclass to a class via decorator syntax rather than
    explicit metaclass declaration. Use as @CrewBase instead of
    class Foo(metaclass=CrewBaseMeta).

    Note:
        Reference: https://stackoverflow.com/questions/11091609/setting-a-class-metaclass-using-a-decorator
    """

main.pyを編集

run関数の中のinputs.topicを質問したい内容に書き換える。

main.py
def run():
    """
    Run the crew.
    """
    inputs = {
        'topic': '最新のJグランツ上の補助金を教えて',
        # 'topic': '従業員50名の東京都の製造業で、金額1000万円以内、今月中に締切りの補助金はある?',
        # 'topic': 'DX推進補助金の募集要項と申請書を要約して',
        'current_year': str(datetime.now().year)
    }

    try:
        McpStudy().crew().kickoff(inputs=inputs)
    except Exception as e:
        raise Exception(f"An error occurred while running the crew: {e}")

CrewAIのAgentからデジタル庁MCPを利用してみる

  • デジタル庁MCPサーバーを起動する(localhost:8000で起動します)

    python -m jgrants_mcp_server.core
    
  • CrewAIのAgentを実行

    crewai run
    

    実行結果例
    出力結果をテキストで貼ると表示崩れるので、キャプチャを貼っておきます。
    実行結果例

参考

Discussion