File size: 8,795 Bytes
073a9d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
#!/usr/bin/env python3
"""

ClimateQA MCP Client - Test and interact with the ClimateQA MCP server.



This script demonstrates how to connect to the ClimateQA MCP server using

the OpenAI Agents SDK and query climate-related documents and graphs.



Usage:

    # List available MCP tools

    python scripts/mcp_client.py list-tools



    # Run a single query

    python scripts/mcp_client.py query "What causes climate change?"



    # Interactive chat mode

    python scripts/mcp_client.py interactive



    # Custom MCP server URL

    python scripts/mcp_client.py --url http://localhost:7960/gradio_api/mcp/sse query "..."



Requirements:

    pip install openai-agents



Environment:

    OPENAI_API_KEY: Required for the agent

    MCP_SERVER_URL: Optional, defaults to http://localhost:7960/gradio_api/mcp/sse

"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
import sys
from typing import TYPE_CHECKING

# Load environment variables
try:
    from dotenv import load_dotenv
    load_dotenv()
except ImportError:
    pass

if TYPE_CHECKING:
    from agents import Agent
    from agents.mcp import MCPServerSse

# Configuration
DEFAULT_MCP_URL = "http://localhost:7960/gradio_api/mcp/sse"
DEFAULT_MODEL = "gpt-4o-mini"
TOOL_RESULT_PREVIEW_LENGTH = 500


def get_mcp_url() -> str:
    """Get the MCP server URL from environment or default."""
    return os.getenv("MCP_SERVER_URL", DEFAULT_MCP_URL)


def check_api_key() -> None:
    """Verify OpenAI API key is set."""
    if not os.getenv("OPENAI_API_KEY"):
        print("❌ Error: OPENAI_API_KEY environment variable is required")
        print("   Set it with: export OPENAI_API_KEY='your-key'")
        sys.exit(1)


def create_mcp_server(url: str) -> "MCPServerSse":
    """Create an MCP server connection."""
    from agents.mcp import MCPServerSse
    
    return MCPServerSse(
        params={"url": url},
        name="climateqa",
        cache_tools_list=True,
    )


def create_agent(mcp_server: "MCPServerSse") -> "Agent":
    """Create the ClimateQA agent with MCP tools."""
    from agents import Agent
    
    return Agent(
        name="ClimateQA Agent",
        instructions="""You are a climate research assistant with access to scientific 

documents from IPCC, IPBES, IPOS reports and graphs from IEA and OWID.



When answering climate-related questions:

1. Use retrieve_data_mcp to get relevant documents and figures from climate reports

2. Use retrieve_graphs_mcp to get relevant data visualizations

3. Synthesize the information into a clear, well-sourced answer



Always cite your sources and mention which reports the information comes from.""",
        mcp_servers=[mcp_server],
        model=DEFAULT_MODEL,
    )


async def list_tools(url: str) -> None:
    """List all available MCP tools from the server."""
    print(f"\nπŸ“‘ Connecting to: {url}")
    print("=" * 60)
    
    mcp_server = create_mcp_server(url)
    
    async with mcp_server:
        tools = await mcp_server.list_tools()
        
        if not tools:
            print("⚠️  No tools found on this MCP server")
            return
        
        print(f"Found {len(tools)} tool(s):\n")
        
        for tool in tools:
            print(f"πŸ“Œ {tool.name}")
            if tool.description:
                print(f"   {tool.description}")
            if tool.inputSchema:
                schema = json.dumps(tool.inputSchema, indent=2)
                print(f"   Schema: {schema}")
            print()


async def run_query(url: str, query: str) -> None:
    """Run a single query through the agent."""
    from agents import Runner
    
    check_api_key()
    
    print(f"\nπŸ“‘ MCP Server: {url}")
    print(f"❓ Query: {query}")
    print("=" * 60)
    
    mcp_server = create_mcp_server(url)
    agent = create_agent(mcp_server)
    
    async with mcp_server:
        result = Runner.run_streamed(agent, query)
        
        async for event in result.stream_events():
            if event.type == "run_item_stream_event":
                item = event.item
                item_type = getattr(item, "type", None)
                
                if item_type == "tool_call_item":
                    name = getattr(item, "name", "unknown")
                    args = getattr(item, "arguments", "{}")
                    print(f"\nπŸ”§ Calling: {name}")
                    print(f"   Args: {_truncate(str(args), 200)}")
                
                elif item_type == "tool_call_output_item":
                    output = getattr(item, "output", "")
                    print(f"\nπŸ“₯ Result preview:")
                    print(f"   {_truncate(str(output), TOOL_RESULT_PREVIEW_LENGTH)}")
        
        print("\n" + "=" * 60)
        print("πŸ€– Agent Response:")
        print("=" * 60)
        print(result.final_output)


async def interactive_mode(url: str) -> None:
    """Run the agent in interactive chat mode."""
    from agents import Runner
    
    check_api_key()
    
    print("\n" + "=" * 60)
    print("🌍 ClimateQA MCP Agent - Interactive Mode")
    print("=" * 60)
    print(f"πŸ“‘ Server: {url}")
    print("πŸ’‘ Type your questions (or 'quit' to exit)")
    print("=" * 60)
    
    mcp_server = create_mcp_server(url)
    agent = create_agent(mcp_server)
    
    async with mcp_server:
        while True:
            try:
                query = input("\n❓ You: ").strip()
                
                if query.lower() in ("quit", "exit", "q"):
                    print("πŸ‘‹ Goodbye!")
                    break
                
                if not query:
                    continue
                
                print("\n⏳ Thinking...")
                
                result = Runner.run_streamed(agent, query)
                
                async for event in result.stream_events():
                    if event.type == "run_item_stream_event":
                        item = event.item
                        item_type = getattr(item, "type", None)
                        
                        if item_type == "tool_call_item":
                            name = getattr(item, "name", "unknown")
                            print(f"   πŸ”§ Using: {name}")
                        
                        elif item_type == "tool_call_output_item":
                            output = getattr(item, "output", "")
                            print(f"   πŸ“₯ Got {len(str(output))} chars")
                
                print(f"\nπŸ€– Agent: {result.final_output}")
                
            except KeyboardInterrupt:
                print("\n\nπŸ‘‹ Interrupted. Goodbye!")
                break
            except Exception as e:
                print(f"\n❌ Error: {e}")


def _truncate(text: str, length: int) -> str:
    """Truncate text with ellipsis if too long."""
    if len(text) <= length:
        return text
    return text[:length] + "..."


def main() -> None:
    """Main entry point."""
    parser = argparse.ArgumentParser(
        description="ClimateQA MCP Client - Query climate documents via MCP",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""

Examples:

  %(prog)s list-tools                          # List available MCP tools

  %(prog)s query "What causes global warming?" # Run a single query

  %(prog)s interactive                         # Interactive chat mode

  %(prog)s --url http://host:7960/... query .. # Use custom server URL

        """,
    )
    
    parser.add_argument(
        "--url",
        type=str,
        default=None,
        help=f"MCP server URL (default: {DEFAULT_MCP_URL})",
    )
    
    subparsers = parser.add_subparsers(dest="command", help="Command to run")
    
    # list-tools command
    subparsers.add_parser("list-tools", help="List available MCP tools")
    
    # query command
    query_parser = subparsers.add_parser("query", help="Run a single query")
    query_parser.add_argument("text", type=str, help="The question to ask")
    
    # interactive command
    subparsers.add_parser("interactive", help="Interactive chat mode")
    
    args = parser.parse_args()
    
    # Determine URL
    url = args.url or get_mcp_url()
    
    if args.command == "list-tools":
        asyncio.run(list_tools(url))
    elif args.command == "query":
        asyncio.run(run_query(url, args.text))
    elif args.command == "interactive":
        asyncio.run(interactive_mode(url))
    else:
        parser.print_help()


if __name__ == "__main__":
    main()