import asyncio
from fastmcp import Client
import ollama
import sys

# MCPサーバーのURL
endpoint = "http://localhost:8700/mcp"

# MCPクライアントのオブジェクト
mcpclient = Client(endpoint)

async def run_client(prompt: str):
  async with mcpclient:
    # MCPサーバーから関数の一覧を取得する
    tools_list = await mcpclient.list_tools()
    
    # （1）tools_listの内容をOllamaで扱えるように整形する
    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,
                 },
               ]
    
    # （2）gpt-oss-20bに推論を依頼する
    response = ollama_agent.chat(
      model='gpt-oss:20b',
      tools=tools,
      messages=messages,
    )

    if response.message.content:
      print(response.message.content)   # （3）結果の表示

    # （4）Function Callingを使う場合の処理
    if response.message.tool_calls:
      for tool_call in response.message.tool_calls:
        # MCPサーバーの関数を呼び出す
        result = await mcpclient.call_tool(tool_call.function.name,
          tool_call.function.arguments)
        if result.content:
          # 関数の実行結果の表示
          print(f"関数の実行結果:{result.content[0].text}")
        else:
          print("関数が見つかりません")

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