Open4

MCP公式ドキュメントの個人的まとめ

tryutryu

具体的な処理の流れ

  • Clude Desktopに対し質問をする
  • MCPクライアントであるClaude Desktopは、利用可能なtoolsの中からどのtoolを選ぶかを決める(MCPサーバー内で、@mcp.tool() の記述がある部分はtoolとなり、ユーザからの許可がある場合にLLMから呼び出される関数である)

clientの実装は以下(該当部分のみ)

async def process_query(self, query: str) -> str:
    """Process a query using Claude and available tools"""
    messages = [
        {
            "role": "user",
            "content": query
        }
    ]

    response = await self.session.list_tools()
    available_tools = [{
        "name": tool.name,
        "description": tool.description,
        "input_schema": tool.inputSchema
    } for tool in response.tools]

https://modelcontextprotocol.io/quickstart/client

  • MCPクライアントは、引数をつけてMCPサーバー内の選択したtoolを実行する(ここで外部APIを呼び出したり、ローカルのファイルをプロンプトの通りに修正したりする)
for content in response.content:
        if content.type == 'text':
            final_text.append(content.text)
            assistant_message_content.append(content)
        elif content.type == 'tool_use':
            tool_name = content.name
            tool_args = content.input

            # Execute tool call
            result = await self.session.call_tool(tool_name, tool_args)
  • 実行結果をMCPクライアントに返す
  • Claude Desktopが受け取った実行結果を自然言語に直し、表示する
tryutryu

MCPサーバについて

MCPサーバーをLLMと一緒に実装する場合

Claude(LLM)に対して、ドキュメントpython-sdkのreadmeをプロンプトに含める形で渡すようにする。こうすることでLLMがMCPについて理解できるようになる。
その上で、プロンプトには以下の情報を含める必要がある:

  • MCPサーバーがどのようなリソースを使用する必要があるか(外部APIなど)
  • LLMから呼び出されるために、どのようなtoolが必要か
  • どのような処理をしてほしいかのプロンプト

https://modelcontextprotocol.io/tutorials/building-mcp-with-llms

MCPサーバーの実装例

https://modelcontextprotocol.io/quickstart/server

開発したMCPサーバーのデバッグ

「MCP Inspector」を使用すると良い
https://modelcontextprotocol.io/docs/tools/inspector

提供されているMCPサーバーの例

https://modelcontextprotocol.io/examples