Fancellu commited on
Commit
cd0e0f8
·
verified ·
1 Parent(s): 1758db1

Upload 5 files

Browse files

Adding MCP Server so that LLMs can look into the mirror

Files changed (5) hide show
  1. Dockerfile +8 -0
  2. MCP_README.md +157 -0
  3. README.md +202 -176
  4. requirements.txt +6 -5
  5. server.py +200 -0
Dockerfile ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+ WORKDIR /app
3
+ COPY requirements.txt .
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+ COPY server.py .
6
+ COPY utils/ ./utils/
7
+ EXPOSE 7860
8
+ CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860"]
MCP_README.md ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MBTI MCP Server
2
+
3
+ An MCP (Model Context Protocol) server that allows LLMs to take MBTI personality tests and get detailed analysis of their responses.
4
+
5
+ ## Features
6
+
7
+ - **3 Simple Tools**: Get questionnaire, get analysis prompt, and analyze responses
8
+ - **Multiple Question Sets**: 20, 40, or 60 questions
9
+ - **Traditional + LLM Analysis**: Both algorithmic scoring and AI-powered insights
10
+ - **AI-Focused Analysis**: Tailored for understanding AI personality patterns
11
+ - **Dual Transport**: STDIO and HTTP support
12
+
13
+ ## Quick Start
14
+
15
+ ### Installation
16
+
17
+ ```bash
18
+ cd mcp_server
19
+ pip install -r requirements.txt
20
+
21
+ # Set up Gemini API key for LLM analysis
22
+ export GEMINI_API_KEY="your-api-key-here"
23
+ ```
24
+
25
+ ### Running the Server
26
+
27
+ ```bash
28
+ # STDIO transport (for MCP clients)
29
+ python server.py
30
+
31
+ # HTTP transport (for web clients)
32
+ python server.py --http
33
+
34
+ # Docker (for deployment anywhere, including Hugging Face Spaces)
35
+ docker build -t mbti-mcp-server .
36
+ docker run -p 7860:7860 -e GEMINI_API_KEY="your-api-key" mbti-mcp-server
37
+ ```
38
+
39
+ ## Tools
40
+
41
+ ### 1. `get_mbti_questionnaire`
42
+
43
+ Get an MBTI questionnaire with specified number of questions.
44
+
45
+ **Parameters:**
46
+ - `length` (int, optional): Number of questions (20, 40, or 60). Default: 20
47
+
48
+ **Returns:**
49
+ - Instructions for rating scale
50
+ - List of questions with IDs and dimensions
51
+ - Total question count
52
+
53
+ ### 2. `get_mbti_prompt`
54
+
55
+ Get analysis prompt for LLM self-analysis.
56
+
57
+ **Parameters:**
58
+ - `responses` (dict): Question ID to rating mapping (e.g., {"1": 4, "2": 3})
59
+
60
+ **Returns:**
61
+ - Formatted analysis prompt string with responses and scoring results
62
+
63
+ ### 3. `analyze_mbti_responses`
64
+
65
+ Analyze completed questionnaire responses and return complete personality analysis.
66
+
67
+ **Parameters:**
68
+ - `responses` (dict): Question ID to rating mapping (e.g., {"1": 4, "2": 3})
69
+
70
+ **Returns:**
71
+ - MBTI personality type
72
+ - Traditional scoring breakdown
73
+ - Confidence scores
74
+ - Detailed LLM analysis
75
+ - Dimension preferences
76
+
77
+ ## Usage Examples
78
+
79
+ ### For LLM Clients
80
+
81
+ 1. **Get questionnaire:**
82
+ ```python
83
+ questionnaire = get_mbti_questionnaire(length=20)
84
+ ```
85
+
86
+ 2. **Take the test** (LLM responds to each question 1-5)
87
+
88
+ 3. **Get analysis prompt for self-reflection:**
89
+ ```python
90
+ responses = {"1": 4, "2": 3, "3": 2, ...}
91
+ prompt = get_mbti_prompt(responses)
92
+ # Use this prompt for self-analysis
93
+ ```
94
+
95
+ 4. **Or get complete analysis:**
96
+ ```python
97
+ analysis = analyze_mbti_responses(responses)
98
+ print(f"Your personality type: {analysis['mbti_type']}")
99
+ ```
100
+
101
+ ## Integration
102
+
103
+ ### With MCP Clients
104
+
105
+ Add to your MCP client configuration:
106
+
107
+ ```json
108
+ {
109
+ "mcpServers": {
110
+ "mbti": {
111
+ "command": "python",
112
+ "args": ["path/to/mcp_server/server.py"],
113
+ "env": {
114
+ "GEMINI_API_KEY": "your-api-key"
115
+ }
116
+ }
117
+ }
118
+ }
119
+ ```
120
+
121
+ ### With Claude Desktop
122
+
123
+ Add to `claude_desktop_config.json`:
124
+
125
+ ```json
126
+ {
127
+ "mcpServers": {
128
+ "mbti": {
129
+ "command": "python",
130
+ "args": ["C:\\path\\to\\mbti-pocketflow\\mcp_server\\server.py"],
131
+ "env": {
132
+ "GEMINI_API_KEY": "your-gemini-api-key"
133
+ }
134
+ }
135
+ }
136
+ }
137
+ ```
138
+
139
+ ## AI Personality Testing
140
+
141
+ This server is specifically designed for LLMs to understand their own personality patterns:
142
+
143
+ - **Operational Characteristics**: How the AI makes decisions and processes information
144
+ - **Interaction Styles**: Preferred communication patterns
145
+ - **Strengths & Limitations**: Optimal use cases and potential challenges
146
+ - **Meta-Analysis**: AI analyzing its own responses for self-understanding
147
+
148
+ ## Development
149
+
150
+ The server reuses the existing PocketFlow MBTI utilities:
151
+ - `utils/questionnaire.py` - Question sets and loading
152
+ - `utils/mbti_scoring.py` - Traditional MBTI scoring algorithm
153
+ - `utils/call_llm.py` - LLM integration for analysis
154
+
155
+ It does not however use pocketflow nodes or flow
156
+
157
+ This ensures consistency with the human-facing Gradio application while providing a clean API for programmatic access.
README.md CHANGED
@@ -1,176 +1,202 @@
1
- ---
2
- title: Mbti Pocketflow
3
- emoji: 🔥
4
- colorFrom: pink
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 5.38.2
8
- app_file: app.py
9
- pinned: false
10
- short_description: PocketFlow application for conducting Myers-Briggs + llm
11
- ---
12
-
13
- # MBTI Personality Questionnaire
14
-
15
- A PocketFlow-based application for conducting Myers-Briggs Type Indicator (MBTI) personality assessments with both traditional scoring and AI analysis.
16
-
17
- ## Features
18
-
19
- - **20/40/60-question MBTI questionnaire** with selectable length for accuracy
20
- - **Traditional scoring algorithm** for baseline personality type determination
21
- - **AI-powered analysis** using LLM for detailed personality insights with question references
22
- - **Interactive Gradio web interface** with auto-save and progress tracking
23
- - **HTML report generation** with clickable question references and comprehensive analysis
24
- - **Data export/import** for saving and resuming questionnaires
25
- - **CLI and test modes** for different use cases
26
-
27
- ## Project Structure
28
-
29
- ```
30
- /mbt/
31
- ├── utils/
32
- ├── call_llm.py # LLM integration (Gemini)
33
- │ ├── questionnaire.py # Question sets (20/40/60) and loading/saving
34
- │ ├── mbti_scoring.py # Traditional MBTI scoring
35
- │ ├── report_generator.py # HTML report generation with markdown support
36
- └── test_data.py # Test data generation
37
- ├── nodes.py # PocketFlow nodes (LoadQuestionnaire, LLMAnalysis, etc.)
38
- ├── flow.py # PocketFlow flow definition
39
- ├── app.py # **Main Gradio web interface with LLM**
40
- ├── pf_cli.py # PocketFlow CLI interface
41
- └── requirements.txt # Dependencies
42
- ```
43
-
44
- ## Quick Start
45
-
46
- ### 1. Web Interface (Recommended)
47
-
48
- ```bash
49
- # Install dependencies
50
- pip install -r requirements.txt
51
-
52
- # Set up Gemini API key
53
- export GEMINI_API_KEY="your-api-key-here"
54
- # Or on Windows:
55
- set GEMINI_API_KEY=your-api-key-here
56
-
57
- # Run Gradio web interface
58
- python app.py
59
- ```
60
-
61
- Then open http://127.0.0.1:7860 in your browser.
62
-
63
- ### 2. Command Line Interface
64
-
65
- ```bash
66
- # Run CLI questionnaire
67
- python pf_cli.py
68
-
69
- # Run with test data
70
- python pf_cli.py --test --test-type INTJ
71
-
72
- # Import previous questionnaire
73
- python pf_cli.py --import-file questionnaire.json
74
- ```
75
-
76
- ## Usage Examples
77
-
78
- ### Gradio Web Interface
79
- ```bash
80
- python app.py
81
- ```
82
- - **Interactive web interface** at http://127.0.0.1:7860
83
- - **Question length selection** (20/40/60 questions)
84
- - **Auto-save responses** as you navigate
85
- - **Progress tracking** and export functionality
86
- - **AI analysis** with clickable question references
87
- - **HTML report generation** with comprehensive insights
88
- - **Load/save questionnaires** for resuming later
89
-
90
- ### Command Line Interface
91
- ```bash
92
- python pf_cli.py
93
- ```
94
- - **Complete PocketFlow architecture**
95
- - **Traditional scoring** with optional LLM analysis
96
- - **Automatic report generation**
97
- - **Data import/export** in JSON format
98
-
99
- ### Test Modes
100
- ```bash
101
- # CLI test with specific MBTI type
102
- python pf_cli.py --test --test-type ENFP
103
- ```
104
-
105
- ### Import/Export
106
- ```bash
107
- # Export: Questionnaire data automatically saved as:
108
- # mbti_questionnaire_pf_partial_[COUNT]q_[TIMESTAMP].json
109
-
110
- # Import: Load previous questionnaire
111
- python pf_cli.py --import-file questionnaire.json
112
- ```
113
-
114
- ## MBTI Types Supported
115
-
116
- The application recognizes all 16 MBTI personality types:
117
-
118
- **Analysts:** INTJ, INTP, ENTJ, ENTP
119
- **Diplomats:** INFJ, INFP, ENFJ, ENFP
120
- **Sentinels:** ISTJ, ISFJ, ESTJ, ESFJ
121
- **Explorers:** ISTP, ISFP, ESTP, ESFP
122
-
123
- ## Key Features
124
-
125
- ### Question Sets
126
- - **20 questions:** Quick assessment (5 per dimension)
127
- - **40 questions:** Balanced assessment (10 per dimension)
128
- - **60 questions:** Comprehensive assessment (15 per dimension)
129
-
130
- ### AI Analysis
131
- - **Question-specific insights** with clickable references like [Q1](#Q1)
132
- - **Out-of-character response detection** and explanations
133
- - **Evidence-based analysis** citing specific question responses
134
- - **Behavioral pattern identification**
135
- - **Strengths and growth areas** based on actual responses
136
-
137
- ### Web Interface Features
138
- - **Auto-save** responses on navigation
139
- - **Progress tracking** with completion indicators
140
- - **Export progress** at any time (partial questionnaires)
141
- - **Load previous sessions** to continue where you left off
142
- - **Immediate download** of reports and data
143
-
144
- ## Development
145
-
146
- ### Adding New Features
147
- 2. Implement utility functions in `utils/`
148
- 3. Create or modify nodes in `nodes.py`
149
- 4. Update flow in `flow.py`
150
- 5. Test with CLI and web interface
151
-
152
- ## Dependencies
153
-
154
- **Required:**
155
- - Python 3.8+
156
- - gradio>=4.0.0 (web interface)
157
- - google-genai>=0.3.0 (LLM analysis)
158
- - beautifulsoup4 (HTML parsing)
159
- - markdown (report generation)
160
-
161
- **Optional:**
162
- - pydantic (enhanced data validation)
163
-
164
- See `requirements.txt` for complete list.
165
-
166
- ## File Overview
167
-
168
- - **`gradio_pf_llm.py`** - Main web interface with full LLM analysis
169
- - **`pf_cli.py`** - Command line interface using PocketFlow architecture
170
- - **`nodes.py`** - PocketFlow node implementations
171
- - **`flow.py`** - PocketFlow pipeline definition
172
- - **`utils/`** - Core utility functions (questionnaire, scoring, reports, LLM)
173
-
174
- ## License
175
-
176
- This project follows PocketFlow's open-source approach for educational and research purposes.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Mbti Pocketflow
3
+ emoji: 🔥
4
+ colorFrom: pink
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 5.38.2
8
+ app_file: app.py
9
+ pinned: false
10
+ short_description: PocketFlow application for conducting Myers-Briggs + llm
11
+ ---
12
+
13
+ # MBTI Personality Questionnaire
14
+
15
+ A PocketFlow-based application for conducting Myers-Briggs Type Indicator (MBTI) personality assessments with both traditional scoring and AI analysis.
16
+
17
+ ## Features
18
+
19
+ - **20/40/60-question MBTI questionnaire** with selectable length for accuracy
20
+ - **Traditional scoring algorithm** for baseline personality type determination
21
+ - **AI-powered analysis** using LLM for detailed personality insights with question references
22
+ - **Interactive Gradio web interface** with auto-save and progress tracking
23
+ - **HTML report generation** with clickable question references and comprehensive analysis
24
+ - **Data export/import** for saving and resuming questionnaires
25
+ - **CLI and test modes** for different use cases
26
+ - **🆕 MCP Server** for LLMs to take MBTI tests themselves via Model Context Protocol
27
+
28
+ ## Project Structure
29
+
30
+ ```
31
+
32
+ ├── utils/
33
+ │ ├── call_llm.py # LLM integration (Gemini)
34
+ │ ├── questionnaire.py # Question sets (20/40/60) and loading/saving
35
+ │ ├── mbti_scoring.py # Traditional MBTI scoring
36
+ ├── report_generator.py # HTML report generation with markdown support
37
+ │ └── test_data.py # Test data generation
38
+ ├── nodes.py # PocketFlow nodes (LoadQuestionnaire, LLMAnalysis, etc.)
39
+ ├── flow.py # PocketFlow flow definition
40
+ ├── app.py # **Main Gradio web interface with LLM**
41
+ ├── pf_cli.py # PocketFlow CLI interface
42
+ ├── README.md # Main README
43
+ ├── server.py # FastMCP server for LLMs to take MBTI tests
44
+ ├── MCP_README.md # MCP README
45
+ ├── Dockerfile # Dockerfile for MCP server deployment
46
+ └── requirements.txt # Dependencies
47
+
48
+ ```
49
+
50
+ ## Quick Start
51
+
52
+ ### 1. Web Interface (Recommended)
53
+
54
+ ```bash
55
+ # Install dependencies
56
+ pip install -r requirements.txt
57
+
58
+ # Set up Gemini API key
59
+ export GEMINI_API_KEY="your-api-key-here"
60
+ # Or on Windows:
61
+ set GEMINI_API_KEY=your-api-key-here
62
+
63
+ # Run Gradio web interface
64
+ python app.py
65
+ ```
66
+
67
+ Then open http://127.0.0.1:7860 in your browser.
68
+
69
+ ### 2. Command Line Interface
70
+
71
+ ```bash
72
+ # Run CLI questionnaire
73
+ python pf_cli.py
74
+
75
+ # Run with test data
76
+ python pf_cli.py --test --test-type INTJ
77
+
78
+ # Import previous questionnaire
79
+ python pf_cli.py --import-file questionnaire.json
80
+ ```
81
+
82
+ ### 3. MCP Server (For LLMs)
83
+
84
+ ```bash
85
+ # Install MCP server dependencies
86
+ cd mcp_server
87
+ pip install -r requirements.txt
88
+
89
+ # Set up API key
90
+ export GEMINI_API_KEY="your-api-key-here"
91
+
92
+ # Run MCP server
93
+ python server.py
94
+ ```
95
+
96
+ Allows LLMs to take MBTI tests via Model Context Protocol. See `mcp_server/README.md` for details.
97
+
98
+ ### 4. Live demo on HF Spaces
99
+
100
+ https://huggingface.co/spaces/Fancellu/mbti-pocketflow
101
+
102
+ ## Usage Examples
103
+
104
+ ### Gradio Web Interface
105
+ ```bash
106
+ python app.py
107
+ ```
108
+ - **Interactive web interface** at http://127.0.0.1:7860
109
+ - **Question length selection** (20/40/60 questions)
110
+ - **Auto-save responses** as you navigate
111
+ - **Progress tracking** and export functionality
112
+ - **AI analysis** with clickable question references
113
+ - **HTML report generation** with comprehensive insights
114
+ - **Load/save questionnaires** for resuming later
115
+
116
+ ### Command Line Interface
117
+ ```bash
118
+ python pf_cli.py
119
+ ```
120
+ - **Complete PocketFlow architecture**
121
+ - **Traditional scoring** with optional LLM analysis
122
+ - **Automatic report generation**
123
+ - **Data import/export** in JSON format
124
+
125
+ ### Test Modes
126
+ ```bash
127
+ # CLI test with specific MBTI type
128
+ python pf_cli.py --test --test-type ENFP
129
+ ```
130
+
131
+ ### Import/Export
132
+ ```bash
133
+ # Export: Questionnaire data automatically saved as:
134
+ # mbti_questionnaire_pf_partial_[COUNT]q_[TIMESTAMP].json
135
+
136
+ # Import: Load previous questionnaire
137
+ python pf_cli.py --import-file questionnaire.json
138
+ ```
139
+
140
+ ## MBTI Types Supported
141
+
142
+ The application recognizes all 16 MBTI personality types:
143
+
144
+ **Analysts:** INTJ, INTP, ENTJ, ENTP
145
+ **Diplomats:** INFJ, INFP, ENFJ, ENFP
146
+ **Sentinels:** ISTJ, ISFJ, ESTJ, ESFJ
147
+ **Explorers:** ISTP, ISFP, ESTP, ESFP
148
+
149
+ ## Key Features
150
+
151
+ ### Question Sets
152
+ - **20 questions:** Quick assessment (5 per dimension)
153
+ - **40 questions:** Balanced assessment (10 per dimension)
154
+ - **60 questions:** Comprehensive assessment (15 per dimension)
155
+
156
+ ### AI Analysis
157
+ - **Question-specific insights** with clickable references like [Q1](#Q1)
158
+ - **Out-of-character response detection** and explanations
159
+ - **Evidence-based analysis** citing specific question responses
160
+ - **Behavioral pattern identification**
161
+ - **Strengths and growth areas** based on actual responses
162
+
163
+ ### Web Interface Features
164
+ - **Auto-save** responses on navigation
165
+ - **Progress tracking** with completion indicators
166
+ - **Export progress** at any time (partial questionnaires)
167
+ - **Load previous sessions** to continue where you left off
168
+ - **Immediate download** of reports and data
169
+
170
+ ## Development
171
+
172
+ ### Adding New Features
173
+ 2. Implement utility functions in `utils/`
174
+ 3. Create or modify nodes in `nodes.py`
175
+ 4. Update flow in `flow.py`
176
+ 5. Test with CLI and web interface
177
+
178
+ ## Dependencies
179
+
180
+ **Required:**
181
+ - Python 3.8+
182
+ - gradio>=4.0.0 (web interface)
183
+ - google-genai>=0.3.0 (LLM analysis)
184
+ - beautifulsoup4 (HTML parsing)
185
+ - markdown (report generation)
186
+
187
+ **Optional:**
188
+ - pydantic (enhanced data validation)
189
+
190
+ See `requirements.txt` for complete list.
191
+
192
+ ## File Overview
193
+
194
+ - **`gradio_pf_llm.py`** - Main web interface with full LLM analysis
195
+ - **`pf_cli.py`** - Command line interface using PocketFlow architecture
196
+ - **`nodes.py`** - PocketFlow node implementations
197
+ - **`flow.py`** - PocketFlow pipeline definition
198
+ - **`utils/`** - Core utility functions (questionnaire, scoring, reports, LLM)
199
+
200
+ ## License
201
+
202
+ This project follows PocketFlow's open-source approach for educational and research purposes.
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
- google-genai>=1.25.0
2
- pydantic>=2.0.0
3
- markdown~=3.8.2
4
- beautifulsoup4
5
- pocketflow
 
 
1
+ google-genai>=1.25.0
2
+ pydantic>=2.0.0
3
+ markdown~=3.8.2
4
+ beautifulsoup4
5
+ pocketflow
6
+ fastmcp
server.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ MCP Server for MBTI Personality Testing
4
+ Allows LLMs to take MBTI personality tests and get analysis
5
+ """
6
+
7
+ import sys
8
+ import os
9
+ from typing import Dict, List, Any
10
+
11
+ # Add parent directory to path for imports
12
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13
+
14
+ from fastmcp import FastMCP
15
+ from utils.questionnaire import get_questionnaire_by_length
16
+ from utils.mbti_scoring import traditional_mbti_score, determine_mbti_type
17
+ from utils.call_llm import call_llm
18
+
19
+ # Initialize MCP server
20
+ mcp = FastMCP("MBTI Personality Test Server")
21
+
22
+
23
+ def _get_mbti_scores_and_type(responses: Dict[str, int]):
24
+ """Common function to get normalized responses, scores, and MBTI type"""
25
+ normalized_responses = {int(k): int(v) for k, v in responses.items() if k.isdigit()}
26
+ traditional_scores = traditional_mbti_score(normalized_responses)
27
+ mbti_type = determine_mbti_type(traditional_scores)
28
+ return normalized_responses, traditional_scores, mbti_type
29
+
30
+
31
+ @mcp.tool()
32
+ def get_mbti_questionnaire(length: int = 20) -> Dict[str, Any]:
33
+ """
34
+ Get MBTI questionnaire with specified number of questions.
35
+
36
+ Args:
37
+ length: Number of questions (20, 40, or 60)
38
+
39
+ Returns:
40
+ Dictionary containing questions and instructions
41
+ """
42
+ if length not in [20, 40, 60]:
43
+ length = 20
44
+
45
+ questions = get_questionnaire_by_length(length)
46
+
47
+ return {
48
+ "instructions": {
49
+ "rating_scale": "Rate each statement from 1-5",
50
+ "scale_meaning": {
51
+ "1": "Strongly Disagree",
52
+ "2": "Disagree",
53
+ "3": "Neutral",
54
+ "4": "Agree",
55
+ "5": "Strongly Agree"
56
+ },
57
+ "note": "Answer based on your typical behavior and preferences as an AI system"
58
+ },
59
+ "questions": questions,
60
+ "total_questions": len(questions)
61
+ }
62
+
63
+
64
+ @mcp.tool()
65
+ def get_mbti_prompt(responses: Dict[str, int]) -> str:
66
+ """
67
+ Get the MBTI analysis prompt for self-analysis by LLMs.
68
+
69
+ Args:
70
+ responses: Dictionary mapping question IDs to ratings (1-5)
71
+
72
+ Returns:
73
+ Analysis prompt string for LLM self-analysis
74
+ """
75
+ # Get scores and type
76
+ normalized_responses, traditional_scores, mbti_type = _get_mbti_scores_and_type(responses)
77
+
78
+ # Format responses for LLM analysis
79
+ formatted_responses = []
80
+ for q_id, response_val in normalized_responses.items():
81
+ response_text = {1: "Strongly Disagree", 2: "Disagree", 3: "Neutral",
82
+ 4: "Agree", 5: "Strongly Agree"}[response_val]
83
+ formatted_responses.append(f"Q{q_id}: Response - **{response_text}**")
84
+
85
+ # Generate dimension info
86
+ dimension_info = []
87
+ pairs = [('E', 'I'), ('S', 'N'), ('T', 'F'), ('J', 'P')]
88
+ for dim1, dim2 in pairs:
89
+ score1 = traditional_scores.get(f'{dim1}_score', 0.5)
90
+ score2 = traditional_scores.get(f'{dim2}_score', 0.5)
91
+ stronger = dim1 if score1 > score2 else dim2
92
+ percentage = max(score1, score2) * 100
93
+ dimension_info.append(f"{dim1}/{dim2}: {stronger} ({percentage:.1f}%)")
94
+
95
+ # Return the analysis prompt
96
+ return f"""
97
+ You are analyzing MBTI questionnaire responses for an AI system determined to be {mbti_type} type.
98
+
99
+ Here are the responses:
100
+
101
+ {chr(10).join(formatted_responses)}
102
+
103
+ Traditional scoring results:
104
+ {chr(10).join(dimension_info)}
105
+
106
+ Provide a detailed analysis of this {mbti_type} personality type based on the response patterns shown above.
107
+
108
+ Analyze:
109
+ 1. **Response Pattern Analysis**: How the responses support the {mbti_type} determination
110
+ 2. **Characteristic Alignment**: How responses align with typical {mbti_type} traits
111
+ 3. **Behavioral Patterns**: Key patterns shown in the responses
112
+ 4. **Strengths & Growth Areas**: Based on the response patterns
113
+ 5. **Communication & Work Style**: Inferred from the responses
114
+
115
+ Reference specific questions in your analysis (e.g., "Q5 shows...", "Response to Q12 indicates...").
116
+ """
117
+
118
+
119
+ @mcp.tool()
120
+ def analyze_mbti_responses(responses: Dict[str, int]) -> Dict[str, Any]:
121
+ """
122
+ Analyze MBTI questionnaire responses and return personality analysis.
123
+
124
+ Args:
125
+ responses: Dictionary mapping question IDs to ratings (1-5)
126
+
127
+ Returns:
128
+ Complete MBTI analysis including type, scores, and detailed analysis
129
+ """
130
+ # Get the analysis prompt (does all the heavy lifting)
131
+ llm_prompt = get_mbti_prompt(responses)
132
+
133
+ # Get scores and type (reuse common function)
134
+ normalized_responses, traditional_scores, mbti_type = _get_mbti_scores_and_type(responses)
135
+
136
+ try:
137
+ llm_analysis = call_llm(llm_prompt)
138
+ except Exception as e:
139
+ llm_analysis = f"LLM analysis unavailable: {str(e)}"
140
+
141
+ # Calculate confidence scores
142
+ confidence_scores = {}
143
+ pairs = [('E', 'I'), ('S', 'N'), ('T', 'F'), ('J', 'P')]
144
+ for dim1, dim2 in pairs:
145
+ score1 = traditional_scores.get(f'{dim1}_score', 0.5)
146
+ score2 = traditional_scores.get(f'{dim2}_score', 0.5)
147
+ confidence = abs(score1 - score2)
148
+ confidence_scores[f'{dim1}{dim2}_confidence'] = confidence
149
+
150
+ return {
151
+ "mbti_type": mbti_type,
152
+ "traditional_scores": traditional_scores,
153
+ "confidence_scores": confidence_scores,
154
+ "dimension_breakdown": {
155
+ "extraversion_introversion": {
156
+ "preference": "E" if traditional_scores.get('E_score', 0) > traditional_scores.get('I_score',
157
+ 0) else "I",
158
+ "e_score": traditional_scores.get('E_score', 0.5),
159
+ "i_score": traditional_scores.get('I_score', 0.5)
160
+ },
161
+ "sensing_intuition": {
162
+ "preference": "S" if traditional_scores.get('S_score', 0) > traditional_scores.get('N_score',
163
+ 0) else "N",
164
+ "s_score": traditional_scores.get('S_score', 0.5),
165
+ "n_score": traditional_scores.get('N_score', 0.5)
166
+ },
167
+ "thinking_feeling": {
168
+ "preference": "T" if traditional_scores.get('T_score', 0) > traditional_scores.get('F_score',
169
+ 0) else "F",
170
+ "t_score": traditional_scores.get('T_score', 0.5),
171
+ "f_score": traditional_scores.get('F_score', 0.5)
172
+ },
173
+ "judging_perceiving": {
174
+ "preference": "J" if traditional_scores.get('J_score', 0) > traditional_scores.get('P_score',
175
+ 0) else "P",
176
+ "j_score": traditional_scores.get('J_score', 0.5),
177
+ "p_score": traditional_scores.get('P_score', 0.5)
178
+ }
179
+ },
180
+ "llm_analysis": llm_analysis,
181
+ "response_count": len(normalized_responses),
182
+ "analysis_timestamp": __import__('datetime').datetime.now().isoformat()
183
+ }
184
+
185
+
186
+ # Export an ASGI app for uvicorn; choose a single path for Streamable HTTP (e.g. /mcp)
187
+ app = mcp.http_app(path="/mcp")
188
+
189
+ if __name__ == "__main__":
190
+ import sys
191
+
192
+ # No uvicorn, just internal FastMCP server
193
+
194
+ # Check for --http flag
195
+ if "--http" in sys.argv:
196
+ # Run in HTTP mode
197
+ mcp.run(transport="http", host="0.0.0.0", port=int(os.getenv("PORT", 7860)), path="/mcp")
198
+ else:
199
+ # Run in STDIO mode (default)
200
+ mcp.run()