|
| 1 | +# mypy: ignore-errors |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import os |
| 5 | + |
| 6 | +from langchain_mcp_adapters.client import MultiServerMCPClient |
| 7 | +from langgraph.checkpoint.memory import InMemorySaver |
| 8 | +from langgraph.prebuilt import create_react_agent |
| 9 | + |
| 10 | + |
| 11 | +def print_stream_item(item): |
| 12 | + if "agent" in item: |
| 13 | + content = [ |
| 14 | + part |
| 15 | + for message in item["agent"]["messages"] |
| 16 | + for part in ( |
| 17 | + message.content |
| 18 | + if isinstance(message.content, list) |
| 19 | + else [message.content] |
| 20 | + ) |
| 21 | + ] |
| 22 | + for c in content: |
| 23 | + if isinstance(c, str): |
| 24 | + print(f"Agent > {c}") |
| 25 | + elif "text" in c: |
| 26 | + print(f"Agent > {c['text']}") |
| 27 | + elif c["type"] == "tool_use": |
| 28 | + print(f" using tool: {c['name']}") |
| 29 | + |
| 30 | + |
| 31 | +async def main(): |
| 32 | + url = f"https://{os.environ.get('DBT_HOST')}/api/ai/v1/mcp/" |
| 33 | + headers = { |
| 34 | + "x-dbt-user-id": os.environ.get("DBT_USER_ID"), |
| 35 | + "x-dbt-prod-environment-id": os.environ.get("DBT_PROD_ENV_ID"), |
| 36 | + "x-dbt-dev-environment-id": os.environ.get("DBT_DEV_ENV_ID"), |
| 37 | + "Authorization": f"token {os.environ.get('DBT_TOKEN')}", |
| 38 | + } |
| 39 | + client = MultiServerMCPClient( |
| 40 | + { |
| 41 | + "dbt": { |
| 42 | + "url": url, |
| 43 | + "headers": headers, |
| 44 | + "transport": "streamable_http", |
| 45 | + } |
| 46 | + } |
| 47 | + ) |
| 48 | + tools = await client.get_tools() |
| 49 | + agent = create_react_agent( |
| 50 | + model="anthropic:claude-3-7-sonnet-latest", |
| 51 | + tools=tools, |
| 52 | + # This allows the agent to have conversational memory. |
| 53 | + checkpointer=InMemorySaver(), |
| 54 | + ) |
| 55 | + # This config maintains the conversation thread. |
| 56 | + config = {"configurable": {"thread_id": "1"}} |
| 57 | + while True: |
| 58 | + user_input = input("User > ") |
| 59 | + async for item in agent.astream( |
| 60 | + {"messages": {"role": "user", "content": user_input}}, |
| 61 | + config, |
| 62 | + ): |
| 63 | + print_stream_item(item) |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + asyncio.run(main()) |
0 commit comments