File size: 17,779 Bytes
5d1056c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
# MCP Architecture Documentation

## Overview

This document explains the Model Context Protocol (MCP) architecture used in the Competitive Analysis Agent system.

## What is the Model Context Protocol?

MCP is a standardized protocol designed to enable seamless integration of:
- **AI Models** (Claude, GPT-4, etc.) with
- **External Tools & Services** (web search, databases, APIs, etc.)
- **Custom Business Logic** (analysis, validation, report generation)

### Why MCP?

1. **Modularity**: Tools are isolated and reusable
2. **Scalability**: Add tools without modifying core agent code
3. **Standardization**: Common protocol across different AI systems
4. **Separation of Concerns**: Clear boundaries between reasoning and action
5. **Production Ready**: Built for enterprise-grade AI applications

---

## System Architecture

### Three-Tier Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚          PRESENTATION LAYER - Gradio UI             β”‚
β”‚  β€’ User input (company name, API key)               β”‚
β”‚  β€’ Report display (formatted Markdown)              β”‚
β”‚  β€’ Error handling and validation                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚ HTTP/REST
                   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚         APPLICATION LAYER - MCP Client              β”‚
β”‚  β€’ OpenAI Agent (GPT-4)                            β”‚
β”‚  β€’ Strategic reasoning and planning                 β”‚
β”‚  β€’ Tool orchestration and sequencing               β”‚
β”‚  β€’ Result synthesis                                 β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                   β”‚ MCP Protocol
                   β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚         SERVICE LAYER - MCP Server (FastMCP)        β”‚
β”‚  Tools:                                             β”‚
β”‚  β€’ validate_company()                              β”‚
β”‚  β€’ identify_sector()                               β”‚
β”‚  β€’ identify_competitors()                          β”‚
β”‚  β€’ browse_page()                                   β”‚
β”‚  β€’ generate_report()                               β”‚
β”‚                                                     β”‚
β”‚  External Services:                                β”‚
β”‚  β€’ DuckDuckGo API                                 β”‚
β”‚  β€’ HTTP/BeautifulSoup scraping                    β”‚
β”‚  β€’ OpenAI API (GPT-4)                             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

---

## Component Details

### 1. Presentation Layer (`app.py`)

**Gradio Interface**
- User-friendly web UI
- Input validation
- Output formatting
- Error messaging

```python
# Example flow
User Input: "Tesla"
    ↓
Validate inputs
    ↓
Call MCP Client.analyze_company()
    ↓
Display Markdown report
```

### 2. Application Layer (`mcp_client.py`)

**MCP Client with OpenAI Agent**

The client implements:
- **System Prompt**: Defines agent role and goals
- **Message History**: Maintains conversation context
- **Tool Calling**: Translates agent decisions to MCP calls
- **Response Synthesis**: Compiles results into reports

```python
system_prompt = """
You are a competitive analysis expert.
Use available tools to:
1. Validate the company
2. Identify sector
3. Find competitors
4. Gather strategic data
5. Generate insights
"""

# Agent workflow:
messages = [
    {"role": "system", "content": system_prompt},
    {"role": "user", "content": "Analyze Sony"}
]

response = client.chat.completions.create(
    model="gpt-4",
    messages=messages
)
# OpenAI returns tool calls, which we execute
```

**Key Features**:
- Graceful fallback to simple analysis when MCP unavailable
- Handles API errors and timeouts
- Synthesizes multiple tool results

### 3. Service Layer (`mcp_server.py`)

**FastMCP Server with Tools**

#### Tools Overview

| Tool | Purpose | Returns |
|------|---------|---------|
| `validate_company(name)` | Check if company exists | Bool + evidence |
| `identify_sector(name)` | Find industry classification | Sector name |
| `identify_competitors(sector, company)` | Discover top 3 rivals | "Comp1, Comp2, Comp3" |
| `browse_page(url, instructions)` | Extract webpage content | Relevant text |
| `generate_report(company, context)` | Create analysis report | Markdown report |

#### Tool Implementation Pattern

```python
@mcp.tool()
def validate_company(company_name: str) -> str:
    """
    Docstring: Describes tool purpose and parameters
    """
    # Implementation
    try:
        results = web_search_tool(f"{company_name} company")
        evidence_count = analyze_search_results(results)
        return validation_result
    except Exception as e:
        return f"Error: {str(e)}"
```

#### Web Search Integration

```python
from duckduckgo_search import DDGS

def web_search_tool(query: str) -> str:
    """Unified search interface for all tools"""
    with DDGS() as ddgs:
        results = list(ddgs.text(query, max_results=5))
    return format_results(results)
```

---

## Message Flow

### Complete Analysis Request

```
1. USER INTERFACE (Gradio)
   β”‚
   β”œβ”€ Company: "Apple"
   └─ OpenAI Key: "sk-..."
   
2. GRADIO β†’ MCP CLIENT
   β”‚
   β”œβ”€ analyze_competitor_landscape("Apple", api_key)
   β”‚
   └─ Creates CompetitiveAnalysisAgent instance
   
3. MCP CLIENT β†’ OPENAI
   β”‚
   β”œβ”€ System: "You are a competitive analyst..."
   β”œβ”€ User: "Analyze Apple's competitors"
   β”‚
   β”œβ”€ OpenAI responds with:
   β”‚  └─ "Call validate_company('Apple')"
   
4. MCP CLIENT β†’ MCP SERVER
   β”‚
   β”œβ”€ Calls: validate_company("Apple")
   β”œβ”€ Calls: identify_sector("Apple")
   β”œβ”€ Calls: identify_competitors("Technology", "Apple")
   β”‚
   └─ Receives results for each tool
   
5. MCP SERVER
   β”‚
   β”œβ”€ validate_company()
   β”‚  └─ Web search β†’ DuckDuckGo API β†’ Parse results
   β”‚
   β”œβ”€ identify_sector()
   β”‚  └─ Multi-stage search β†’ Keyword analysis β†’ Return sector
   β”‚
   β”œβ”€ identify_competitors()
   β”‚  └─ Industry search β†’ Competitor extraction β†’ Ranking
   β”‚
   └─ generate_report()
      └─ Format results β†’ Markdown template β†’ Return report
   
6. MCP CLIENT SYNTHESIS
   β”‚
   β”œβ”€ Compile all tool results
   β”œβ”€ Add OpenAI insights
   └─ Return complete report
   
7. GRADIO DISPLAY
   β”‚
   └─ Render Markdown report to user
```

---

## Data Flow Diagram

```
USER INPUT
    β”‚
    β”œβ”€ company_name: "Company X"
    └─ api_key: "sk-xxx"
    β”‚
    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Input Validation   β”‚
β”‚  (Length, Format)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   OpenAI Agent Planning      β”‚
β”‚  (System + User Messages)    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚
           β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
           β”‚                             β”‚                         β”‚              β”‚
           β–Ό                             β–Ό                         β–Ό              β–Ό
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”      β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ validate_      β”‚         β”‚ identify_        β”‚      β”‚ identify_    β”‚   β”‚ browse_ β”‚
    β”‚ company()      β”‚         β”‚ sector()         β”‚      β”‚ competitors()β”‚   β”‚ page()  β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜      β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜
             β”‚                         β”‚                       β”‚                  β”‚
             β–Ό                         β–Ό                       β–Ό                  β–Ό
       β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
       β”‚ Web Search   β”‚         β”‚ Web Search  β”‚         β”‚ Web Search β”‚     β”‚ HTTP Get β”‚
       β”‚ DuckDuckGo   β”‚         β”‚ Multi-stage β”‚         β”‚ Industry   β”‚     β”‚ Parse    β”‚
       β”‚ + Analysis   β”‚         β”‚             β”‚         β”‚ Leaders    β”‚     β”‚ HTML     β”‚
       β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”˜
              β”‚                       β”‚                      β”‚                  β”‚
              β–Ό                       β–Ό                      β–Ό                  β–Ό
         VALIDATION  β†’  SECTOR ID  β†’  COMPETITORS  β†’  ADDITIONAL DATA
              β”‚              β”‚              β”‚                  β”‚
              β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  generate_report()  β”‚
                    β”‚  (Compile results)  β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                    β”‚  OpenAI Final       β”‚
                    β”‚  Synthesis          β”‚
                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                             β”‚
                             β–Ό
                     FINAL REPORT
                    (Markdown format)
```

---

## Tool Implementation Details

### Tool 1: `validate_company()`

```python
# Multi-stage validation
search_results = web_search_tool("Tesla company business official site")

# Evidence signals:
βœ“ Official website found (.com/.io)
βœ“ "Official site" or "official website" mention
βœ“ Company + sector description
βœ“ Business terminology present
βœ“ Wikipedia/news mentions

# Result: Evidence count >= 2 β†’ Valid company
```

### Tool 2: `identify_sector()`

```python
# Three search strategies:
1. "What does Tesla do?" β†’ Extract sector keywords
2. "Tesla industry type" β†’ Direct classification
3. "Tesla sector news" β†’ Financial/news sources

# Sector patterns:
{
  "Technology": ["software", "hardware", "cloud", "ai", ...],
  "Finance": ["banking", "fintech", "insurance", ...],
  "Manufacturing": ["automotive", "industrial", ...],
  ...
}

# Weighted voting to determine primary sector
```

### Tool 3: `identify_competitors()`

```python
# Search strategy:
1. "Top technology companies" β†’ Market leaders
2. "Tesla competitors" β†’ Direct rivals
3. "EV industry leaders" β†’ Sector players

# Extraction methods:
- Pattern matching for company names
- List parsing (comma-separated, bulleted)
- Frequency analysis and ranking

# Returns: Top 3 ranked competitors
```

### Tool 4: `browse_page()`

```python
# Content extraction workflow:
requests.get(url) 
  β†’ BeautifulSoup parsing
  β†’ Remove scripts/styles/headers/footers
  β†’ Extract main content divs/articles/paragraphs
  β†’ Keyword matching against instructions
  β†’ Return top N relevant sentences

# Safety: Timeout=10s, max_content=5000 chars
```

### Tool 5: `generate_report()`

```python
# Template-based report generation
report = f"""
# Competitive Analysis Report: {company_name}

## Executive Summary
[Synthesized findings]

## Competitor Comparison
| Competitor | Strategy | Pricing | Products | Market |
|------------|----------|---------|----------|--------|
| [extracted competitors] | - | - | - | - |

## Strategic Insights
[Recommendations]
"""
```

---

## Error Handling Strategy

### Layered Error Handling

```
Layer 1: Input Validation (Gradio)
  └─ Check company name length
  └─ Validate API key format
  └─ Return user-friendly error

Layer 2: Tool Execution (MCP Server)
  └─ Try/except on each tool
  └─ Timeout protection (10s requests)
  └─ Graceful degradation
  └─ Log detailed errors

Layer 3: Agent Logic (MCP Client)
  └─ API timeout handling
  └─ Rate limit handling
  └─ Fallback to simple analysis
  └─ Return partial results

Layer 4: User Feedback (Gradio)
  └─ Display error with context
  └─ Suggest remediation
  └─ Allow retry
```

---

## Performance Optimization

### Caching Strategy
```python
# Web search results cached for 5 minutes
# Sector identify, re-used across tools
# Competitor list, reused in reports
```

### Parallel Tool Execution
```python
# Future enhancement: Run independent tools in parallel
validate_company() (parallel)
identify_sector()  (parallel)
identify_competitors() (sequential, depends on sector)
```

### Rate Limiting
```python
# DuckDuckGo: 2.0 second delays between searches
# OpenAI: Batched requests, monitoring quota
# HTTP: 10-second timeout, connection pooling
```

---

## Security Considerations

### API Key Handling
```python
# Keys accepted via:
βœ“ UI input field (temporary in memory)
βœ— NOT stored in files
βœ— NOT logged in output
βœ— NOT persisted in database

# Environment variables optional:
Optional: Load from .env via python-dotenv
```

### Data Privacy
```python
# Web search results: Temporary, discarded after analysis
# Company data: Not cached or stored
# User queries: Not logged or tracked
# Report generation: All local processing
```

### Web Scraping Safety
```python
# User-Agent provided (genuine browser identification)
# Robots.txt respected (DuckDuckGo + BeautifulSoup)
# Timeout protection (10 seconds)
# Error handling for blocked requests
```

---

## Extension Points

### Adding New Tools

```python
@mcp.tool()
def custom_tool(param1: str, param2: int) -> str:
    """
    Your custom tool description.
    Args:
        param1: Parameter 1 description
        param2: Parameter 2 description
    Returns:
        str: Result description
    """
    try:
        # Implementation
        result = some_operation(param1, param2)
        return result
    except Exception as e:
        return f"Error: {str(e)}"
```

### Modifying Agent Behavior

```python
# In mcp_client.py, edit system_prompt:
system_prompt = """
Updated instructions for agent behavior
"""

# Or add initial human message:
messages.append({
    "role": "user",
    "content": "Additional analysis request..."
})
```

### Customizing Report Generation

```python
# In mcp_server.py, edit generate_report() template:
report = f"""
# Custom Report Format

Your custom structure here...
"""
```

---

## Testing

### Manual Testing

```bash
# Test MCP Server
python mcp_server.py

# Test MCP Client functions
python -c "from mcp_client import analyze_competitor_landscape; print(analyze_competitor_landscape('Microsoft', 'sk-...'))"

# Test Gradio UI
python app.py
# Navigate to http://localhost:7860
```

### Validation Tests

```python
# Test validate_company()
assert "VALID" in validate_company("Google")
assert "NOT" in validate_company("FakeCompanyXYZ123")

# Test identify_sector()
assert "Technology" in identify_sector("Microsoft")
assert "Finance" in identify_sector("JPMorgan")

# Test competitor discovery
competitors = identify_competitors("Technology", "Google")
assert len(competitors) <= 3
```

---

## Future Enhancements

1. **Real-time Market Data**: Integrate financial APIs (Alpha Vantage, etc.)
2. **Sentiment Analysis**: Analyze news sentiment about companies
3. **Patent Analysis**: Include R&D insights from patents
4. **Social Media**: Monitor competitor social media activity
5. **Pricing Intelligence**: Track price changes over time
6. **SWOT Matrix**: Generate structured SWOT analysis
7. **Visualization**: Create charts and graphs
8. **PDF Export**: Generate PDF reports
9. **Multi-company Batch**: Analyze multiple companies
10. **Integration APIs**: Connect to Slack, Salesforce, etc.

---

## Conclusion

The MCP architecture provides:
- βœ… Modularity and extensibility
- βœ… Clear separation of concerns
- βœ… Robust error handling
- βœ… Scalability for future enhancements
- βœ… Production-ready design
- βœ… Easy tool management

This design enables rapid development, maintenance, and deployment of AI-powered competitive analysis systems.

---

**Document Version**: 1.0  
**Last Updated**: March 2026