import asyncio
from fastmcp import Client
import ollama
import sys

endpoint = "http://localhost:8700/mcp"
mcpclient = Client(endpoint)

async def run_client(prompt: str):
  async with mcpclient:
    tools_list = await mcpclient.list_tools()
    tools = [{
               'type': 'function',
               'function': {
                 'name': tool.name,
                 'description': tool.description,
                 'parameters': tool.inputSchema
               }
             } for tool in tools_list]

    ollama_agent = ollama.Client(host="localhost:11434")
    messages = [
                 {
                   'role': 'user',
                   'content': prompt,
                 },
               ]
    
    # （1）推論のループ（10回）
    for _ in range(10):
      response = ollama_agent.chat(
        model='gpt-oss:20b',
        tools=tools,
        messages=messages,
        )
        
      if response.message.content:
        print(response.message.content)

      if response.message.tool_calls:
        for tool_call in response.message.tool_calls:
          result = await mcpclient.call_tool(tool_call.function.name,
            tool_call.function.arguments)
          if result.content:
            print(f"関数の実行結果:{result.content[0].text}")
            # （2）実行結果を用いて推論を繰り返す
            messages.append({"role": "tool", 
                             "content": result.content[0].text, 
                             "tool_name": tool_call.function.name})
          else:
            print("関数が見つかりません")
      else:
        break  

if __name__ == "__main__":
  prompt = sys.argv[1]   # コマンドライン引数からプロンプトを取得
  asyncio.run(run_client(prompt))