#
tokens: 49378/50000 48/62 files (page 1/3)
lines: on (toggle) GitHub
raw markdown copy reset
This is page 1 of 3. Use http://codebase.md/adamsmaka/flutter-mcp?lines=true&page={x} to view the full context.

# Directory Structure

```
├── .dockerignore
├── .github
│   └── workflows
│       ├── build-executables.yml
│       └── publish-pypi.yml
├── .gitignore
├── .pypirc.template
├── .python-version
├── build.spec
├── CHANGELOG.md
├── CLAUDE.md
├── context7-installation-analysis.md
├── docker
│   ├── docker-compose.yml
│   └── Dockerfile
├── docs
│   ├── api-reference.md
│   ├── CLIENT-CONFIGURATIONS.md
│   ├── CONTRIBUTING.md
│   ├── DEVELOPMENT.md
│   ├── planning
│   │   ├── context7-marketing-analysis.md
│   │   ├── flutter-mcp-project-summary.md
│   │   ├── IMPLEMENTATION_SUMMARY.md
│   │   ├── ingestion-strategy.md
│   │   ├── initial-vision.md
│   │   ├── project-summary.md
│   │   ├── project-tasks.csv
│   │   ├── README-highlights.md
│   │   └── task-summary.md
│   ├── PUBLISHING.md
│   ├── README.md
│   ├── token-counting-analysis.md
│   ├── token-management-implementation.md
│   ├── TOOL-CONSOLIDATION-PLAN.md
│   ├── truncation-algorithm.md
│   └── VERSION_SPECIFICATION.md
├── ERROR_HANDLING.md
├── examples
│   ├── token_management_demo.py
│   └── truncation_demo.py
├── LICENSE
├── MANIFEST.in
├── npm-wrapper
│   ├── .gitignore
│   ├── bin
│   │   └── flutter-mcp.js
│   ├── index.js
│   ├── package.json
│   ├── publish.sh
│   ├── README.md
│   └── scripts
│       └── install.js
├── pyproject.toml
├── QUICK_FIX.md
├── README.md
├── RELEASE_GUIDE.md
├── scripts
│   ├── build-executables.sh
│   ├── publish-pypi.sh
│   └── test-server.sh
├── setup.py
├── src
│   └── flutter_mcp
│       ├── __init__.py
│       ├── __main__.py
│       ├── cache.py
│       ├── cli.py
│       ├── error_handling.py
│       ├── logging_utils.py
│       ├── recovery.py
│       ├── server.py
│       ├── token_manager.py
│       └── truncation.py
├── tests
│   ├── __init__.py
│   ├── test_integration.py
│   ├── test_token_management.py
│   ├── test_tools.py
│   └── test_truncation.py
└── uv.lock
```

# Files

--------------------------------------------------------------------------------
/.python-version:
--------------------------------------------------------------------------------

```
1 | 3.13
2 | 
```

--------------------------------------------------------------------------------
/npm-wrapper/.gitignore:
--------------------------------------------------------------------------------

```
 1 | # Node modules
 2 | node_modules/
 3 | 
 4 | # npm debug logs
 5 | npm-debug.log*
 6 | 
 7 | # IDE
 8 | .vscode/
 9 | .idea/
10 | 
11 | # OS
12 | .DS_Store
13 | Thumbs.db
14 | 
15 | # Build artifacts
16 | *.tgz
```

--------------------------------------------------------------------------------
/.pypirc.template:
--------------------------------------------------------------------------------

```
 1 | # PyPI configuration template
 2 | # Copy this file to ~/.pypirc and update with your credentials
 3 | # DO NOT commit this file with real credentials!
 4 | 
 5 | [distutils]
 6 | index-servers =
 7 |     pypi
 8 |     testpypi
 9 | 
10 | [pypi]
11 | username = __token__
12 | password = pypi-<your-token-here>
13 | 
14 | [testpypi]
15 | repository = https://test.pypi.org/legacy/
16 | username = __token__
17 | password = pypi-<your-test-token-here>
```

--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------

```
 1 | # Python
 2 | __pycache__/
 3 | *.py[cod]
 4 | *$py.class
 5 | *.so
 6 | .Python
 7 | .venv/
 8 | venv/
 9 | ENV/
10 | env/
11 | 
12 | # Testing
13 | .pytest_cache/
14 | .coverage
15 | htmlcov/
16 | .tox/
17 | .nox/
18 | 
19 | # Git
20 | .git/
21 | .gitignore
22 | 
23 | # Documentation (except needed files)
24 | docs/planning/
25 | 
26 | # Development
27 | .env
28 | .env.local
29 | *.log
30 | *.swp
31 | .DS_Store
32 | 
33 | # IDE
34 | .vscode/
35 | .idea/
36 | *.sublime-*
37 | 
38 | # Build artifacts
39 | build/
40 | dist/
41 | *.egg-info/
42 | .eggs/
43 | 
44 | # Cache
45 | .cache/
46 | .mypy_cache/
47 | .ruff_cache/
```

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
 1 | # Python
 2 | __pycache__/
 3 | *.py[cod]
 4 | *$py.class
 5 | *.so
 6 | .Python
 7 | env/
 8 | venv/
 9 | ENV/
10 | env.bak/
11 | venv.bak/
12 | .venv
13 | pip-log.txt
14 | pip-delete-this-directory.txt
15 | .env
16 | 
17 | # Virtual environments
18 | bin/
19 | include/
20 | lib/
21 | lib64/
22 | share/
23 | pyvenv.cfg
24 | 
25 | # Distribution / packaging
26 | .Python
27 | build/
28 | develop-eggs/
29 | dist/
30 | downloads/
31 | eggs/
32 | .eggs/
33 | lib/
34 | lib64/
35 | parts/
36 | sdist/
37 | var/
38 | wheels/
39 | *.egg-info/
40 | .installed.cfg
41 | *.egg
42 | MANIFEST
43 | 
44 | # PyInstaller
45 | *.manifest
46 | 
47 | # Unit test / coverage
48 | htmlcov/
49 | .tox/
50 | .coverage
51 | .coverage.*
52 | .cache
53 | nosetests.xml
54 | coverage.xml
55 | *.cover
56 | .hypothesis/
57 | .pytest_cache/
58 | 
59 | # IDEs
60 | .vscode/
61 | .idea/
62 | *.swp
63 | *.swo
64 | *~
65 | .DS_Store
66 | 
67 | # Project specific
68 | .uv/
69 | *.log
70 | dump.rdb
71 | redis-data/
72 | 
73 | # MCP
74 | mcp-inspector-data/
75 | inspiration/
```

--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------

```markdown
1 | docs/README.md
```

--------------------------------------------------------------------------------
/npm-wrapper/README.md:
--------------------------------------------------------------------------------

```markdown
 1 | # flutter-mcp
 2 | 
 3 | Stop hallucinated Flutter code. Get real docs, instantly.
 4 | 
 5 | Flutter MCP provides AI coding assistants with real-time access to Flutter/Dart documentation, eliminating outdated or incorrect API suggestions.
 6 | 
 7 | ## Quick Start
 8 | 
 9 | ```bash
10 | # One-time usage (no installation)
11 | npx flutter-mcp
12 | 
13 | # Or install globally
14 | npm install -g flutter-mcp
15 | flutter-mcp
16 | ```
17 | 
18 | ## Claude Desktop Setup
19 | 
20 | Add to your `claude_desktop_config.json`:
21 | 
22 | ```json
23 | {
24 |   "mcpServers": {
25 |     "flutter-docs": {
26 |       "command": "npx",
27 |       "args": ["flutter-mcp"]
28 |     }
29 |   }
30 | }
31 | ```
32 | 
33 | That's it! No configuration needed.
34 | 
35 | ## Features
36 | 
37 | ✅ **Real-time documentation** - Always up-to-date Flutter/Dart APIs  
38 | ✅ **500+ pre-indexed widgets** - Instant access to common Flutter components  
39 | ✅ **Smart search** - Fuzzy matching finds what you need  
40 | ✅ **Pub.dev integration** - Package docs and examples included  
41 | ✅ **Zero config** - Works out of the box  
42 | 
43 | ## Advanced Usage
44 | 
45 | ```bash
46 | # HTTP mode for web clients
47 | flutter-mcp --http --port 3000
48 | 
49 | # SSE mode for streaming
50 | flutter-mcp --sse --port 3000
51 | 
52 | # Update Python backend
53 | flutter-mcp --install
54 | ```
55 | 
56 | ## Requirements
57 | 
58 | - Node.js 16+
59 | - Python 3.8+
60 | - pip (Python package manager)
61 | 
62 | ## What it does
63 | 
64 | This wrapper:
65 | 1. Checks for Python 3.8+ installation
66 | 2. Installs the `flutter-mcp-server` Python package if needed
67 | 3. Runs the Flutter MCP Server
68 | 
69 | ## Documentation
70 | 
71 | For full documentation, visit: https://github.com/flutter-mcp/flutter-mcp
72 | 
73 | ## License
74 | 
75 | MIT
```

--------------------------------------------------------------------------------
/docs/README.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Flutter MCP: Give Your AI Real-Time Flutter Superpowers 🚀
  2 | 
  3 | **A real-time MCP server providing Flutter/Dart documentation and pub.dev package info to AI assistants — supports ALL 50,000+ packages on demand.**
  4 | 
  5 | Stop fighting with hallucinated widgets and deprecated APIs. Flutter MCP connects your AI assistant to real-time documentation, ensuring the Flutter code it generates actually works.
  6 | 
  7 | <p align="center">
  8 |   <a href="https://www.npmjs.com/package/flutter-mcp"><img src="https://img.shields.io/npm/v/flutter-mcp.svg" alt="npm version"></a>
  9 |   <a href="https://www.npmjs.com/package/flutter-mcp"><img src="https://img.shields.io/npm/dm/flutter-mcp.svg" alt="npm downloads"></a>
 10 | </p>
 11 | 
 12 | <p align="center">
 13 |   <img src="https://img.shields.io/badge/Flutter-02569B?style=for-the-badge&logo=flutter&logoColor=white" alt="Flutter">
 14 |   <img src="https://img.shields.io/badge/Dart-0175C2?style=for-the-badge&logo=dart&logoColor=white" alt="Dart">
 15 |   <img src="https://img.shields.io/badge/Python-3776AB?style=for-the-badge&logo=python&logoColor=white" alt="Python">
 16 |   <img src="https://img.shields.io/badge/MCP-Protocol-green?style=for-the-badge" alt="MCP">
 17 | </p>
 18 | 
 19 | <p align="center">
 20 |   <a href="#-quick-start">Quick Start</a> •
 21 |   <a href="#-demo">Demo</a> •
 22 |   <a href="#-features">Features</a> •
 23 |   <a href="#-how-it-works">How it Works</a> •
 24 |   <a href="#-contributing">Contributing</a>
 25 | </p>
 26 | 
 27 | ## 🎬 Demo
 28 | 
 29 | <p align="center">
 30 |   <img src="https://github.com/flutter-mcp/flutter-mcp/assets/demo.gif" alt="Flutter MCP Demo" width="800">
 31 | </p>
 32 | 
 33 | **See it in action**: From `npx flutter-mcp` to getting real-time Flutter documentation in 20 seconds.
 34 | 
 35 | ## The Problem: Your AI is Stuck in 2021
 36 | 
 37 | <table>
 38 | <tr>
 39 | <td width="50%" align="center">
 40 | 
 41 | ### 😡 Without Flutter MCP
 42 | 
 43 | ```dart
 44 | // User: "How do I use Riverpod to watch a future?"
 45 | 
 46 | // AI generates (outdated):
 47 | final userProvider = FutureProvider((ref) async {
 48 |   return fetchUser();
 49 | });
 50 | 
 51 | // WRONG! Missing autoDispose, family, etc.
 52 | ```
 53 | 
 54 | **Result**: Deprecation warnings, confused debugging, time wasted on Google
 55 | 
 56 | </td>
 57 | <td width="50%" align="center">
 58 | 
 59 | ### ✅ With Flutter MCP
 60 | 
 61 | ```dart
 62 | // User: "How do I use @flutter_mcp riverpod:^2.5.0 to watch a future?"
 63 | 
 64 | // AI generates (using v2.5.1 docs):
 65 | final userProvider = FutureProvider.autoDispose
 66 |   .family<User, String>((ref, userId) async {
 67 |     return ref.watch(apiProvider).fetchUser(userId);
 68 | });
 69 | 
 70 | // Correct, version-specific, actually works!
 71 | ```
 72 | 
 73 | **Result**: Code works immediately, you ship faster
 74 | 
 75 | </td>
 76 | </tr>
 77 | </table>
 78 | 
 79 | ## 🚀 Quick Start
 80 | 
 81 | ### Installation
 82 | 
 83 | Get started in seconds with npm:
 84 | 
 85 | ```bash
 86 | # One-line usage (no installation required)
 87 | npx flutter-mcp
 88 | 
 89 | # Or install globally
 90 | npm install -g flutter-mcp
 91 | flutter-mcp
 92 | ```
 93 | 
 94 | That's it! No Python setup, no configuration, no complexity. The server automatically installs dependencies and starts running.
 95 | 
 96 | > **📢 For MCP SuperAssistant Users**: Use `npx flutter-mcp --transport http --port 8000` to enable HTTP transport!
 97 | 
 98 | ### Alternative Installation Methods
 99 | 
100 | <details>
101 | <summary><strong>🐍 Python Package (pip)</strong></summary>
102 | 
103 | If you prefer using Python directly:
104 | 
105 | ```bash
106 | # Install from GitHub (PyPI package coming soon)
107 | pip install git+https://github.com/adamsmaka/flutter-mcp.git
108 | 
109 | # Run the server
110 | flutter-mcp-server start
111 | ```
112 | 
113 | </details>
114 | 
115 | <details>
116 | <summary><strong>🔧 Install from Source</strong></summary>
117 | 
118 | For development or customization:
119 | 
120 | ```bash
121 | # Clone the repository
122 | git clone https://github.com/adamsmaka/flutter-mcp.git
123 | cd flutter-mcp
124 | 
125 | # Create virtual environment
126 | python3 -m venv venv
127 | source venv/bin/activate  # On Windows: venv\Scripts\activate
128 | 
129 | # Install in development mode
130 | pip install -e .
131 | 
132 | # Run the server
133 | flutter-mcp-server start
134 | ```
135 | 
136 | </details>
137 | 
138 | <details>
139 | <summary><strong>🐳 Docker</strong></summary>
140 | 
141 | For containerized deployments:
142 | 
143 | ```bash
144 | # Docker image coming soon
145 | # Run with Docker (once published)
146 | # docker run -d -p 8000:8000 ghcr.io/adamsmaka/flutter-mcp:latest
147 | 
148 | # For now, use local development setup instead
149 | pip install git+https://github.com/adamsmaka/flutter-mcp.git
150 | ```
151 | 
152 | </details>
153 | 
154 | <details>
155 | <summary><strong>🎯 Single Executable (Coming Soon)</strong></summary>
156 | 
157 | ```bash
158 | # Download for your platform
159 | curl -L https://github.com/flutter-mcp/flutter-mcp/releases/latest/flutter-mcp-macos -o flutter-mcp
160 | chmod +x flutter-mcp
161 | ./flutter-mcp
162 | ```
163 | 
164 | No Python, no pip, just download and run!
165 | 
166 | </details>
167 | 
168 | ### Requirements
169 | 
170 | - **Node.js 16+** (for npm/npx)
171 | - Python 3.10+ is auto-detected and used by the npm package
172 | - That's it! Built-in SQLite caching means no external dependencies
173 | 
174 | ### 2. Add to Your AI Assistant
175 | 
176 | <details open>
177 | <summary><strong>Claude Desktop</strong></summary>
178 | 
179 | Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
180 | 
181 | ```json
182 | {
183 |   "mcpServers": {
184 |     "flutter-docs": {
185 |       "command": "npx",
186 |       "args": ["flutter-mcp"]
187 |     }
188 |   }
189 | }
190 | ```
191 | 
192 | Or if you installed globally:
193 | 
194 | ```json
195 | {
196 |   "mcpServers": {
197 |     "flutter-docs": {
198 |       "command": "flutter-mcp"
199 |     }
200 |   }
201 | }
202 | ```
203 | 
204 | Restart Claude Desktop after saving. The server will automatically install dependencies on first run.
205 | 
206 | </details>
207 | 
208 | <details>
209 | <summary><strong>Claude Code (claude.ai/code)</strong></summary>
210 | 
211 | Create a `.mcp.json` file in your Flutter project root:
212 | 
213 | ```json
214 | {
215 |   "mcpServers": {
216 |     "flutter-docs": {
217 |       "command": "npx",
218 |       "args": ["flutter-mcp"]
219 |     }
220 |   }
221 | }
222 | ```
223 | 
224 | Then run Claude Code in your project directory:
225 | ```bash
226 | cd your-flutter-project
227 | claude
228 | ```
229 | 
230 | Flutter MCP will automatically provide documentation for all packages in your `pubspec.yaml`.
231 | 
232 | **Alternative: Global npm install**
233 | 
234 | If you installed globally with `npm install -g flutter-mcp`:
235 | 
236 | ```json
237 | {
238 |   "mcpServers": {
239 |     "flutter-docs": {
240 |       "command": "flutter-mcp"
241 |     }
242 |   }
243 | }
244 | ```
245 | 
246 | **Important:** Don't use the `--dangerously-skip-permissions` flag when running Claude Code, as it prevents MCP servers from being loaded.
247 | 
248 | </details>
249 | 
250 | <details>
251 | <summary><strong>Cursor / Windsurf</strong></summary>
252 | 
253 | In Settings → MCP Servers, add:
254 | 
255 | ```json
256 | {
257 |   "flutter-docs": {
258 |     "command": "npx",
259 |     "args": ["flutter-mcp"]
260 |   }
261 | }
262 | ```
263 | 
264 | </details>
265 | 
266 | <details>
267 | <summary><strong>MCP SuperAssistant</strong></summary>
268 | 
269 | MCP SuperAssistant requires HTTP transport. Configure it with:
270 | 
271 | 1. Start the server with HTTP transport:
272 | ```bash
273 | npx flutter-mcp --transport http --port 8000
274 | ```
275 | 
276 | 2. In MCP SuperAssistant, add a new server:
277 |    - **Name**: Flutter MCP
278 |    - **URL**: `http://localhost:8000`
279 |    - **Type**: HTTP MCP Server
280 | 
281 | 3. The server will now be available in your MCP SuperAssistant client.
282 | 
283 | </details>
284 | 
285 | <details>
286 | <summary><strong>VS Code + Continue</strong></summary>
287 | 
288 | In your `.continuerc.json`:
289 | 
290 | ```json
291 | {
292 |   "models": [
293 |     {
294 |       "provider": "claude",
295 |       "mcp_servers": {
296 |         "flutter-docs": {
297 |           "command": "npx",
298 |           "args": ["flutter-mcp"]
299 |         }
300 |       }
301 |     }
302 |   ]
303 | }
304 | ```
305 | 
306 | </details>
307 | 
308 | ### 3. Start the Server (Optional for Testing)
309 | 
310 | <details>
311 | <summary>Manual server control and transport options</summary>
312 | 
313 | ```bash
314 | # Default STDIO mode (for Claude Desktop)
315 | npx flutter-mcp
316 | 
317 | # HTTP transport (for MCP SuperAssistant)
318 | npx flutter-mcp --transport http --port 8000
319 | 
320 | # SSE transport
321 | npx flutter-mcp --transport sse --port 8080
322 | 
323 | # Custom host binding
324 | npx flutter-mcp --transport http --host 0.0.0.0 --port 3000
325 | 
326 | # If installed globally
327 | flutter-mcp-server --transport http --port 8000
328 | ```
329 | 
330 | **Transport Options:**
331 | - Default (no flag) - STDIO for Claude Desktop and most MCP clients
332 | - `--transport http` - For HTTP-based clients like MCP SuperAssistant
333 | - `--transport sse` - For Server-Sent Events based clients
334 | - `--port PORT` - Port for HTTP/SSE transport (default: 8000)
335 | - `--host HOST` - Host to bind to (default: 127.0.0.1)
336 | 
337 | Note: When configured in Claude Desktop, the server starts automatically using STDIO transport.
338 | 
339 | </details>
340 | 
341 | ### 3. Use It!
342 | 
343 | Flutter MCP now features simplified tools following Context7's successful pattern - just 2 main tools instead of 5!
344 | 
345 | #### 🎯 New Simplified Usage (Recommended)
346 | 
347 | The AI assistant can now use Flutter MCP more intelligently:
348 | 
349 | ```
350 | # Universal search
351 | "Search for Flutter animation widgets"
352 | "Find state management packages" 
353 | "Look for HTTP clients in pub.dev"
354 | 
355 | # Smart documentation fetching
356 | "Show me Container widget documentation"
357 | "Get the docs for provider package"
358 | "Explain dart:async Future class"
359 | ```
360 | 
361 | #### 💫 Natural Language Support
362 | 
363 | Your AI will automatically detect Flutter/Dart content and fetch relevant docs:
364 | 
365 | ```
366 | "How do I implement infinite scroll with infinite_scroll_pagination?"
367 | "Show me dio interceptors for auth tokens"
368 | "What's the difference between bloc and riverpod?"
369 | ```
370 | 
371 | #### 🔧 Legacy Support
372 | 
373 | The `@flutter_mcp` mentions still work for backward compatibility:
374 | 
375 | ```
376 | "Explain @flutter_mcp freezed code generation"
377 | "Show me all @flutter_mcp get_it service locator patterns"
378 | ```
379 | 
380 | ### 🎯 Version-Specific Documentation (NEW!)
381 | 
382 | Get documentation for specific package versions using familiar pub.dev syntax:
383 | 
384 | ```
385 | # Exact versions
386 | "Show me @flutter_mcp provider:6.0.5 breaking changes"
387 | "How does @flutter_mcp riverpod:2.5.1 AsyncNotifier work?"
388 | 
389 | # Version ranges
390 | "Compare @flutter_mcp dio:^5.0.0 vs @flutter_mcp dio:^4.0.0"
391 | "What's new in @flutter_mcp bloc:>=8.0.0?"
392 | 
393 | # Special keywords
394 | "Try @flutter_mcp get:latest experimental features"
395 | "Is @flutter_mcp provider:stable production ready?"
396 | ```
397 | 
398 | See [Version Specification Guide](docs/VERSION_SPECIFICATION.md) for details.
399 | 
400 | ## 📚 Available Tools
401 | 
402 | ### 🎯 NEW: Simplified Tools (Context7-style)
403 | 
404 | Flutter MCP now provides just 2 main tools, making it easier for AI assistants to use:
405 | 
406 | ### 1. `flutter_search` - Universal Search
407 | 
408 | Search across Flutter/Dart documentation and pub.dev packages with intelligent ranking.
409 | 
410 | ```json
411 | {
412 |   "tool": "flutter_search",
413 |   "arguments": {
414 |     "query": "state management",
415 |     "limit": 10  // Optional: max results (default: 10)
416 |   }
417 | }
418 | ```
419 | 
420 | Returns multiple options for the AI to choose from, including Flutter classes, Dart libraries, pub packages, and concepts.
421 | 
422 | ### 2. `flutter_docs` - Smart Documentation Fetcher
423 | 
424 | Get documentation for any Flutter/Dart identifier with automatic type detection.
425 | 
426 | ```json
427 | {
428 |   "tool": "flutter_docs",
429 |   "arguments": {
430 |     "identifier": "Container",              // Auto-detects as Flutter widget
431 |     "topic": "examples",                    // Optional: filter content
432 |     "max_tokens": 10000                     // Optional: limit response size
433 |   }
434 | }
435 | ```
436 | 
437 | Supports various formats:
438 | - `"Container"` - Flutter widget
439 | - `"material.AppBar"` - Library-qualified class
440 | - `"provider"` - pub.dev package
441 | - `"dart:async.Future"` - Dart core library
442 | 
443 | ### 3. `flutter_status` - Health Check (Optional)
444 | 
445 | Monitor service health and cache statistics.
446 | 
447 | ```json
448 | {
449 |   "tool": "flutter_status",
450 |   "arguments": {}
451 | }
452 | ```
453 | 
454 | ---
455 | 
456 | ### 📦 Legacy Tools (Deprecated but still functional)
457 | 
458 | The following tools are maintained for backward compatibility but internally use the new simplified tools:
459 | 
460 | <details>
461 | <summary>View legacy tools</summary>
462 | 
463 | #### `get_flutter_docs` (Use `flutter_docs` instead)
464 | ```json
465 | {
466 |   "tool": "get_flutter_docs",
467 |   "arguments": {
468 |     "class_name": "Container",
469 |     "library": "widgets"
470 |   }
471 | }
472 | ```
473 | 
474 | #### `get_pub_package_info` (Use `flutter_docs` instead)
475 | ```json
476 | {
477 |   "tool": "get_pub_package_info",
478 |   "arguments": {
479 |     "package_name": "provider",
480 |     "version": "6.0.5"
481 |   }
482 | }
483 | ```
484 | 
485 | #### `search_flutter_docs` (Use `flutter_search` instead)
486 | ```json
487 | {
488 |   "tool": "search_flutter_docs",
489 |   "arguments": {
490 |     "query": "material.AppBar"
491 |   }
492 | }
493 | ```
494 | 
495 | #### `process_flutter_mentions` (Still functional)
496 | ```json
497 | {
498 |   "tool": "process_flutter_mentions",
499 |   "arguments": {
500 |     "text": "I need help with @flutter_mcp riverpod state management"
501 |   }
502 | }
503 | ```
504 | 
505 | #### `health_check` (Use `flutter_status` instead)
506 | ```json
507 | {
508 |   "tool": "health_check",
509 |   "arguments": {}
510 | }
511 | ```
512 | 
513 | </details>
514 | 
515 | ## 🎯 Features
516 | 
517 | - **✨ NEW: Simplified Tools**: Just 2 main tools instead of 5 - following Context7's successful pattern
518 | - **📦 Real-Time Documentation**: Fetches the latest docs for any pub.dev package on-demand
519 | - **🎯 Version-Specific Docs**: Request exact versions, ranges, or use keywords like `latest`/`stable`
520 | - **🚀 Zero Configuration**: Automatically detects packages from your `pubspec.yaml`
521 | - **⚡ Lightning Fast**: Intelligent caching means instant responses after first fetch
522 | - **🔒 100% Private**: Runs locally - your code never leaves your machine
523 | - **🎨 Smart Context**: Provides constructors, methods, examples, and migration guides
524 | - **♾️ Unlimited Packages**: Works with all 50,000+ packages on pub.dev
525 | - **🤖 AI-Optimized**: Token limiting and smart truncation for efficient LLM usage
526 | 
527 | ## 💡 How It Works
528 | 
529 | Flutter MCP is a local MCP server (think of it as a "RAG sidecar" for Flutter) built on the battle-tested Python MCP SDK. It enhances your AI with real-time documentation:
530 | 
531 | ```mermaid
532 | graph LR
533 |     A[Your Prompt] --> B[AI Assistant]
534 |     B --> C{Flutter/Dart Content?}
535 |     C -->|Yes| D[Query Flutter MCP]
536 |     D --> E[Check Local Cache]
537 |     E -->|Hit| F[Return Cached Docs]
538 |     E -->|Miss| G[Fetch from pub.dev]
539 |     G --> H[Process & Cache]
540 |     H --> F
541 |     F --> I[Enhanced Context]
542 |     I --> J[AI Generates Accurate Code]
543 |     C -->|No| J
544 | ```
545 | 
546 | ### The Magic Behind the Scenes
547 | 
548 | 1. **MCP Integration**: Your AI assistant automatically detects when you're asking about Flutter/Dart packages
549 | 2. **Smart Detection**: No special syntax required - just mention package names naturally
550 | 3. **Lightning Cache**: First request fetches from pub.dev (1-2 seconds), subsequent requests are instant
551 | 4. **Context Injection**: Documentation is seamlessly added to your AI's knowledge before it responds
552 | 5. **Privacy First**: Everything runs locally - your code and queries never leave your machine
553 | 
554 | ### Performance Notes
555 | 
556 | - ⚡ **First Query**: 1-2 seconds (fetching from pub.dev)
557 | - 🚀 **Cached Queries**: <50ms (from local SQLite cache)
558 | - 💾 **Cache Duration**: 24 hours for API docs, 12 hours for packages
559 | - 🧹 **Auto-Cleanup**: Expired entries cleaned on access
560 | 
561 | ### Error Handling
562 | 
563 | If documentation isn't available or a fetch fails, Flutter MCP gracefully informs your AI, preventing it from generating incorrect or hallucinated code based on missing information. Your AI will let you know it couldn't find the docs rather than guessing.
564 | 
565 | ## 📊 What Gets Indexed
566 | 
567 | When you request a package, Flutter MCP extracts:
568 | 
569 | - ✅ **API Documentation**: Classes, methods, properties with full signatures
570 | - ✅ **Constructors**: All parameters, named arguments, defaults
571 | - ✅ **Code Examples**: From official docs and README files
572 | - ✅ **Migration Guides**: Breaking changes and upgrade paths
573 | - ✅ **Package Metadata**: Dependencies, platform support, versions
574 | 
575 | ## 🛠️ Advanced Usage
576 | 
577 | <details>
578 | <summary><strong>Debug Commands</strong></summary>
579 | 
580 | ```bash
581 | # Run with debug logging
582 | DEBUG=true npx flutter-mcp
583 | 
584 | # Check server status and cache info
585 | flutter-mcp-server --help
586 | ```
587 | 
588 | Note: Cache is automatically managed by the server. Cached documentation expires after 24 hours (API docs) or 12 hours (packages).
589 | 
590 | </details>
591 | 
592 | <details>
593 | <summary><strong>Docker Deployment</strong></summary>
594 | 
595 | For production or team use:
596 | 
597 | ```bash
598 | # Run the server (Docker image coming soon)
599 | # docker run -d -p 8000:8000 --name flutter-mcp ghcr.io/adamsmaka/flutter-mcp:latest
600 | 
601 | # Check logs
602 | docker logs -f flutter-mcp
603 | ```
604 | 
605 | </details>
606 | 
607 | ## 🛠️ Troubleshooting
608 | 
609 | <details>
610 | <summary><strong>Error: spawn flutter-mcp ENOENT</strong></summary>
611 | 
612 | This error means the system cannot find the `flutter-mcp` command. Solutions:
613 | 
614 | 1. **Use npx (recommended):**
615 | ```json
616 | {
617 |   "mcpServers": {
618 |     "flutter-docs": {
619 |       "command": "npx",
620 |       "args": ["flutter-mcp"]
621 |     }
622 |   }
623 | }
624 | ```
625 | 
626 | 2. **Install globally first:**
627 | ```bash
628 | npm install -g flutter-mcp
629 | # Then use:
630 | {
631 |   "mcpServers": {
632 |     "flutter-docs": {
633 |       "command": "flutter-mcp"
634 |     }
635 |   }
636 | }
637 | ```
638 | 
639 | 3. **Check Node.js installation:**
640 | ```bash
641 | node --version  # Should be 16+
642 | npm --version   # Should be installed
643 | ```
644 | 
645 | </details>
646 | 
647 | <details>
648 | <summary><strong>MCP server failed to start</strong></summary>
649 | 
650 | 1. Check if Node.js 16+ is installed: `node --version`
651 | 2. Try running manually to see errors: `npx flutter-mcp`
652 | 3. The npm package will auto-install Python dependencies on first run
653 | 4. Check if Python 3.8+ is available: `python3 --version`
654 | 5. View detailed logs: `DEBUG=true npx flutter-mcp`
655 | 
656 | </details>
657 | 
658 | <details>
659 | <summary><strong>Documentation not found errors</strong></summary>
660 | 
661 | - Some very new packages might not have documentation yet
662 | - Private packages are not supported
663 | - Try using the package name exactly as it appears on pub.dev
664 | 
665 | </details>
666 | 
667 | <details>
668 | <summary><strong>Cannot connect from MCP client</strong></summary>
669 | 
670 | Different MCP clients require different transport protocols:
671 | 
672 | 1. **Claude Desktop**: Uses STDIO transport (default)
673 |    - No port/URL needed
674 |    - Just use: `npx flutter-mcp`
675 | 
676 | 2. **MCP SuperAssistant**: Requires HTTP transport
677 |    - Start with: `npx flutter-mcp --transport http --port 8000`
678 |    - Connect to: `http://localhost:8000`
679 | 
680 | 3. **Custom clients**: May need SSE transport
681 |    - Start with: `npx flutter-mcp --transport sse --port 8080`
682 |    - SSE endpoint: `http://localhost:8080/sse`
683 | 
684 | If connection fails:
685 | - Verify the correct transport mode for your client
686 | - Check if the port is already in use
687 | - Try binding to all interfaces: `--host 0.0.0.0`
688 | - Ensure Node.js and npm are properly installed
689 | 
690 | </details>
691 | 
692 | ## 📱 Client Configurations
693 | 
694 | Need help configuring your MCP client? We have detailed guides for:
695 | - Claude Desktop
696 | - MCP SuperAssistant  
697 | - Claude Code
698 | - VS Code + Continue
699 | - Custom HTTP/SSE clients
700 | - Docker configurations
701 | 
702 | **[→ View all client configuration examples](docs/CLIENT-CONFIGURATIONS.md)**
703 | 
704 | ## 🤝 Contributing
705 | 
706 | We love contributions! This is an open-source project and we welcome improvements.
707 | 
708 | **[→ Read our Contributing Guide](CONTRIBUTING.md)**
709 | 
710 | ### Quick Ways to Contribute
711 | 
712 | - 🐛 **Report bugs** - [Open an issue](https://github.com/flutter-mcp/flutter-mcp/issues)
713 | - 💡 **Suggest features** - [Start a discussion](https://github.com/flutter-mcp/flutter-mcp/discussions)
714 | - 📖 **Improve docs** - Even fixing a typo helps!
715 | - 🧪 **Add tests** - Help us reach 100% coverage
716 | - 🌐 **Add translations** - Make Flutter MCP accessible globally
717 | - ⭐ **Star the repo** - Help others discover Flutter MCP
718 | 
719 | ### 🚀 What's New & Coming Soon
720 | 
721 | **Recently Released:**
722 | - ✅ **Simplified Tools**: Reduced from 5 tools to just 2 main tools (Context7-style)
723 | - ✅ **Smart Detection**: Auto-detects Flutter widgets, Dart classes, and pub packages
724 | - ✅ **Token Limiting**: Default 10,000 tokens with smart truncation
725 | - ✅ **Topic Filtering**: Focus on specific sections (examples, constructors, etc.)
726 | 
727 | **On our roadmap:**
728 | - 📚 Stack Overflow integration for common Flutter questions
729 | - 🎯 Natural language activation: "use flutter docs" pattern
730 | - 🌍 Offline mode for airplane coding
731 | - 🚀 Hosted service option for teams
732 | 
733 | Want to help build these features? [Join us!](CONTRIBUTING.md)
734 | 
735 | ## ❤️ Spread the Word
736 | 
737 | Help other Flutter developers discover AI superpowers:
738 | 
739 | <p align="center">
740 | <a href="https://twitter.com/intent/tweet?text=Just%20gave%20my%20AI%20assistant%20Flutter%20superpowers%20with%20%40flutter_mcp!%20Real-time%20docs%20for%20any%20pub.dev%20package.%20No%20more%20outdated%20code!%20%23Flutter%20%23AI&url=https://github.com/flutter-mcp/flutter-mcp">
741 |   <img src="https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Fgithub.com%2Fflutter-mcp%2Fflutter-mcp" alt="Tweet">
742 | </a>
743 | </p>
744 | 
745 | 
746 | Add the badge to your project:
747 | 
748 | ```markdown
749 | [![Flutter MCP](https://img.shields.io/badge/Enhanced%20by-Flutter%20MCP-blue)](https://github.com/flutter-mcp/flutter-mcp)
750 | ```
751 | 
752 | ## 📄 License
753 | 
754 | MIT © 2024 Flutter MCP Contributors
755 | 
756 | ## 🏗️ Built With
757 | 
758 | - **[Python MCP SDK](https://github.com/modelcontextprotocol/python-sdk)** - The most popular MCP implementation (14k+ stars)
759 | - **[FastMCP](https://github.com/modelcontextprotocol/fastmcp)** - High-level Python framework for MCP servers
760 | - **SQLite** - Built-in caching with zero configuration
761 | - **npm/npx** - Simple one-line installation and execution
762 | - **BeautifulSoup** - Robust HTML parsing
763 | - **httpx** - Modern async HTTP client
764 | 
765 | ---
766 | 
767 | <p align="center">
768 |   <strong>Ready to give your AI Flutter superpowers?</strong>
769 |   <br><br>
770 |   <a href="#-quick-start">Get Started</a> • 
771 |   <a href="https://github.com/flutter-mcp/flutter-mcp/issues">Report Bug</a> • 
772 |   <a href="https://github.com/flutter-mcp/flutter-mcp/discussions">Request Feature</a>
773 |   <br><br>
774 |   Made with ❤️ by the Flutter community
775 | </p>
776 | 
```

--------------------------------------------------------------------------------
/CLAUDE.md:
--------------------------------------------------------------------------------

```markdown
 1 | # CLAUDE.md
 2 | 
 3 | This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
 4 | 
 5 | ## Project Overview
 6 | 
 7 | This is a Flutter/Dart documentation MCP (Model Context Protocol) server project designed to provide AI assistants with seamless access to Flutter and Dart documentation. Following Context7's proven approach, the project uses on-demand web scraping with Redis caching to ensure users always get the most current documentation while maintaining fast response times.
 8 | 
 9 | ## Key Architecture Components
10 | 
11 | 1. **MCP Server**: FastMCP server with on-demand documentation fetching
12 | 2. **Redis Caching**: Fast in-memory cache for processed documentation
13 | 3. **Web Scraping**: Respectful fetching from api.flutter.dev and api.dart.dev
14 | 4. **Pub.dev API**: Official API for package documentation
15 | 5. **Processing Pipeline**: Parse → Enrich → Clean → Cache (Context7-style)
16 | 6. **Rate Limiting**: 2 requests/second to respect server resources
17 | 
18 | ## Development Commands
19 | 
20 | ```bash
21 | # Project setup (using uv package manager)
22 | uv init mcp-server-flutter-docs
23 | cd mcp-server-flutter-docs
24 | uv add "mcp[cli]" httpx redis beautifulsoup4 structlog
25 | 
26 | # Start Redis (required for caching)
27 | redis-server  # In a separate terminal
28 | 
29 | # Development server with MCP Inspector
30 | mcp dev server.py
31 | 
32 | # Run the server
33 | uv run server.py
34 | 
35 | # Alternative with traditional Python
36 | python -m venv venv
37 | source venv/bin/activate  # On Windows: venv\Scripts\activate
38 | pip install "mcp[cli]" httpx redis beautifulsoup4 structlog
39 | python server.py
40 | ```
41 | 
42 | ## Core Implementation Guidelines
43 | 
44 | 1. **On-Demand Fetching**: Fetch documentation only when requested, like Context7
45 | 2. **Redis Caching**: Cache processed docs with appropriate TTLs (24h for APIs, 12h for packages)
46 | 3. **Smart URL Resolution**: Pattern matching to resolve queries to documentation URLs
47 | 4. **Rate Limiting**: RateLimiter class ensuring 2 requests/second max
48 | 5. **Error Handling**: Graceful fallbacks when documentation isn't found
49 | 6. **User Agent**: Always identify as "Flutter-MCP-Docs/1.0" with GitHub URL
50 | 
51 | ## Transport and Distribution
52 | 
53 | - **Primary Transport**: STDIO for local Claude Desktop integration
54 | - **Configuration Path**: `~/Library/Application Support/Claude/claude_desktop_config.json`
55 | - **Distribution Size**: <10MB lightweight package
56 | - **Dependencies**: Redis required (local or external service)
57 | - **Distribution Methods**: PyPI package, npm package, Docker image
58 | - **Versioning**: Semantic versioning (MAJOR.MINOR.PATCH)
59 | 
60 | ## Implementation Timeline
61 | 
62 | 1. **MVP (4 hours)**: Basic server with Flutter API docs
63 | 2. **Week 1**: Add pub.dev support, search functionality
64 | 3. **Week 2**: Polish, documentation, and launch
65 | 4. **Future**: Stack Overflow, cookbook, version-specific docs
```

--------------------------------------------------------------------------------
/docs/CONTRIBUTING.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Contributing to Flutter MCP 🎉
  2 | 
  3 | First off, **thank you** for considering contributing to Flutter MCP! 🙏 This is an open-source community project, and it's people like you who make it possible to give AI assistants real-time Flutter superpowers. Whether you're fixing a typo, reporting a bug, or adding a major feature, every contribution matters!
  4 | 
  5 | ## 🌟 Ways to Contribute
  6 | 
  7 | There are many ways to contribute to Flutter MCP, and we value them all:
  8 | 
  9 | ### 🐛 Report Bugs
 10 | 
 11 | Found something broken? [Open an issue](https://github.com/adamsmaka/flutter-mcp/issues/new?template=bug_report.md) and help us squash it!
 12 | 
 13 | ### 💡 Suggest Features
 14 | 
 15 | Have an idea to make Flutter MCP even better? [Start a discussion](https://github.com/adamsmaka/flutter-mcp/discussions/new?category=ideas) or [open a feature request](https://github.com/adamsmaka/flutter-mcp/issues/new?template=feature_request.md)!
 16 | 
 17 | ### 📖 Improve Documentation
 18 | 
 19 | Even the smallest documentation fix helps! Whether it's fixing a typo, clarifying instructions, or adding examples - documentation is crucial.
 20 | 
 21 | ### 🧪 Write Tests
 22 | 
 23 | Help us maintain quality by adding tests. We aim for high test coverage to ensure Flutter MCP stays reliable.
 24 | 
 25 | ### 🌐 Add Translations
 26 | 
 27 | Make Flutter MCP accessible to developers worldwide by helping with translations.
 28 | 
 29 | ### ⭐ Spread the Word
 30 | 
 31 | Star the repo, share it with your Flutter community, write a blog post, or tweet about your experience!
 32 | 
 33 | ### 💻 Write Code
 34 | 
 35 | Fix bugs, implement features, optimize performance - dive into the code and make Flutter MCP better!
 36 | 
 37 | ## 🚀 Getting Started
 38 | 
 39 | ### Prerequisites
 40 | 
 41 | Before you begin, ensure you have:
 42 | 
 43 | - Python 3.10 or higher
 44 | - Redis installed and running
 45 | - Git for version control
 46 | - A GitHub account
 47 | 
 48 | ### Development Setup
 49 | 
 50 | 1. **Fork the repository**
 51 | 
 52 |    Click the "Fork" button at the top right of the [Flutter MCP repository](https://github.com/adamsmaka/flutter-mcp).
 53 | 
 54 | 2. **Clone your fork**
 55 | 
 56 |    ```bash
 57 |    git clone https://github.com/YOUR-USERNAME/flutter-mcp.git
 58 |    cd flutter-mcp
 59 |    ```
 60 | 
 61 | 3. **Set up the development environment**
 62 | 
 63 |    ```bash
 64 |    # Create a virtual environment
 65 |    python -m venv venv
 66 | 
 67 |    # Activate it
 68 |    source venv/bin/activate  # On Windows: venv\Scripts\activate
 69 | 
 70 |    # Install dependencies in development mode
 71 |    pip install -e ".[dev]"
 72 |    ```
 73 | 
 74 | 4. **Start Redis**
 75 | 
 76 |    ```bash
 77 |    # macOS
 78 |    brew services start redis
 79 | 
 80 |    # Linux
 81 |    sudo systemctl start redis
 82 | 
 83 |    # Docker
 84 |    docker run -d -p 6379:6379 --name flutter-mcp-redis redis:alpine
 85 |    ```
 86 | 
 87 | 5. **Run the development server**
 88 | 
 89 |    ```bash
 90 |    # Run with MCP Inspector for debugging
 91 |    mcp dev src/flutter_mcp/server.py
 92 | 
 93 |    # Or run directly
 94 |    python -m flutter_mcp.server
 95 |    ```
 96 | 
 97 | For more detailed setup instructions, check out our [Development Guide](DEVELOPMENT.md).
 98 | 
 99 | ## 📋 Before You Submit
100 | 
101 | ### 🎨 Code Style Guidelines
102 | 
103 | We use Python's standard style guidelines with a few preferences:
104 | 
105 | - **Black** for code formatting (line length: 88)
106 | - **isort** for import sorting
107 | - **Type hints** for all public functions
108 | - **Docstrings** for all classes and public methods
109 | 
110 | Run the formatters before committing:
111 | 
112 | ```bash
113 | # Format code
114 | black src/ tests/
115 | 
116 | # Sort imports
117 | isort src/ tests/
118 | 
119 | # Check types
120 | mypy src/
121 | 
122 | # Run linter
123 | ruff check src/ tests/
124 | ```
125 | 
126 | ### 🧪 Testing Guidelines
127 | 
128 | All code changes should include tests:
129 | 
130 | ```bash
131 | # Run all tests
132 | pytest
133 | 
134 | # Run with coverage
135 | pytest --cov=flutter_mcp
136 | 
137 | # Run specific test file
138 | pytest tests/test_server.py
139 | 
140 | # Run tests in watch mode
141 | pytest-watch
142 | ```
143 | 
144 | We aim for at least 80% test coverage. Write tests that:
145 | 
146 | - Cover both happy paths and edge cases
147 | - Are isolated and don't depend on external services
148 | - Use mocks for Redis and external API calls
149 | - Have descriptive names that explain what they test
150 | 
151 | ### 📝 Commit Messages
152 | 
153 | We follow the [Conventional Commits](https://www.conventionalcommits.org/) specification:
154 | 
155 | ```
156 | feat: add support for package version constraints
157 | fix: handle rate limiting from pub.dev API
158 | docs: update Redis installation instructions
159 | test: add tests for cache expiration
160 | refactor: extract documentation parser into separate module
161 | ```
162 | 
163 | ## 🔄 Pull Request Process
164 | 
165 | ### 1. Create a Feature Branch
166 | 
167 | ```bash
168 | git checkout -b feature/your-feature-name
169 | # or
170 | git checkout -b fix/issue-description
171 | ```
172 | 
173 | ### 2. Make Your Changes
174 | 
175 | - Write clean, readable code
176 | - Add tests for new functionality
177 | - Update documentation if needed
178 | - Ensure all tests pass
179 | 
180 | ### 3. Commit Your Changes
181 | 
182 | ```bash
183 | git add .
184 | git commit -m "feat: add amazing new feature"
185 | ```
186 | 
187 | ### 4. Push to Your Fork
188 | 
189 | ```bash
190 | git push origin feature/your-feature-name
191 | ```
192 | 
193 | ### 5. Open a Pull Request
194 | 
195 | 1. Go to the [Flutter MCP repository](https://github.com/adamsmaka/flutter-mcp)
196 | 2. Click "Compare & pull request"
197 | 3. Fill out the PR template:
198 |    - Describe what changes you made
199 |    - Link any related issues
200 |    - Include screenshots if relevant
201 |    - Check all the boxes in the checklist
202 | 
203 | ### 6. Code Review
204 | 
205 | - Be patient and respectful during review
206 | - Respond to feedback constructively
207 | - Make requested changes promptly
208 | - Ask questions if something isn't clear
209 | 
210 | ## 🐛 Reporting Bugs
211 | 
212 | Found a bug? Help us fix it by providing detailed information:
213 | 
214 | 1. **Search existing issues** first to avoid duplicates
215 | 2. **Use the bug report template** when creating an issue
216 | 3. **Include**:
217 |    - Flutter MCP version (`flutter-mcp --version`)
218 |    - Python version (`python --version`)
219 |    - OS and version
220 |    - Steps to reproduce
221 |    - Expected behavior
222 |    - Actual behavior
223 |    - Error messages/logs
224 |    - Screenshots if applicable
225 | 
226 | ## 💡 Requesting Features
227 | 
228 | Have an idea? We'd love to hear it!
229 | 
230 | 1. **Check existing issues and discussions** first
231 | 2. **Use the feature request template**
232 | 3. **Explain**:
233 |    - The problem you're trying to solve
234 |    - Your proposed solution
235 |    - Alternative solutions you've considered
236 |    - How it benefits other users
237 | 
238 | ## 🤝 Community Guidelines
239 | 
240 | ### Our Code of Conduct
241 | 
242 | We're committed to providing a welcoming and inclusive environment. By participating, you agree to:
243 | 
244 | - **Be respectful** - Treat everyone with respect
245 | - **Be constructive** - Provide helpful feedback
246 | - **Be inclusive** - Welcome newcomers and help them get started
247 | - **Be patient** - Remember that everyone is volunteering their time
248 | - **Be professional** - Keep discussions focused and productive
249 | 
250 | ### Getting Help
251 | 
252 | - 💬 **Discord**: Join our [Flutter MCP Discord](https://discord.gg/flutter-mcp)
253 | - 🤔 **Discussions**: Ask questions in [GitHub Discussions](https://github.com/adamsmaka/flutter-mcp/discussions)
254 | - 📧 **Email**: Reach out to [email protected]
255 | 
256 | ## 🏆 Recognition
257 | 
258 | We believe in recognizing our contributors!
259 | 
260 | ### All Contributors
261 | 
262 | We use the [All Contributors](https://allcontributors.org/) specification to recognize everyone who helps make Flutter MCP better. Contributors are automatically added to our README.
263 | 
264 | ### Types of Contributions We Recognize
265 | 
266 | - 💻 Code
267 | - 📖 Documentation
268 | - 🎨 Design
269 | - 💡 Ideas & Planning
270 | - 🧪 Testing
271 | - 🐛 Bug Reports
272 | - 👀 Code Reviews
273 | - 📢 Evangelism
274 | - 🌍 Translation
275 | - 💬 Answering Questions
276 | - 🚧 Maintenance
277 | - 🔧 Tools
278 | - 📦 Packaging
279 | 
280 | ## 📚 Additional Resources
281 | 
282 | - [Development Guide](DEVELOPMENT.md) - Detailed development setup
283 | - [Architecture Overview](docs/ARCHITECTURE.md) - How Flutter MCP works
284 | - [API Reference](docs/API.md) - Server API documentation
285 | - [Testing Guide](docs/TESTING.md) - How to write effective tests
286 | 
287 | ## 🎯 Current Priorities
288 | 
289 | Check our [Project Board](https://github.com/adamsmaka/flutter-mcp/projects) for current priorities. Good first issues are labeled with [`good first issue`](https://github.com/adamsmaka/flutter-mcp/labels/good%20first%20issue).
290 | 
291 | ### Quick Wins for New Contributors
292 | 
293 | - Fix typos or improve documentation clarity
294 | - Add missing tests for existing functionality
295 | - Improve error messages
296 | - Add code examples to documentation
297 | - Help triage issues
298 | 
299 | ## 🚢 Release Process
300 | 
301 | We use semantic versioning and release regularly:
302 | 
303 | - **Patch releases** (x.x.1) - Bug fixes, documentation updates
304 | - **Minor releases** (x.1.0) - New features, non-breaking changes
305 | - **Major releases** (1.0.0) - Breaking changes (rare)
306 | 
307 | Releases are automated through GitHub Actions when maintainers tag a new version.
308 | 
309 | ---
310 | 
311 | <p align="center">
312 |   <strong>Ready to contribute?</strong>
313 |   <br><br>
314 |   Remember: no contribution is too small! Whether you're fixing a typo or adding a major feature, you're helping make AI + Flutter development better for everyone.
315 |   <br><br>
316 |   <strong>Thank you for being awesome! 🎉</strong>
317 |   <br><br>
318 |   Made with ❤️ by the Flutter MCP community
319 | </p>
320 | 
```

--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------

```python
1 | """Flutter MCP Server test suite."""
```

--------------------------------------------------------------------------------
/src/flutter_mcp/__main__.py:
--------------------------------------------------------------------------------

```python
1 | #!/usr/bin/env python3
2 | """Main entry point for Flutter MCP Server executable"""
3 | 
4 | if __name__ == "__main__":
5 |     from .cli import main
6 |     main()
```

--------------------------------------------------------------------------------
/src/flutter_mcp/__init__.py:
--------------------------------------------------------------------------------

```python
1 | """Flutter MCP Server - Real-time Flutter/Dart documentation for AI assistants."""
2 | 
3 | __version__ = "0.1.0"
4 | __author__ = "Flutter MCP Team"
5 | __email__ = "[email protected]"
6 | 
7 | from .server import mcp, main
8 | 
9 | __all__ = ["mcp", "main"]
```

--------------------------------------------------------------------------------
/docker/docker-compose.yml:
--------------------------------------------------------------------------------

```yaml
 1 | version: '3.8'
 2 | 
 3 | services:
 4 |   flutter-mcp:
 5 |     build:
 6 |       context: ..
 7 |       dockerfile: docker/Dockerfile
 8 |     container_name: flutter-mcp-server
 9 |     environment:
10 |       - PYTHONUNBUFFERED=1
11 |     volumes:
12 |       # Mount source code for development
13 |       - ../src:/app/src:ro
14 |       # Persist cache between restarts
15 |       - cache-data:/app/.cache
16 |     stdin_open: true
17 |     tty: true
18 |     restart: unless-stopped
19 |     ports:
20 |       - "8000:8000"
21 | 
22 | volumes:
23 |   cache-data:
```

--------------------------------------------------------------------------------
/npm-wrapper/publish.sh:
--------------------------------------------------------------------------------

```bash
 1 | #!/bin/bash
 2 | # Script to publish the npm wrapper package
 3 | 
 4 | echo "Publishing @flutter-mcp/server to npm..."
 5 | 
 6 | # Check if logged in to npm
 7 | if ! npm whoami &> /dev/null; then
 8 |     echo "Error: Not logged in to npm. Please run 'npm login' first."
 9 |     exit 1
10 | fi
11 | 
12 | # Clean any previous builds
13 | rm -rf node_modules package-lock.json
14 | 
15 | # Install dependencies
16 | echo "Installing dependencies..."
17 | npm install
18 | 
19 | # Run prepublish script
20 | npm run prepublishOnly
21 | 
22 | # Publish to npm
23 | echo "Publishing to npm..."
24 | npm publish --access public
25 | 
26 | echo "✅ Published successfully!"
27 | echo ""
28 | echo "Users can now install with:"
29 | echo "  npx @flutter-mcp/server"
```

--------------------------------------------------------------------------------
/.github/workflows/publish-pypi.yml:
--------------------------------------------------------------------------------

```yaml
 1 | name: Publish to PyPI
 2 | 
 3 | on:
 4 |   push:
 5 |     tags:
 6 |       - 'v*'
 7 |   workflow_dispatch:
 8 | 
 9 | jobs:
10 |   build-and-publish:
11 |     runs-on: ubuntu-latest
12 |     
13 |     steps:
14 |     - uses: actions/checkout@v4
15 |     
16 |     - name: Set up Python
17 |       uses: actions/setup-python@v5
18 |       with:
19 |         python-version: '3.11'
20 |     
21 |     - name: Install build dependencies
22 |       run: |
23 |         python -m pip install --upgrade pip
24 |         pip install build twine
25 |     
26 |     - name: Build package
27 |       run: python -m build
28 |     
29 |     - name: Check package
30 |       run: twine check dist/*
31 |     
32 |     - name: Publish to PyPI
33 |       if: startsWith(github.ref, 'refs/tags/v')
34 |       env:
35 |         TWINE_USERNAME: __token__
36 |         TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
37 |       run: |
38 |         twine upload dist/*
```

--------------------------------------------------------------------------------
/QUICK_FIX.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Quick Fix for MCP SuperAssistant Users
 2 | 
 3 | ## For Users Who Already Installed from Source
 4 | 
 5 | 1. **Pull the latest changes**:
 6 | ```bash
 7 | cd flutter-mcp  # or wherever you cloned it
 8 | git pull
 9 | ```
10 | 
11 | 2. **Reinstall with new features**:
12 | ```bash
13 | pip install -e .
14 | ```
15 | 
16 | 3. **Start with HTTP transport**:
17 | ```bash
18 | flutter-mcp start --transport http --port 8000
19 | ```
20 | 
21 | 4. **Configure MCP SuperAssistant**:
22 | - URL: `http://localhost:8000`
23 | - Type: HTTP MCP Server
24 | 
25 | That's it! The HTTP transport support is now available.
26 | 
27 | ## Alternative: Direct GitHub Install
28 | 
29 | If you haven't cloned the repo:
30 | ```bash
31 | pip install git+https://github.com/flutter-mcp/flutter-mcp.git
32 | flutter-mcp start --transport http --port 8000
33 | ```
34 | 
35 | ## Troubleshooting
36 | 
37 | If `flutter-mcp` command not found:
38 | ```bash
39 | python -m flutter_mcp.cli start --transport http --port 8000
40 | ```
41 | 
42 | Or from the source directory:
43 | ```bash
44 | cd src
45 | python -m flutter_mcp start --transport http --port 8000
46 | ```
```

--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Changelog
 2 | 
 3 | All notable changes to this project will be documented in this file.
 4 | 
 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
 7 | 
 8 | ## [0.1.1] - 2025-06-28
 9 | 
10 | ### Fixed
11 | - Fixed HTTP and SSE transport modes that were failing with FastMCP API errors
12 |   - Removed incorrect `sse_params` parameter usage 
13 |   - Removed `get_asgi_app()` call that doesn't exist in FastMCP
14 |   - FastMCP now handles HTTP transport internally without uvicorn
15 | 
16 | ### Changed
17 | - Removed uvicorn dependency as it's no longer needed (FastMCP handles HTTP transport internally)
18 | 
19 | ## [0.1.0] - 2025-06-22
20 | 
21 | ### Added
22 | - Initial release of Flutter MCP Server
23 | - Real-time Flutter and Dart documentation fetching
24 | - pub.dev package documentation support
25 | - SQLite caching for performance
26 | - Multiple transport modes: stdio, HTTP, SSE
27 | - Rich CLI interface with progress indicators
```

--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------

```dockerfile
 1 | # Flutter MCP Server Docker Image
 2 | # Build from project root: docker build -f docker/Dockerfile -t flutter-mcp .
 3 | FROM python:3.11-slim
 4 | 
 5 | # Install system dependencies
 6 | RUN apt-get update && apt-get install -y \
 7 |     git \
 8 |     && rm -rf /var/lib/apt/lists/*
 9 | 
10 | # Set working directory
11 | WORKDIR /app
12 | 
13 | # Copy project files
14 | COPY pyproject.toml setup.py ./
15 | COPY src ./src
16 | COPY docs/README.md LICENSE ./
17 | 
18 | # Install Python dependencies
19 | RUN pip install --no-cache-dir -e .
20 | 
21 | # Expose MCP default port (optional, MCP uses stdio by default)
22 | EXPOSE 8000
23 | 
24 | # Set environment variables
25 | ENV PYTHONUNBUFFERED=1
26 | ENV CACHE_DIR=/app/.cache
27 | 
28 | # Health check using our health_check tool
29 | HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
30 |     CMD python -c "import asyncio; import sys; sys.path.insert(0, '/app/src'); from flutter_mcp.server import health_check; print(asyncio.run(health_check()))"
31 | 
32 | # Run the MCP server
33 | CMD ["python", "-m", "flutter_mcp.server"]
```

--------------------------------------------------------------------------------
/npm-wrapper/package.json:
--------------------------------------------------------------------------------

```json
 1 | {
 2 |   "name": "flutter-mcp",
 3 |   "version": "0.1.1",
 4 |   "description": "NPM wrapper for Flutter MCP Server - Real-time Flutter/Dart documentation for AI assistants",
 5 |   "main": "index.js",
 6 |   "bin": {
 7 |     "flutter-mcp": "bin/flutter-mcp.js"
 8 |   },
 9 |   "scripts": {
10 |     "test": "echo \"No tests for wrapper\"",
11 |     "postinstall": "node scripts/install.js",
12 |     "prepublishOnly": "node -e \"console.log('Preparing to publish Flutter MCP npm wrapper...')\""
13 |   },
14 |   "keywords": [
15 |     "flutter",
16 |     "dart",
17 |     "mcp",
18 |     "ai",
19 |     "claude",
20 |     "documentation",
21 |     "pub.dev"
22 |   ],
23 |   "author": "Flutter MCP Team",
24 |   "license": "MIT",
25 |   "repository": {
26 |     "type": "git",
27 |     "url": "git+https://github.com/flutter-mcp/flutter-mcp.git"
28 |   },
29 |   "bugs": {
30 |     "url": "https://github.com/flutter-mcp/flutter-mcp/issues"
31 |   },
32 |   "homepage": "https://github.com/flutter-mcp/flutter-mcp#readme",
33 |   "preferGlobal": true,
34 |   "engines": {
35 |     "node": ">=16.0.0"
36 |   },
37 |   "dependencies": {
38 |     "execa": "^8.0.1",
39 |     "ora": "^8.0.1",
40 |     "which": "^4.0.0"
41 |   }
42 | }
43 | 
```

--------------------------------------------------------------------------------
/scripts/publish-pypi.sh:
--------------------------------------------------------------------------------

```bash
 1 | #!/bin/bash
 2 | # Script to publish Flutter MCP Server to PyPI
 3 | 
 4 | set -e  # Exit on error
 5 | 
 6 | echo "🚀 Publishing Flutter MCP Server to PyPI..."
 7 | 
 8 | # Check Python version
 9 | PYTHON_VERSION=$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')
10 | echo "Python version: $PYTHON_VERSION"
11 | 
12 | # Clean previous builds
13 | echo "🧹 Cleaning previous builds..."
14 | rm -rf dist/ build/ *.egg-info src/*.egg-info
15 | 
16 | # Install build tools
17 | echo "📦 Installing build tools..."
18 | pip install --upgrade pip setuptools wheel twine build
19 | 
20 | # Build the package
21 | echo "🔨 Building package..."
22 | python -m build
23 | 
24 | # Check the package
25 | echo "✅ Checking package with twine..."
26 | twine check dist/*
27 | 
28 | # Show what will be uploaded
29 | echo ""
30 | echo "📦 Package contents:"
31 | ls -la dist/
32 | 
33 | echo ""
34 | echo "⚠️  Ready to upload to PyPI!"
35 | echo "To upload to TestPyPI first (recommended):"
36 | echo "  twine upload --repository testpypi dist/*"
37 | echo ""
38 | echo "To upload to PyPI:"
39 | echo "  twine upload dist/*"
40 | echo ""
41 | echo "Note: You'll need PyPI credentials configured in ~/.pypirc or use:"
42 | echo "  export TWINE_USERNAME=__token__"
43 | echo "  export TWINE_PASSWORD=<your-pypi-token>"
```

--------------------------------------------------------------------------------
/scripts/test-server.sh:
--------------------------------------------------------------------------------

```bash
 1 | #!/bin/bash
 2 | # Test script for Flutter MCP Server
 3 | 
 4 | echo "🚀 Flutter MCP Server Test Script"
 5 | echo "================================"
 6 | 
 7 | # Check if Redis is running
 8 | if command -v redis-cli &> /dev/null; then
 9 |     if redis-cli ping &> /dev/null; then
10 |         echo "✅ Redis is running"
11 |     else
12 |         echo "❌ Redis is not running. Starting Redis..."
13 |         if command -v redis-server &> /dev/null; then
14 |             redis-server --daemonize yes
15 |             echo "✅ Redis started"
16 |         else
17 |             echo "❌ Redis is not installed. Please install Redis first:"
18 |             echo "   macOS: brew install redis"
19 |             echo "   Ubuntu: sudo apt-get install redis-server"
20 |             echo ""
21 |             echo "The server will run without caching (slower responses)"
22 |         fi
23 |     fi
24 | else
25 |     echo "⚠️  Redis CLI not found. The server will run without caching."
26 | fi
27 | 
28 | # Check if uv is available
29 | if ! command -v uv &> /dev/null; then
30 |     # Source uv if installed locally
31 |     if [ -f "$HOME/.local/bin/env" ]; then
32 |         source "$HOME/.local/bin/env"
33 |     fi
34 | fi
35 | 
36 | echo ""
37 | echo "Starting MCP Inspector..."
38 | echo "========================="
39 | 
40 | # Run with MCP Inspector
41 | if command -v uv &> /dev/null; then
42 |     uv run mcp dev src/flutter_mcp/server.py
43 | else
44 |     echo "❌ uv not found. Please install uv first:"
45 |     echo "   curl -LsSf https://astral.sh/uv/install.sh | sh"
46 |     echo ""
47 |     echo "Or run directly with Python:"
48 |     echo "   python -m src.flutter_mcp.server"
49 | fi
```

--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------

```toml
 1 | [project]
 2 | name = "flutter-mcp-server"
 3 | version = "0.1.1"
 4 | description = "MCP server providing real-time Flutter/Dart documentation to AI assistants"
 5 | readme = "docs/README.md"
 6 | license = {text = "MIT"}
 7 | authors = [{name = "Flutter MCP Contributors"}]
 8 | keywords = ["flutter", "dart", "mcp", "ai", "documentation", "pubdev"]
 9 | classifiers = [
10 |     "Development Status :: 4 - Beta",
11 |     "Intended Audience :: Developers",
12 |     "License :: OSI Approved :: MIT License",
13 |     "Programming Language :: Python :: 3",
14 |     "Programming Language :: Python :: 3.10",
15 |     "Programming Language :: Python :: 3.11",
16 |     "Programming Language :: Python :: 3.12",
17 |     "Topic :: Software Development :: Documentation",
18 |     "Topic :: Software Development :: Libraries :: Python Modules",
19 | ]
20 | requires-python = ">=3.10"
21 | dependencies = [
22 |     "aiofiles>=24.1.0",
23 |     "beautifulsoup4>=4.13.4",
24 |     "httpx>=0.28.1",
25 |     "humanize>=4.11.0",
26 |     "mcp @ git+https://github.com/modelcontextprotocol/python-sdk.git@main",
27 |     "platformdirs>=4.0.0",
28 |     "rich>=13.10.0",
29 |     "structlog>=25.4.0",
30 | ]
31 | 
32 | [project.urls]
33 | "Homepage" = "https://github.com/flutter-mcp/flutter-mcp"
34 | "Bug Reports" = "https://github.com/flutter-mcp/flutter-mcp/issues"
35 | "Source" = "https://github.com/flutter-mcp/flutter-mcp"
36 | 
37 | [project.scripts]
38 | flutter-mcp = "flutter_mcp.cli:main"
39 | 
40 | [build-system]
41 | requires = ["setuptools>=61.0", "wheel"]
42 | build-backend = "setuptools.build_meta"
43 | 
44 | [tool.setuptools]
45 | package-dir = {"" = "src"}
46 | packages = ["flutter_mcp"]
47 | 
```

--------------------------------------------------------------------------------
/docs/planning/task-summary.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Task Summary: Who Does What
 2 | 
 3 | ## Tasks Claude Can Do (41 tasks)
 4 | All code implementation, documentation writing, and technical content creation:
 5 | - ✅ All Python code development (server, tools, parsers)
 6 | - ✅ Writing README, API docs, blog posts
 7 | - ✅ Creating comparison tables and demos
 8 | - ✅ Designing badges and templates
 9 | - ✅ Writing marketing copy and Reddit posts
10 | - ✅ Creating Docker/PyPI/npm packages
11 | 
12 | ## Tasks You Need to Do Manually (13 tasks)
13 | Personal actions and real-world engagement:
14 | - 🤝 Reaching out to influencers (T027, T045, T049)
15 | - 📹 Recording demo videos/GIFs (T014, T057)
16 | - 💬 Joining Discord and being active (T018, T044)
17 | - 📊 Creating Google Form for testimonials (T041)
18 | - 🚀 Posting to Reddit/Twitter/YouTube (T028, T060)
19 | - 🎥 Hosting live coding sessions (T056)
20 | - 🧪 Running load tests (T029)
21 | - 🔍 Testing with MCP Inspector (T011)
22 | 
23 | ## Tasks We Do Together (6 tasks)
24 | Collaborative efforts:
25 | - 🤝 Testing with popular packages (T010)
26 | - 🤝 Setting up GitHub repository (T017)
27 | - 🤝 Creating feedback system (T033)
28 | - 🤝 Planning launch week (T051)
29 | - 🤝 Writing weekly Flutter AI tips (T054)
30 | - 🤝 Creating press kit (T059 - I write, you add logo/screenshots)
31 | 
32 | ## Quick Stats
33 | - **Claude does**: 68% of tasks (mostly technical)
34 | - **You do**: 22% of tasks (mostly community/marketing)
35 | - **Together**: 10% of tasks (planning and ongoing work)
36 | 
37 | This division lets Claude handle all the heavy technical lifting while you focus on human connections and visual content creation!
```

--------------------------------------------------------------------------------
/scripts/build-executables.sh:
--------------------------------------------------------------------------------

```bash
 1 | #!/bin/bash
 2 | # Build standalone executables for Flutter MCP Server
 3 | 
 4 | set -e
 5 | 
 6 | echo "🔨 Building Flutter MCP Server executables..."
 7 | 
 8 | # Ensure we're in the project root
 9 | cd "$(dirname "$0")/.."
10 | 
11 | # Install PyInstaller if not already installed
12 | pip install pyinstaller
13 | 
14 | # Clean previous builds
15 | echo "🧹 Cleaning previous builds..."
16 | rm -rf build dist
17 | 
18 | # Build the executable
19 | echo "🏗️ Building executable..."
20 | pyinstaller build.spec
21 | 
22 | # Create release directory
23 | mkdir -p releases
24 | 
25 | # Get the platform
26 | PLATFORM=$(python -c "import platform; print(platform.system().lower())")
27 | ARCH=$(python -c "import platform; print(platform.machine())")
28 | 
29 | # Move and rename based on platform
30 | if [ "$PLATFORM" = "darwin" ]; then
31 |     if [ "$ARCH" = "arm64" ]; then
32 |         BINARY_NAME="flutter-mcp-macos-arm64"
33 |     else
34 |         BINARY_NAME="flutter-mcp-macos-x64"
35 |     fi
36 | elif [ "$PLATFORM" = "linux" ]; then
37 |     BINARY_NAME="flutter-mcp-linux-x64"
38 | elif [ "$PLATFORM" = "windows" ]; then
39 |     BINARY_NAME="flutter-mcp-windows-x64.exe"
40 | else
41 |     BINARY_NAME="flutter-mcp-$PLATFORM-$ARCH"
42 | fi
43 | 
44 | # Move the binary
45 | mv "dist/flutter-mcp" "releases/$BINARY_NAME" 2>/dev/null || \
46 | mv "dist/flutter-mcp.exe" "releases/$BINARY_NAME" 2>/dev/null
47 | 
48 | echo "✅ Build complete! Binary available at: releases/$BINARY_NAME"
49 | 
50 | # Test the binary
51 | echo "🧪 Testing the binary..."
52 | "./releases/$BINARY_NAME" --version
53 | 
54 | echo "
55 | 📦 Binary details:"
56 | ls -lh "releases/$BINARY_NAME"
57 | file "releases/$BINARY_NAME"
58 | 
59 | echo "
60 | 🚀 To distribute, upload releases/$BINARY_NAME to GitHub Releases"
```

--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------

```python
 1 | #!/usr/bin/env python3
 2 | """Setup script for Flutter MCP Server - for backward compatibility only.
 3 | Please use pip install with pyproject.toml for modern installations."""
 4 | 
 5 | from setuptools import setup, find_packages
 6 | 
 7 | # Read long description from README
 8 | with open("docs/README.md", "r", encoding="utf-8") as fh:
 9 |     long_description = fh.read()
10 | 
11 | setup(
12 |     name="flutter-mcp-server",
13 |     version="0.1.0",
14 |     author="Flutter MCP Contributors",
15 |     description="MCP server providing real-time Flutter/Dart documentation to AI assistants",
16 |     long_description=long_description,
17 |     long_description_content_type="text/markdown",
18 |     url="https://github.com/flutter-mcp/flutter-mcp",
19 |     packages=find_packages(where="src"),
20 |     package_dir={"": "src"},
21 |     classifiers=[
22 |         "Development Status :: 4 - Beta",
23 |         "Intended Audience :: Developers",
24 |         "License :: OSI Approved :: MIT License",
25 |         "Programming Language :: Python :: 3",
26 |         "Programming Language :: Python :: 3.10",
27 |         "Programming Language :: Python :: 3.11",
28 |         "Programming Language :: Python :: 3.12",
29 |         "Topic :: Software Development :: Documentation",
30 |     ],
31 |     python_requires=">=3.10",
32 |     install_requires=[
33 |         "aiofiles>=24.1.0",
34 |         "beautifulsoup4>=4.13.4",
35 |         "httpx>=0.28.1",
36 |         "mcp @ git+https://github.com/modelcontextprotocol/python-sdk.git@main",
37 |         "platformdirs>=4.0.0",
38 |         "structlog>=25.4.0",
39 |     ],
40 |     entry_points={
41 |         "console_scripts": [
42 |             "flutter-mcp=flutter_mcp.cli:main",
43 |         ],
44 |     },
45 | )
```

--------------------------------------------------------------------------------
/npm-wrapper/index.js:
--------------------------------------------------------------------------------

```javascript
 1 | /**
 2 |  * Flutter MCP Server Node.js wrapper
 3 |  * Main entry point for programmatic usage
 4 |  */
 5 | 
 6 | const { execa } = require('execa');
 7 | const which = require('which');
 8 | 
 9 | class FlutterMCPServer {
10 |   constructor(options = {}) {
11 |     this.pythonCmd = null;
12 |     this.options = {
13 |       stdio: options.stdio || false,
14 |       debug: options.debug || false,
15 |       ...options
16 |     };
17 |   }
18 | 
19 |   async findPython() {
20 |     if (this.pythonCmd) return this.pythonCmd;
21 |     
22 |     const pythonCommands = ['python3', 'python'];
23 |     
24 |     for (const cmd of pythonCommands) {
25 |       try {
26 |         await which(cmd);
27 |         const { stdout } = await execa(cmd, ['--version']);
28 |         const match = stdout.match(/Python (\d+)\.(\d+)/);
29 |         if (match) {
30 |           const major = parseInt(match[1]);
31 |           const minor = parseInt(match[2]);
32 |           if (major >= 3 && minor >= 8) {
33 |             this.pythonCmd = cmd;
34 |             return cmd;
35 |           }
36 |         }
37 |       } catch (e) {
38 |         // Continue to next command
39 |       }
40 |     }
41 |     throw new Error('Python 3.8+ is required but not found');
42 |   }
43 | 
44 |   async ensureInstalled() {
45 |     const pythonCmd = await this.findPython();
46 |     
47 |     try {
48 |       await execa(pythonCmd, ['-m', 'flutter_mcp', '--version']);
49 |       return true;
50 |     } catch (e) {
51 |       // Try to install
52 |       await execa(pythonCmd, ['-m', 'pip', 'install', 'flutter-mcp-server']);
53 |       return true;
54 |     }
55 |   }
56 | 
57 |   async start() {
58 |     await this.ensureInstalled();
59 |     const pythonCmd = await this.findPython();
60 |     
61 |     const args = ['-m', 'flutter_mcp'];
62 |     if (this.options.stdio) {
63 |       args.push('--stdio');
64 |     }
65 |     
66 |     const subprocess = execa(pythonCmd, args, {
67 |       stdio: this.options.stdio ? 'inherit' : 'pipe'
68 |     });
69 |     
70 |     return subprocess;
71 |   }
72 | 
73 |   async stop() {
74 |     // Implement stop functionality if needed
75 |   }
76 | }
77 | 
78 | module.exports = FlutterMCPServer;
```

--------------------------------------------------------------------------------
/docs/planning/README-highlights.md:
--------------------------------------------------------------------------------

```markdown
 1 | # README Highlights & Marketing Psychology
 2 | 
 3 | ## Key Psychological Triggers We've Implemented
 4 | 
 5 | ### 1. **Problem Agitation → Solution**
 6 | - Opens with relatable pain: "Stop fighting with hallucinated widgets"
 7 | - Visual before/after table validates frustration
 8 | - Immediate solution: "Real-time Flutter superpowers"
 9 | 
10 | ### 2. **Trust Signals**
11 | - "100% Private - your code never leaves your machine"
12 | - Built on "battle-tested Python MCP SDK (14k+ stars)"
13 | - Error handling transparency
14 | - Performance metrics with concrete numbers
15 | 
16 | ### 3. **Social Proof**
17 | - Success stories section
18 | - Pre-written tweet for easy sharing
19 | - Community testimonials
20 | - "Made with ❤️ by the Flutter community"
21 | 
22 | ### 4. **Low Friction Onboarding**
23 | - "Get Started in 2 Minutes" (realistic)
24 | - Platform-specific install commands
25 | - Claude Desktop auto-start (huge win!)
26 | - Natural language usage (no special syntax required)
27 | 
28 | ### 5. **FOMO & Urgency**
29 | - "Give your AI Flutter superpowers"
30 | - "50,000+ packages on pub.dev"
31 | - Coming soon features create anticipation
32 | - Badge for projects creates viral loop
33 | 
34 | ## Technical Clarity Achieved
35 | 
36 | 1. **Redis Dependency** - Upfront with easy install options
37 | 2. **MCP Pattern** - Both natural and explicit usage shown
38 | 3. **Performance** - Clear expectations (1-2s first, <50ms cached)
39 | 4. **Architecture** - "Local RAG server" positioning
40 | 5. **Error Handling** - What happens when things fail
41 | 
42 | ## Marketing Positioning
43 | 
44 | - **Hero Message**: "Give Your AI Real-Time Flutter Superpowers"
45 | - **Value Prop**: Ensure Flutter code actually works
46 | - **Differentiator**: Real-time docs for ANY pub.dev package
47 | - **Target Audience**: Flutter devs using AI assistants
48 | 
49 | ## Viral Elements
50 | 
51 | 1. Click-to-tweet with pre-written message
52 | 2. "Powered by Flutter MCP" badge for projects
53 | 3. Coming soon features create discussion
54 | 4. Easy contribution paths build community
55 | 
56 | ## Next Steps for Launch
57 | 
58 | 1. Create demo GIF/video showing the magic
59 | 2. Write technical blog post for launch
60 | 3. Prepare GitHub repository with issues/discussions
61 | 4. Contact Flutter influencers for early access
62 | 5. Plan Reddit launch post for "Show-off Saturday"
```

--------------------------------------------------------------------------------
/tests/test_tools.py:
--------------------------------------------------------------------------------

```python
 1 | #!/usr/bin/env python3
 2 | """Test script for Flutter MCP tools"""
 3 | 
 4 | import asyncio
 5 | import json
 6 | import sys
 7 | from pathlib import Path
 8 | 
 9 | # Add the src directory to the Python path
10 | sys.path.insert(0, str(Path(__file__).parent.parent / 'src'))
11 | 
12 | from flutter_mcp.server import get_flutter_docs, search_flutter_docs, get_pub_package_info, process_flutter_mentions
13 | 
14 | async def test_tools():
15 |     print("🧪 Testing Flutter MCP Tools")
16 |     print("=" * 50)
17 |     
18 |     # Test 1: Get Flutter docs
19 |     print("\n1. Testing get_flutter_docs for Container widget:")
20 |     result = await get_flutter_docs("Container", "widgets")
21 |     print(f"   Source: {result.get('source', 'unknown')}")
22 |     print(f"   Content length: {len(result.get('content', ''))} chars")
23 |     print(f"   Has error: {'error' in result}")
24 |     
25 |     # Test 2: Search Flutter docs
26 |     print("\n2. Testing search_flutter_docs for material.AppBar:")
27 |     result = await search_flutter_docs("material.AppBar")
28 |     print(f"   Total results: {result.get('total', 0)}")
29 |     if result.get('results'):
30 |         print(f"   First result source: {result['results'][0].get('source', 'unknown')}")
31 |     
32 |     # Test 3: Get pub package info with README
33 |     print("\n3. Testing get_pub_package_info for provider package:")
34 |     result = await get_pub_package_info("provider")
35 |     print(f"   Source: {result.get('source', 'unknown')}")
36 |     print(f"   Version: {result.get('version', 'unknown')}")
37 |     print(f"   Has README: {'readme' in result}")
38 |     if 'readme' in result:
39 |         print(f"   README length: {len(result['readme'])} chars")
40 |     
41 |     # Test 4: Process Flutter mentions
42 |     print("\n4. Testing process_flutter_mentions:")
43 |     test_text = """
44 |     I want to use @flutter_mcp provider for state management.
45 |     Also need docs for @flutter_mcp material.Scaffold widget.
46 |     """
47 |     result = await process_flutter_mentions(test_text)
48 |     print(f"   Found mentions: {result.get('mentions_found', 0)}")
49 |     for mention in result.get('results', []):
50 |         print(f"   - {mention.get('mention', '')} -> {mention.get('type', 'unknown')}")
51 |     
52 |     print("\n✅ All tests completed!")
53 | 
54 | if __name__ == "__main__":
55 |     asyncio.run(test_tools())
```

--------------------------------------------------------------------------------
/docs/DEVELOPMENT.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Flutter MCP Server Development Guide
  2 | 
  3 | ## Quick Start
  4 | 
  5 | 1. **Install Redis** (required for caching):
  6 |    ```bash
  7 |    # macOS
  8 |    brew install redis && brew services start redis
  9 |    
 10 |    # Ubuntu/Debian
 11 |    sudo apt-get install redis-server
 12 |    
 13 |    # Docker (alternative)
 14 |    docker run -d -p 6379:6379 --name flutter-mcp-redis redis:alpine
 15 |    ```
 16 | 
 17 | 2. **Run the test script**:
 18 |    ```bash
 19 |    ./test-server.sh
 20 |    ```
 21 | 
 22 |    This will:
 23 |    - Check if Redis is running
 24 |    - Start the MCP Inspector
 25 |    - Open a web interface at http://localhost:5173
 26 | 
 27 | 3. **Test the tools** in MCP Inspector:
 28 |    
 29 |    **Get Flutter documentation:**
 30 |    ```json
 31 |    {
 32 |      "class_name": "Container",
 33 |      "library": "widgets"
 34 |    }
 35 |    ```
 36 |    
 37 |    **Search Flutter docs:**
 38 |    ```json
 39 |    {
 40 |      "query": "material.AppBar"
 41 |    }
 42 |    ```
 43 |    
 44 |    **Get pub.dev package info:**
 45 |    ```json
 46 |    {
 47 |      "package_name": "provider"
 48 |    }
 49 |    ```
 50 | 
 51 | ## Development Commands
 52 | 
 53 | ```bash
 54 | # Install dependencies
 55 | uv sync
 56 | 
 57 | # Run server directly
 58 | uv run server.py
 59 | 
 60 | # Run with MCP Inspector (recommended)
 61 | uv run mcp dev server.py
 62 | 
 63 | # Run without uv
 64 | python server.py
 65 | ```
 66 | 
 67 | ## Testing with Claude Desktop
 68 | 
 69 | 1. Add to Claude Desktop config:
 70 |    ```json
 71 |    {
 72 |      "mcpServers": {
 73 |        "flutter-mcp": {
 74 |          "command": "uv",
 75 |          "args": ["--directory", "/path/to/flutter-docs-mcp", "run", "server.py"]
 76 |        }
 77 |      }
 78 |    }
 79 |    ```
 80 | 
 81 | 2. Restart Claude Desktop
 82 | 
 83 | 3. Test with queries like:
 84 |    - "How do I use the Container widget in Flutter?"
 85 |    - "Show me the documentation for material.Scaffold"
 86 |    - "What's the latest version of the provider package?"
 87 | 
 88 | ## Architecture
 89 | 
 90 | - **FastMCP**: Handles MCP protocol and tool registration
 91 | - **Redis**: Caches processed documentation (24h for APIs, 12h for packages)
 92 | - **Rate Limiter**: Ensures respectful scraping (2 requests/second)
 93 | - **HTML Parser**: Converts Flutter docs to clean Markdown
 94 | - **Structured Logging**: Track performance and debug issues
 95 | 
 96 | ## Common Issues
 97 | 
 98 | 1. **Redis not running**: Server works but responses are slower
 99 | 2. **Rate limiting**: First requests take 1-2 seconds
100 | 3. **404 errors**: Check class name and library spelling
101 | 
102 | ## Next Steps
103 | 
104 | - [ ] Add pub.dev README parsing
105 | - [ ] Implement @flutter_mcp activation
106 | - [ ] Add Flutter cookbook integration
107 | - [ ] Support version-specific docs
```

--------------------------------------------------------------------------------
/docs/planning/ingestion-strategy.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Flutter MCP Ingestion Strategy
 2 | 
 3 | ## Content Extraction Priorities
 4 | 
 5 | When we say we "support" a Flutter/Dart package, we extract and process the following content in priority order:
 6 | 
 7 | ### 1. Essential Content (MVP)
 8 | - **Doc Comments (`///`)**: Primary source of API documentation
 9 | - **Class/Method Signatures**: Full signatures with parameter types and return values
10 | - **Constructor Parameters**: Named parameters, required vs optional, default values
11 | - **README.md**: Package overview, getting started, basic examples
12 | - **pubspec.yaml**: Dependencies, Flutter/Dart SDK constraints
13 | 
14 | ### 2. High-Value Content (Week 1)
15 | - **Example Directory**: Complete runnable examples showing real usage
16 | - **CHANGELOG.md**: Recent version changes, breaking changes, migration guides
17 | - **Type Definitions**: Enums, typedefs, extension methods
18 | - **Export Statements**: Understanding the public API surface
19 | 
20 | ### 3. Context-Enhancing Content (Week 2+)
21 | - **Test Files**: Understanding expected behavior and edge cases
22 | - **Issue Templates**: Common problems and their solutions
23 | - **Migration Guides**: Version-specific upgrade instructions
24 | - **Platform-Specific Code**: iOS/Android/Web specific implementations
25 | 
26 | ### What We DON'T Extract
27 | - **Full Method Bodies**: Too much noise, not helpful for LLM context
28 | - **Private Implementation Details**: Focus on public API only
29 | - **Generated Code**: Skip `.g.dart`, `.freezed.dart` files
30 | - **Build Configuration**: Detailed build settings aren't useful for API questions
31 | 
32 | ## Semantic Chunking Strategy
33 | 
34 | Instead of naive text splitting, we chunk semantically:
35 | 
36 | ```
37 | CHUNK 1: package:provider, version:6.1.1, type:class
38 | # ChangeNotifierProvider<T>
39 | A widget that creates a ChangeNotifier and automatically disposes it.
40 | Constructor: ChangeNotifierProvider({required Create<T> create, bool? lazy, Widget? child})
41 | ...
42 | 
43 | CHUNK 2: package:provider, version:6.1.1, type:method, class:ChangeNotifierProvider
44 | # static T of<T>(BuildContext context, {bool listen = true})
45 | Obtains the nearest Provider<T> up its widget tree and returns its value.
46 | ...
47 | ```
48 | 
49 | ## Metadata Enrichment
50 | 
51 | Each chunk includes:
52 | - Package name and version
53 | - Source file path
54 | - Content type (class/method/example/changelog)
55 | - Null safety status
56 | - Platform compatibility
57 | - Last updated timestamp
58 | 
59 | This approach ensures high-quality, relevant context for LLMs while keeping storage and processing costs manageable.
```

--------------------------------------------------------------------------------
/docs/planning/project-summary.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Flutter MCP Project Summary
 2 | 
 3 | ## Vision
 4 | Create the Context7 of Flutter - an MCP server that gives AI assistants real-time access to Flutter/Dart documentation, positioning it as the essential tool for Flutter developers using Claude, Cursor, or Windsurf.
 5 | 
 6 | ## Key Innovation: On-Demand Package Support
 7 | Instead of pre-indexing 35,000+ packages, we use an on-demand model:
 8 | - User requests `@flutter_mcp provider`
 9 | - System fetches, processes, and caches package docs in ~30 seconds
10 | - Future requests are served instantly from cache
11 | 
12 | ## Technical Architecture
13 | - **Core**: Python FastMCP with Redis caching
14 | - **Fetching**: On-demand from api.flutter.dev, pub.dev API
15 | - **Processing**: HTML → Clean Markdown with semantic chunking
16 | - **Activation**: `@flutter_mcp package_name` in prompts
17 | 
18 | ## Marketing Strategy
19 | 
20 | ### Positioning
21 | "The first AI companion that supports ANY pub.dev package on-demand"
22 | 
23 | ### Key Messages
24 | 1. **End the State Management Wars** - Impartial expert on all approaches
25 | 2. **Beyond the README** - Full source analysis, not just documentation
26 | 3. **Always Current** - Real-time fetching, never outdated
27 | 
28 | ### Launch Plan
29 | - **Platform**: r/FlutterDev "Show-off Saturday"
30 | - **Demo**: LLM failing → add @flutter_mcp → perfect answer
31 | - **Engagement**: Live package request fulfillment during launch
32 | - **Influencers**: Reach out to top Flutter YouTubers
33 | 
34 | ### Viral Tactics
35 | - Developer testimonials with specific problems solved
36 | - "Powered by @flutter_mcp" badges
37 | - Community-generated before/after demos
38 | - Flutter package maintainer partnerships
39 | 
40 | ## Success Metrics
41 | - 1,000+ GitHub stars in first month
42 | - 100+ packages indexed in first week
43 | - 50%+ cache hit rate after first month
44 | - 10+ developer testimonials
45 | - Coverage in Flutter Weekly
46 | 
47 | ## Timeline
48 | - **MVP (4 hours)**: Basic server with Flutter API docs
49 | - **Week 1**: Add pub.dev support, search, polish
50 | - **Week 2**: Launch preparation and marketing push
51 | - **Launch Week**: Coordinated multi-platform release
52 | 
53 | ## Files Created
54 | 1. `project-tasks.csv` - 60 detailed tasks with priorities
55 | 2. `ingestion-strategy.md` - What content to extract from packages
56 | 3. `context7-marketing-analysis.md` - Marketing tactics analysis
57 | 
58 | The project is designed to solve a real problem (outdated AI knowledge of Flutter) with a simple solution (@flutter_mcp activation) that can be built quickly and marketed effectively to the Flutter community.
```

--------------------------------------------------------------------------------
/RELEASE_GUIDE.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Release Guide for Flutter MCP Server
  2 | 
  3 | ## ✅ Package Status
  4 | 
  5 | The package has been successfully built and is ready for publication:
  6 | - **PyPI Package**: `flutter_mcp_server-0.1.0` 
  7 | - **npm Package**: `@flutter-mcp/[email protected]`
  8 | 
  9 | ## 🚀 Publishing to PyPI
 10 | 
 11 | ### 1. Create PyPI Account
 12 | - Main PyPI: https://pypi.org/account/register/
 13 | - Test PyPI: https://test.pypi.org/account/register/
 14 | 
 15 | ### 2. Get API Token
 16 | - Go to https://pypi.org/manage/account/token/
 17 | - Create a new API token with scope "Entire account"
 18 | - Save the token securely (starts with `pypi-`)
 19 | 
 20 | ### 3. Publish to TestPyPI (Recommended First)
 21 | ```bash
 22 | # Set your TestPyPI token
 23 | export TWINE_USERNAME=__token__
 24 | export TWINE_PASSWORD=<your-test-pypi-token>
 25 | 
 26 | # Upload to TestPyPI
 27 | twine upload --repository testpypi dist/*
 28 | 
 29 | # Test installation
 30 | pip install -i https://test.pypi.org/simple/ flutter-mcp-server
 31 | ```
 32 | 
 33 | ### 4. Publish to PyPI
 34 | ```bash
 35 | # Set your PyPI token
 36 | export TWINE_USERNAME=__token__
 37 | export TWINE_PASSWORD=<your-pypi-token>
 38 | 
 39 | # Upload to PyPI
 40 | twine upload dist/*
 41 | ```
 42 | 
 43 | ### 5. Verify Installation
 44 | ```bash
 45 | pip install flutter-mcp-server
 46 | flutter-mcp --version
 47 | ```
 48 | 
 49 | ## 📦 Publishing npm Package
 50 | 
 51 | ### 1. Login to npm
 52 | ```bash
 53 | npm login
 54 | ```
 55 | 
 56 | ### 2. Publish the Package
 57 | ```bash
 58 | cd npm-wrapper
 59 | ./publish.sh
 60 | ```
 61 | 
 62 | ### 3. Verify Installation
 63 | ```bash
 64 | npx @flutter-mcp/server --version
 65 | ```
 66 | 
 67 | ## 🎉 What's New in This Release
 68 | 
 69 | ### Transport Support (v0.1.0)
 70 | - **STDIO Transport** (default) - For Claude Desktop and most MCP clients
 71 | - **HTTP Transport** - For MCP SuperAssistant and HTTP-based clients  
 72 | - **SSE Transport** - For Server-Sent Events based clients
 73 | 
 74 | ### Usage Examples
 75 | 
 76 | #### HTTP Transport (for MCP SuperAssistant)
 77 | ```bash
 78 | flutter-mcp start --transport http --port 8000
 79 | ```
 80 | 
 81 | #### SSE Transport
 82 | ```bash
 83 | flutter-mcp start --transport sse --port 8080
 84 | ```
 85 | 
 86 | #### Custom Host Binding
 87 | ```bash
 88 | flutter-mcp start --transport http --host 0.0.0.0 --port 3000
 89 | ```
 90 | 
 91 | ## 📝 Post-Release Checklist
 92 | 
 93 | - [ ] Upload to TestPyPI and test
 94 | - [ ] Upload to PyPI
 95 | - [ ] Publish npm package
 96 | - [ ] Create GitHub release with tag `v0.1.0`
 97 | - [ ] Update the main README if needed
 98 | - [ ] Announce in relevant communities
 99 | 
100 | ## 🔧 Troubleshooting
101 | 
102 | ### "Package already exists"
103 | The package name might be taken. Check:
104 | - PyPI: https://pypi.org/project/flutter-mcp-server/
105 | - npm: https://www.npmjs.com/package/@flutter-mcp/server
106 | 
107 | ### Build Issues
108 | ```bash
109 | # Clean and rebuild
110 | rm -rf dist/ build/ *.egg-info src/*.egg-info
111 | python -m build
112 | ```
113 | 
114 | ### npm Login Issues
115 | ```bash
116 | npm whoami  # Check if logged in
117 | npm login   # Login again if needed
118 | ```
```

--------------------------------------------------------------------------------
/docs/PUBLISHING.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Publishing Flutter MCP Server
  2 | 
  3 | This document explains how to publish Flutter MCP Server to PyPI and npm.
  4 | 
  5 | ## PyPI Publication
  6 | 
  7 | ### Prerequisites
  8 | 
  9 | 1. PyPI account: https://pypi.org/account/register/
 10 | 2. PyPI API token: https://pypi.org/manage/account/token/
 11 | 3. TestPyPI account (optional but recommended): https://test.pypi.org/account/register/
 12 | 
 13 | ### Setup
 14 | 
 15 | 1. Configure PyPI credentials:
 16 |    ```bash
 17 |    cp .pypirc.template ~/.pypirc
 18 |    # Edit ~/.pypirc with your API tokens
 19 |    ```
 20 | 
 21 |    Or use environment variables:
 22 |    ```bash
 23 |    export TWINE_USERNAME=__token__
 24 |    export TWINE_PASSWORD=pypi-your-token-here
 25 |    ```
 26 | 
 27 | 2. Install build tools:
 28 |    ```bash
 29 |    pip install --upgrade pip setuptools wheel twine build
 30 |    ```
 31 | 
 32 | ### Publishing Process
 33 | 
 34 | 1. Update version in:
 35 |    - `pyproject.toml`
 36 |    - `setup.py`
 37 |    - `src/flutter_mcp/cli.py` (__version__)
 38 | 
 39 | 2. Run the publish script:
 40 |    ```bash
 41 |    ./scripts/publish-pypi.sh
 42 |    ```
 43 | 
 44 | 3. Test on TestPyPI first (recommended):
 45 |    ```bash
 46 |    twine upload --repository testpypi dist/*
 47 |    
 48 |    # Test installation
 49 |    pip install -i https://test.pypi.org/simple/ flutter-mcp-server
 50 |    ```
 51 | 
 52 | 4. Publish to PyPI:
 53 |    ```bash
 54 |    twine upload dist/*
 55 |    ```
 56 | 
 57 | 5. Verify installation:
 58 |    ```bash
 59 |    pip install flutter-mcp-server
 60 |    flutter-mcp --version
 61 |    ```
 62 | 
 63 | ## NPM Publication
 64 | 
 65 | ### Prerequisites
 66 | 
 67 | 1. npm account: https://www.npmjs.com/signup
 68 | 2. Login to npm: `npm login`
 69 | 
 70 | ### Publishing Process
 71 | 
 72 | 1. Update version in `npm-wrapper/package.json`
 73 | 
 74 | 2. Navigate to npm wrapper directory:
 75 |    ```bash
 76 |    cd npm-wrapper
 77 |    ```
 78 | 
 79 | 3. Run the publish script:
 80 |    ```bash
 81 |    ./publish.sh
 82 |    ```
 83 | 
 84 | 4. Verify installation:
 85 |    ```bash
 86 |    npx @flutter-mcp/server --version
 87 |    ```
 88 | 
 89 | ## Version Synchronization
 90 | 
 91 | Keep versions synchronized across:
 92 | - `pyproject.toml`
 93 | - `setup.py`
 94 | - `src/flutter_mcp/cli.py`
 95 | - `npm-wrapper/package.json`
 96 | 
 97 | ## Release Checklist
 98 | 
 99 | - [ ] Update version numbers
100 | - [ ] Update CHANGELOG
101 | - [ ] Run tests: `pytest`
102 | - [ ] Test locally: `flutter-mcp start`
103 | - [ ] Build and check package: `./scripts/publish-pypi.sh`
104 | - [ ] Publish to TestPyPI
105 | - [ ] Test installation from TestPyPI
106 | - [ ] Publish to PyPI
107 | - [ ] Publish npm wrapper
108 | - [ ] Create GitHub release
109 | - [ ] Update documentation
110 | 
111 | ## Troubleshooting
112 | 
113 | ### "Invalid distribution file"
114 | - Ensure README.md exists in docs/
115 | - Check MANIFEST.in includes all necessary files
116 | 
117 | ### "Version already exists"
118 | - Increment version number
119 | - Delete old builds: `rm -rf dist/ build/`
120 | 
121 | ### npm publish fails
122 | - Ensure you're logged in: `npm whoami`
123 | - Check package name availability
124 | - Verify package.json is valid: `npm pack --dry-run`
```

--------------------------------------------------------------------------------
/context7-installation-analysis.md:
--------------------------------------------------------------------------------

```markdown
 1 | # Flutter MCP vs Context7: Installation Simplicity Achieved! 🎉
 2 | 
 3 | ## Installation Comparison
 4 | 
 5 | ### Context7
 6 | ```bash
 7 | npx -y @upstash/context7-mcp
 8 | ```
 9 | 
10 | ### Flutter MCP (After Improvements)
11 | ```bash
12 | pip install flutter-mcp-server
13 | flutter-mcp start
14 | ```
15 | 
16 | Or even simpler with executables:
17 | ```bash
18 | # Download and run - no Python needed!
19 | curl -L https://github.com/flutter-mcp/releases/latest/flutter-mcp-macos -o flutter-mcp
20 | chmod +x flutter-mcp
21 | ./flutter-mcp
22 | ```
23 | 
24 | ## What We Changed
25 | 
26 | ### Phase 1: Removed External Dependencies ✅
27 | - **Before**: Required Python + Redis server
28 | - **After**: Just Python (SQLite built-in)
29 | - **Impact**: 50% reduction in setup complexity
30 | 
31 | ### Phase 2: Single Executable Distribution ✅
32 | - **Before**: pip install + dependencies
33 | - **After**: Download one file and run
34 | - **Impact**: Zero dependencies for end users
35 | 
36 | ## Key Improvements Made
37 | 
38 | 1. **Replaced Redis with SQLite**
39 |    - No external services to install/manage
40 |    - Automatic cache directory creation
41 |    - Platform-aware storage locations
42 |    - Same performance for single-user tool
43 | 
44 | 2. **Added PyInstaller Packaging**
45 |    - Creates standalone executables
46 |    - Bundles Python runtime
47 |    - Works on Windows, macOS, Linux
48 |    - ~30MB download vs multi-step install
49 | 
50 | 3. **Simplified Configuration**
51 |    - Removed all Redis configuration options
52 |    - Works with zero config out of the box
53 |    - Optional cache directory override only
54 | 
55 | 4. **Multiple Distribution Options**
56 |    - PyPI: `pip install flutter-mcp-server`
57 |    - Docker: `docker run ghcr.io/flutter-mcp/flutter-mcp`
58 |    - Executable: Download and run
59 |    - Source: Clone and develop
60 | 
61 | ## Performance Impact
62 | 
63 | - **First query**: Same (1-2 seconds to fetch)
64 | - **Cached queries**: <50ms (SQLite nearly as fast as Redis)
65 | - **Startup time**: PyInstaller adds ~1 second (acceptable)
66 | - **Memory usage**: Slightly lower without Redis
67 | 
68 | ## User Experience Wins
69 | 
70 | 1. **Zero Configuration Required**
71 |    - No Redis URLs
72 |    - No service management
73 |    - No port conflicts
74 | 
75 | 2. **Works Everywhere**
76 |    - macOS, Windows, Linux
77 |    - No admin rights needed
78 |    - Portable executables
79 | 
80 | 3. **Graceful Degradation**
81 |    - Cache automatically created
82 |    - Works offline with cache
83 |    - Clear error messages
84 | 
85 | ## Conclusion
86 | 
87 | Flutter MCP now matches Context7's installation simplicity while maintaining all functionality. Users can choose their preferred installation method:
88 | 
89 | - **Developers**: `pip install` for easy updates
90 | - **Non-technical users**: Download executable
91 | - **Teams**: Docker for consistency
92 | - **Contributors**: Clone and develop
93 | 
94 | The key insight from Context7: **Hide complexity, not functionality**. By replacing Redis with SQLite and adding executable distribution, we achieved the same "it just works" experience! 🚀
```

--------------------------------------------------------------------------------
/.github/workflows/build-executables.yml:
--------------------------------------------------------------------------------

```yaml
  1 | name: Build Executables
  2 | 
  3 | on:
  4 |   push:
  5 |     tags:
  6 |       - 'v*'
  7 |   workflow_dispatch:
  8 | 
  9 | jobs:
 10 |   build:
 11 |     strategy:
 12 |       matrix:
 13 |         include:
 14 |           - os: ubuntu-latest
 15 |             platform: linux
 16 |             arch: x64
 17 |           - os: macos-latest
 18 |             platform: macos
 19 |             arch: x64
 20 |           - os: macos-14  # M1 runner
 21 |             platform: macos
 22 |             arch: arm64
 23 |           - os: windows-latest
 24 |             platform: windows
 25 |             arch: x64
 26 | 
 27 |     runs-on: ${{ matrix.os }}
 28 |     
 29 |     steps:
 30 |     - uses: actions/checkout@v4
 31 |     
 32 |     - name: Set up Python
 33 |       uses: actions/setup-python@v5
 34 |       with:
 35 |         python-version: '3.11'
 36 |     
 37 |     - name: Install dependencies
 38 |       run: |
 39 |         python -m pip install --upgrade pip
 40 |         pip install pyinstaller
 41 |         pip install -e .
 42 |     
 43 |     - name: Build executable
 44 |       run: |
 45 |         pyinstaller build.spec
 46 |     
 47 |     - name: Rename executable
 48 |       shell: bash
 49 |       run: |
 50 |         mkdir -p releases
 51 |         if [ "${{ matrix.platform }}" = "windows" ]; then
 52 |           mv dist/flutter-mcp.exe releases/flutter-mcp-${{ matrix.platform }}-${{ matrix.arch }}.exe
 53 |         else
 54 |           mv dist/flutter-mcp releases/flutter-mcp-${{ matrix.platform }}-${{ matrix.arch }}
 55 |         fi
 56 |     
 57 |     - name: Test executable
 58 |       shell: bash
 59 |       run: |
 60 |         if [ "${{ matrix.platform }}" = "windows" ]; then
 61 |           ./releases/flutter-mcp-${{ matrix.platform }}-${{ matrix.arch }}.exe --version
 62 |         else
 63 |           ./releases/flutter-mcp-${{ matrix.platform }}-${{ matrix.arch }} --version
 64 |         fi
 65 |     
 66 |     - name: Upload artifact
 67 |       uses: actions/upload-artifact@v4
 68 |       with:
 69 |         name: flutter-mcp-${{ matrix.platform }}-${{ matrix.arch }}
 70 |         path: releases/*
 71 | 
 72 |   release:
 73 |     needs: build
 74 |     runs-on: ubuntu-latest
 75 |     if: startsWith(github.ref, 'refs/tags/v')
 76 |     
 77 |     steps:
 78 |     - uses: actions/checkout@v4
 79 |     
 80 |     - name: Download all artifacts
 81 |       uses: actions/download-artifact@v4
 82 |       with:
 83 |         path: releases
 84 |         pattern: flutter-mcp-*
 85 |         merge-multiple: true
 86 |     
 87 |     - name: Create Release
 88 |       uses: softprops/action-gh-release@v1
 89 |       with:
 90 |         files: releases/*
 91 |         body: |
 92 |           # Flutter MCP Server ${{ github.ref_name }}
 93 |           
 94 |           ## Installation
 95 |           
 96 |           ### Option 1: Download Executable (Easiest!)
 97 |           Download the appropriate executable for your platform below. No Python required!
 98 |           
 99 |           ### Option 2: Install from PyPI
100 |           ```bash
101 |           pip install flutter-mcp-server
102 |           ```
103 |           
104 |           ### Option 3: Docker
105 |           ```bash
106 |           docker run -p 8000:8000 ghcr.io/flutter-mcp/flutter-mcp:${{ github.ref_name }}
107 |           ```
108 |           
109 |           ## What's New
110 |           See [CHANGELOG.md](https://github.com/flutter-mcp/flutter-mcp/blob/main/CHANGELOG.md) for details.
111 |         draft: false
112 |         prerelease: false
```

--------------------------------------------------------------------------------
/docs/planning/context7-marketing-analysis.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Context7 Marketing & Community Engagement Analysis
  2 | 
  3 | ## Key Success Factors
  4 | 
  5 | ### 1. Strong Value Proposition
  6 | - **Clear Problem Statement**: "LLMs are trained on old data" - immediately resonates with developers
  7 | - **Simple Solution**: "Get up-to-date, version-specific documentation"
  8 | - **Instant Benefit**: "Stop getting broken, outdated code"
  9 | 
 10 | ### 2. GitHub-First Strategy
 11 | - **13.7k stars** in a short time
 12 | - Open source with MIT license
 13 | - Active issue tracking (45 open issues)
 14 | - Community contributions encouraged through PRs
 15 | 
 16 | ### 3. Free Pricing Model
 17 | - "Free for personal use" - removes barriers to adoption
 18 | - Built on Upstash infrastructure
 19 | - No hidden costs or limitations mentioned
 20 | 
 21 | ### 4. Developer-Centric Messaging
 22 | - Technical but accessible language
 23 | - Real examples (Next.js `after()` function, React Query)
 24 | - Focus on time-saving and frustration reduction
 25 | 
 26 | ### 5. Multiple Integration Paths
 27 | - One-click Cursor installation
 28 | - Support for 14+ languages
 29 | - Multiple package managers (npm, deno, etc.)
 30 | - Works with any LLM-powered editor
 31 | 
 32 | ### 6. Community Building Tactics
 33 | - **Easy Contribution**: "Add your project" with simple form or PR
 34 | - **Direct Feedback Channels**: Email and GitHub
 35 | - **Documentation Integration**: Libraries can add Context7 links
 36 | - **Phased Launch**: Started simple, added features based on feedback
 37 | 
 38 | ### 7. Content Marketing
 39 | - Technical blog posts on Upstash blog
 40 | - Clear before/after examples
 41 | - Step-by-step installation guides
 42 | - Focus on specific use cases
 43 | 
 44 | ### 8. Positioning Strategy
 45 | - Backed by established company (Upstash)
 46 | - "Community-maintained" messaging
 47 | - Focus on solving universal developer pain point
 48 | - No direct competitor comparisons
 49 | 
 50 | ## Tactics to Adapt for Flutter Documentation MCP
 51 | 
 52 | ### 1. Clear Problem Framing
 53 | - "Flutter's rapid evolution means AI assistants give outdated widget examples"
 54 | - "Stop debugging AI-generated Flutter code that uses deprecated APIs"
 55 | 
 56 | ### 2. Flutter-Specific Examples
 57 | - Show common Flutter pain points (e.g., null safety migration, new widgets)
 58 | - Use real Flutter code examples in marketing materials
 59 | - Highlight version-specific challenges (Flutter 2.x vs 3.x)
 60 | 
 61 | ### 3. Community Integration
 62 | - Launch on r/FlutterDev, Flutter Discord
 63 | - Partner with Flutter YouTube channels
 64 | - Get featured in Flutter Weekly newsletter
 65 | 
 66 | ### 4. Free Tier Strategy
 67 | - Start completely free for individual developers
 68 | - Build trust and adoption first
 69 | - Consider team/enterprise tiers later
 70 | 
 71 | ### 5. Easy Onboarding
 72 | - One-click installation for popular Flutter IDEs
 73 | - Video tutorials showing immediate value
 74 | - "Add to your Flutter project in 30 seconds"
 75 | 
 76 | ### 6. Developer Advocacy
 77 | - Encourage Flutter package authors to add support
 78 | - Create badges for "Context7-enabled" packages
 79 | - Build relationships with popular package maintainers
 80 | 
 81 | ### 7. Content Strategy
 82 | - Weekly blog posts solving real Flutter problems
 83 | - Before/after code comparisons
 84 | - Guest posts from Flutter influencers
 85 | 
 86 | ### 8. Growth Metrics to Track
 87 | - GitHub stars and forks
 88 | - Daily active users
 89 | - Number of Flutter packages indexed
 90 | - Community contributions
 91 | - Support queries (indicator of engagement)
 92 | 
 93 | ## Launch Checklist
 94 | 
 95 | 1. **Pre-Launch**
 96 |    - Build MVP with core Flutter packages
 97 |    - Create compelling demos
 98 |    - Prepare documentation
 99 |    - Set up GitHub repository
100 | 
101 | 2. **Soft Launch**
102 |    - Share with Flutter friends/colleagues
103 |    - Get initial feedback
104 |    - Fix critical issues
105 | 
106 | 3. **Public Launch**
107 |    - Post on r/FlutterDev with problem/solution focus
108 |    - Share in Flutter Discord channels
109 |    - Submit to Flutter Weekly
110 |    - Launch on Product Hunt (Flutter/Dev Tools category)
111 | 
112 | 4. **Post-Launch**
113 |    - Respond to all feedback quickly
114 |    - Regular updates showing progress
115 |    - Build in public on Twitter/X
116 |    - Create video content for YouTube
117 | 
118 | ## Key Takeaway
119 | Context7's success comes from solving a real, universal developer problem with a free, easy-to-use solution backed by strong technical execution and community engagement. The same approach can work for Flutter developers who face similar challenges with AI-generated code.
```

--------------------------------------------------------------------------------
/docs/CLIENT-CONFIGURATIONS.md:
--------------------------------------------------------------------------------

```markdown
  1 | # MCP Client Configurations
  2 | 
  3 | This document provides configuration examples for various MCP clients to connect to Flutter MCP Server.
  4 | 
  5 | ## Transport Modes Overview
  6 | 
  7 | Flutter MCP Server supports three transport modes:
  8 | - **STDIO** (default): Standard input/output communication
  9 | - **HTTP**: REST-like HTTP transport
 10 | - **SSE**: Server-Sent Events for streaming
 11 | 
 12 | ## Claude Desktop
 13 | 
 14 | **Transport**: STDIO
 15 | 
 16 | Edit `~/Library/Application Support/Claude/claude_desktop_config.json`:
 17 | 
 18 | ```json
 19 | {
 20 |   "mcpServers": {
 21 |     "flutter-mcp": {
 22 |       "command": "flutter-mcp",
 23 |       "args": ["start"],
 24 |       "env": {}
 25 |     }
 26 |   }
 27 | }
 28 | ```
 29 | 
 30 | Or using npx:
 31 | ```json
 32 | {
 33 |   "mcpServers": {
 34 |     "flutter-mcp": {
 35 |       "command": "npx",
 36 |       "args": ["@flutter-mcp/server", "start"],
 37 |       "env": {}
 38 |     }
 39 |   }
 40 | }
 41 | ```
 42 | 
 43 | ## MCP SuperAssistant
 44 | 
 45 | **Transport**: HTTP
 46 | 
 47 | 1. Start the server:
 48 |    ```bash
 49 |    flutter-mcp start --transport http --port 8000
 50 |    ```
 51 | 
 52 | 2. In MCP SuperAssistant:
 53 |    - Click "Add Server"
 54 |    - Name: `Flutter MCP`
 55 |    - URL: `http://localhost:8000`
 56 |    - Type: `HTTP MCP Server`
 57 | 
 58 | ## Claude Code (claude.ai/code)
 59 | 
 60 | **Transport**: STDIO
 61 | 
 62 | ### Global Configuration
 63 | 
 64 | Install globally and Claude Code will auto-detect:
 65 | ```bash
 66 | pip install flutter-mcp-server
 67 | ```
 68 | 
 69 | ### Per-Project Configuration
 70 | 
 71 | Create `.mcp.json` in your project root:
 72 | ```json
 73 | {
 74 |   "mcpServers": {
 75 |     "flutter-mcp": {
 76 |       "command": "/path/to/flutter-mcp/venv/bin/flutter-mcp",
 77 |       "args": ["start"]
 78 |     }
 79 |   }
 80 | }
 81 | ```
 82 | 
 83 | ## VS Code + Continue
 84 | 
 85 | **Transport**: STDIO
 86 | 
 87 | In `.continuerc.json`:
 88 | ```json
 89 | {
 90 |   "models": [
 91 |     {
 92 |       "provider": "claude",
 93 |       "mcp_servers": {
 94 |         "flutter-mcp": {
 95 |           "command": "flutter-mcp",
 96 |           "args": ["start"]
 97 |         }
 98 |       }
 99 |     }
100 |   ]
101 | }
102 | ```
103 | 
104 | ## Custom HTTP Client
105 | 
106 | **Transport**: HTTP
107 | 
108 | ```python
109 | import httpx
110 | 
111 | # Start server: flutter-mcp start --transport http --port 8000
112 | 
113 | client = httpx.Client(base_url="http://localhost:8000")
114 | 
115 | # Make MCP requests
116 | response = client.post("/mcp/v1/tools/list")
117 | tools = response.json()
118 | 
119 | # Call a tool
120 | response = client.post("/mcp/v1/tools/call", json={
121 |     "name": "get_flutter_docs",
122 |     "arguments": {
123 |         "query": "StatefulWidget"
124 |     }
125 | })
126 | ```
127 | 
128 | ## Custom SSE Client
129 | 
130 | **Transport**: SSE
131 | 
132 | ```javascript
133 | // Start server: flutter-mcp start --transport sse --port 8080
134 | 
135 | const eventSource = new EventSource('http://localhost:8080/sse');
136 | 
137 | eventSource.onmessage = (event) => {
138 |   const data = JSON.parse(event.data);
139 |   console.log('Received:', data);
140 | };
141 | 
142 | // Send requests via POST to the same server
143 | fetch('http://localhost:8080/mcp/v1/tools/list', {
144 |   method: 'POST',
145 |   headers: { 'Content-Type': 'application/json' }
146 | })
147 | .then(res => res.json())
148 | .then(console.log);
149 | ```
150 | 
151 | ## Docker Configurations
152 | 
153 | ### Claude Desktop with Docker
154 | 
155 | ```json
156 | {
157 |   "mcpServers": {
158 |     "flutter-mcp": {
159 |       "command": "docker",
160 |       "args": [
161 |         "run", "-i", "--rm",
162 |         "ghcr.io/flutter-mcp/flutter-mcp:latest"
163 |       ]
164 |     }
165 |   }
166 | }
167 | ```
168 | 
169 | ### HTTP Server with Docker
170 | 
171 | ```bash
172 | # Run with HTTP transport exposed
173 | docker run -p 8000:8000 ghcr.io/flutter-mcp/flutter-mcp:latest \
174 |   flutter-mcp start --transport http --host 0.0.0.0 --port 8000
175 | ```
176 | 
177 | ## Environment Variables
178 | 
179 | All transport modes support these environment variables:
180 | 
181 | ```bash
182 | # Cache directory
183 | export CACHE_DIR=/path/to/cache
184 | 
185 | # Debug logging
186 | export DEBUG=1
187 | 
188 | # Transport settings (when not using CLI args)
189 | export MCP_TRANSPORT=http
190 | export MCP_PORT=8000
191 | export MCP_HOST=0.0.0.0
192 | ```
193 | 
194 | ## Troubleshooting Connection Issues
195 | 
196 | ### STDIO Transport
197 | - Ensure the command path is correct
198 | - Check Python is installed: `python3 --version`
199 | - Verify installation: `flutter-mcp --version`
200 | 
201 | ### HTTP/SSE Transport
202 | - Check port availability: `lsof -i :8000`
203 | - Try different port: `--port 8080`
204 | - Bind to all interfaces: `--host 0.0.0.0`
205 | - Check firewall settings
206 | 
207 | ### Common Issues
208 | 
209 | 1. **"Connection refused"**
210 |    - Server not running
211 |    - Wrong port
212 |    - Firewall blocking connection
213 | 
214 | 2. **"Command not found"**
215 |    - Package not installed
216 |    - Wrong path in configuration
217 |    - Virtual environment not activated
218 | 
219 | 3. **"Transport mismatch"**
220 |    - Client expects different transport
221 |    - Check client documentation
222 |    - Use correct transport flag
223 | 
224 | ## Testing Connection
225 | 
226 | ### Test STDIO
227 | ```bash
228 | echo '{"method": "mcp/v1/tools/list"}' | flutter-mcp start
229 | ```
230 | 
231 | ### Test HTTP
232 | ```bash
233 | # Start server
234 | flutter-mcp start --transport http --port 8000
235 | 
236 | # Test with curl
237 | curl -X POST http://localhost:8000/mcp/v1/tools/list
238 | ```
239 | 
240 | ### Test SSE
241 | ```bash
242 | # Start server
243 | flutter-mcp start --transport sse --port 8080
244 | 
245 | # Test with curl
246 | curl http://localhost:8080/sse
247 | ```
```

--------------------------------------------------------------------------------
/docs/planning/IMPLEMENTATION_SUMMARY.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Flutter MCP Server - Implementation Summary
  2 | 
  3 | ## 🎯 Project Overview
  4 | 
  5 | We've successfully built a complete Flutter MCP (Model Context Protocol) server that provides real-time Flutter/Dart documentation to AI assistants. The server supports ALL 50,000+ packages on pub.dev through on-demand fetching.
  6 | 
  7 | ## ✅ Completed Features
  8 | 
  9 | ### Core Functionality
 10 | - ✅ **FastMCP Server**: Built with Python using the FastMCP framework
 11 | - ✅ **5 MCP Tools**: 
 12 |   - `get_flutter_docs` - Fetches Flutter/Dart API documentation
 13 |   - `get_pub_package_info` - Gets package info with full README from pub.dev
 14 |   - `search_flutter_docs` - Intelligent search across documentation
 15 |   - `process_flutter_mentions` - Parses @flutter_mcp mentions in text
 16 |   - `health_check` - Monitors scraper and service health
 17 | - ✅ **Redis Caching**: 24h for APIs, 12h for packages with graceful fallback
 18 | - ✅ **Rate Limiting**: 2 requests/second to respect server resources
 19 | - ✅ **HTML to Markdown Converter**: Clean documentation for AI consumption
 20 | - ✅ **Smart URL Resolution**: Pattern matching for Flutter/Dart libraries
 21 | 
 22 | ### Developer Experience
 23 | - ✅ **CLI Interface**: `flutter-mcp start/dev/help/version` commands
 24 | - ✅ **Multiple Installation Options**:
 25 |   - PyPI: `pip install flutter-mcp-server`
 26 |   - Docker: `docker run ghcr.io/flutter-mcp/flutter-mcp`
 27 |   - Docker Compose with Redis included
 28 | - ✅ **Works Without Redis**: Graceful degradation with warnings
 29 | - ✅ **Structured Logging**: Using structlog for debugging
 30 | 
 31 | ### Testing & Quality
 32 | - ✅ **Integration Tests**: 80% pass rate (4/5 tests)
 33 | - ✅ **Tested with Popular Packages**: provider, bloc, dio, get, riverpod
 34 | - ✅ **Health Check System**: Real-time monitoring of scraper status
 35 | - ✅ **Error Handling**: Graceful failures with helpful messages
 36 | 
 37 | ### Documentation & Distribution
 38 | - ✅ **Comprehensive README**: Quick start, features, tool reference
 39 | - ✅ **CONTRIBUTING.md**: Community guidelines and development setup
 40 | - ✅ **DEVELOPMENT.md**: Local development guide
 41 | - ✅ **MIT License**: Open source friendly
 42 | - ✅ **PyPI Ready**: pyproject.toml with git dependency for MCP
 43 | - ✅ **Docker Support**: Dockerfile and docker-compose.yml
 44 | 
 45 | ## 📊 Technical Architecture
 46 | 
 47 | ```
 48 | Client (AI) → MCP Protocol → FastMCP Server
 49 |                                   ↓
 50 |                             Rate Limiter (2/sec)
 51 |                                   ↓
 52 |                             Cache Check (Redis)
 53 |                                   ↓ (miss)
 54 |                             Web Scraper
 55 |                                   ↓
 56 |                             HTML Parser → Markdown
 57 |                                   ↓
 58 |                             Cache Store → Response
 59 | ```
 60 | 
 61 | ## 🚀 Launch Readiness
 62 | 
 63 | ### What's Ready
 64 | - ✅ Server is fully functional
 65 | - ✅ All critical tools implemented
 66 | - ✅ PyPI package structure complete
 67 | - ✅ Docker images configured
 68 | - ✅ Installation instructions clear
 69 | - ✅ Health monitoring in place
 70 | 
 71 | ### What's Needed for Launch
 72 | 1. **PyPI Publication**: Run `python -m build` and `twine upload`
 73 | 2. **Docker Hub Push**: Build and push Docker image
 74 | 3. **Demo GIF/Video**: Show the 20-second experience
 75 | 4. **GitHub Repository**: Push to public repo
 76 | 5. **Reddit Post**: Launch on r/FlutterDev
 77 | 
 78 | ## 📈 Key Metrics to Track
 79 | 
 80 | - GitHub stars (target: 100+ in first month)
 81 | - PyPI downloads
 82 | - Docker pulls
 83 | - Active packages being queried
 84 | - Cache hit rate
 85 | - Community contributions
 86 | 
 87 | ## 🎨 Marketing Message
 88 | 
 89 | **Hero**: "Give Your AI Real-Time Flutter Superpowers"
 90 | **Value Prop**: "Supports ALL 50,000+ pub.dev packages on-demand"
 91 | **Differentiator**: "Never outdated, always current documentation"
 92 | 
 93 | ## 🔧 Technical Decisions Made
 94 | 
 95 | 1. **Python over TypeScript**: Easier for Claude to maintain
 96 | 2. **On-demand over Pre-indexing**: "Supports ALL packages" message
 97 | 3. **FastMCP over Raw MCP**: Simpler, cleaner code
 98 | 4. **Git dependency for MCP**: Until official PyPI release
 99 | 5. **Health check as tool**: Can be monitored programmatically
100 | 
101 | ## 🎁 Bonus Features Implemented
102 | 
103 | - CLI with multiple commands
104 | - Docker Compose for easy dev setup
105 | - Integration test suite
106 | - Structured logging throughout
107 | - @flutter_mcp mention processing
108 | 
109 | ## 📝 Lessons Learned
110 | 
111 | 1. **Scraper fragility is real**: Health checks are essential
112 | 2. **README location varies**: Had to try multiple selectors
113 | 3. **Rate limiting matters**: 2/sec keeps servers happy
114 | 4. **Cache is optional but valuable**: 10x+ speed improvement
115 | 5. **Clear messaging wins**: "ALL packages" is powerful
116 | 
117 | ## 🙏 Acknowledgments
118 | 
119 | Special thanks to Gemini Pro for strategic advice on launch readiness and the importance of the "First Five Minutes" experience.
120 | 
121 | ---
122 | 
123 | **Total Implementation Time**: ~6 hours
124 | **Lines of Code**: ~880 (server.py)
125 | **Test Coverage**: Core functionality tested
126 | **Ready for Launch**: ✅ YES!
```

--------------------------------------------------------------------------------
/src/flutter_mcp/cli.py:
--------------------------------------------------------------------------------

```python
  1 | #!/usr/bin/env python3
  2 | """CLI entry point for Flutter MCP Server"""
  3 | 
  4 | import sys
  5 | import argparse
  6 | import os
  7 | from typing import Optional
  8 | import asyncio
  9 | 
 10 | # Add version info
 11 | __version__ = "0.1.1"
 12 | 
 13 | 
 14 | def main():
 15 |     """Main CLI entry point"""
 16 |     parser = argparse.ArgumentParser(
 17 |         prog='flutter-mcp',
 18 |         description='Flutter MCP Server - Real-time Flutter/Dart documentation for AI assistants',
 19 |         epilog='For more information, visit: https://github.com/flutter-mcp/flutter-mcp'
 20 |     )
 21 |     
 22 |     parser.add_argument(
 23 |         'command',
 24 |         choices=['start', 'serve', 'dev', 'version', 'help'],
 25 |         nargs='?',
 26 |         default='start',
 27 |         help='Command to run (default: start)'
 28 |     )
 29 |     
 30 |     parser.add_argument(
 31 |         '--cache-dir',
 32 |         default=None,
 33 |         help='Custom cache directory (default: platform-specific)'
 34 |     )
 35 |     
 36 |     parser.add_argument(
 37 |         '--debug',
 38 |         action='store_true',
 39 |         help='Enable debug logging'
 40 |     )
 41 |     
 42 |     parser.add_argument(
 43 |         '--version',
 44 |         action='version',
 45 |         version=f'%(prog)s {__version__}'
 46 |     )
 47 |     
 48 |     parser.add_argument(
 49 |         '--transport',
 50 |         choices=['stdio', 'sse', 'http'],
 51 |         default='stdio',
 52 |         help='Transport protocol to use (default: stdio)'
 53 |     )
 54 |     
 55 |     parser.add_argument(
 56 |         '--port',
 57 |         type=int,
 58 |         default=8000,
 59 |         help='Port to listen on for HTTP/SSE transport (default: 8000)'
 60 |     )
 61 |     
 62 |     parser.add_argument(
 63 |         '--host',
 64 |         default='127.0.0.1',
 65 |         help='Host to bind to for HTTP/SSE transport (default: 127.0.0.1)'
 66 |     )
 67 |     
 68 |     args = parser.parse_args()
 69 |     
 70 |     # Handle commands
 71 |     if args.command == 'version':
 72 |         print(f"Flutter MCP Server v{__version__}", file=sys.stderr)
 73 |         sys.exit(0)
 74 |     
 75 |     elif args.command == 'help':
 76 |         parser.print_help(sys.stderr)
 77 |         sys.exit(0)
 78 |     
 79 |     elif args.command == 'dev':
 80 |         # Run with MCP Inspector
 81 |         print("🚀 Starting Flutter MCP Server with MCP Inspector...", file=sys.stderr)
 82 |         print("📝 Opening browser at http://localhost:5173", file=sys.stderr)
 83 |         print("⚡ Use Ctrl+C to stop the server\n", file=sys.stderr)
 84 |         
 85 |         import subprocess
 86 |         try:
 87 |             # Set environment variables
 88 |             env = os.environ.copy()
 89 |             if args.cache_dir:
 90 |                 env['CACHE_DIR'] = args.cache_dir
 91 |             if args.debug:
 92 |                 env['DEBUG'] = '1'
 93 |             
 94 |             subprocess.run(['mcp', 'dev', 'src/flutter_mcp/server.py'], env=env)
 95 |         except KeyboardInterrupt:
 96 |             print("\n\n✅ Server stopped", file=sys.stderr)
 97 |         except FileNotFoundError:
 98 |             print("❌ Error: MCP CLI not found. Please install with: pip install 'mcp[cli]'", file=sys.stderr)
 99 |             sys.exit(1)
100 |     
101 |     else:  # start or serve
102 |         # Run the server directly
103 |         # Print cool header using rich
104 |         from flutter_mcp.logging_utils import print_server_header
105 |         print_server_header()
106 |         
107 |         from rich.console import Console
108 |         console = Console(stderr=True)
109 |         
110 |         console.print(f"\n[bold green]🚀 Starting Flutter MCP Server v{__version__}[/bold green]")
111 |         console.print("[cyan]📦 Using built-in SQLite cache[/cyan]")
112 |         if args.cache_dir:
113 |             console.print(f"[dim]💾 Cache directory: {args.cache_dir}[/dim]")
114 |         
115 |         # Show transport-specific information
116 |         if args.transport == 'stdio':
117 |             console.print("[yellow]⚡ Server running via STDIO - connect your AI assistant[/yellow]")
118 |         elif args.transport in ['sse', 'http']:
119 |             console.print(f"[yellow]🌐 Server running on {args.transport.upper()} transport[/yellow]")
120 |             console.print(f"[yellow]📡 Listening on http://{args.host}:{args.port}[/yellow]")
121 |             if args.transport == 'sse':
122 |                 console.print(f"[dim]   SSE endpoint: http://{args.host}:{args.port}/sse[/dim]")
123 |             
124 |         console.print("[yellow]⚡ Use Ctrl+C to stop the server[/yellow]\n")
125 |         
126 |         # Set environment variables
127 |         if args.cache_dir:
128 |             os.environ['CACHE_DIR'] = args.cache_dir
129 |         if args.debug:
130 |             os.environ['DEBUG'] = '1'
131 |         
132 |         # Set transport configuration
133 |         os.environ['MCP_TRANSPORT'] = args.transport
134 |         os.environ['MCP_PORT'] = str(args.port)
135 |         os.environ['MCP_HOST'] = args.host
136 |         
137 |         # Set flag to indicate we're running from CLI
138 |         sys._flutter_mcp_cli = True
139 |         
140 |         try:
141 |             # Import and run the server
142 |             from . import main as server_main
143 |             server_main()
144 |         except KeyboardInterrupt:
145 |             print("\n\n✅ Server stopped", file=sys.stderr)
146 |         except ImportError as e:
147 |             print(f"❌ Error: Failed to import server: {e}", file=sys.stderr)
148 |             print("Make sure you're in the correct directory and dependencies are installed", file=sys.stderr)
149 |             sys.exit(1)
150 | 
151 | 
152 | if __name__ == "__main__":
153 |     main()
```

--------------------------------------------------------------------------------
/npm-wrapper/bin/flutter-mcp.js:
--------------------------------------------------------------------------------

```javascript
  1 | #!/usr/bin/env node
  2 | /**
  3 |  * Flutter MCP Server wrapper for Node.js
  4 |  * This script ensures Python is available and runs the Flutter MCP server
  5 |  */
  6 | 
  7 | const { execa } = require('execa');
  8 | const which = require('which');
  9 | const ora = require('ora');
 10 | const path = require('path');
 11 | const fs = require('fs');
 12 | 
 13 | async function findPython() {
 14 |   const pythonCommands = ['python3', 'python'];
 15 |   
 16 |   for (const cmd of pythonCommands) {
 17 |     try {
 18 |       await which(cmd);
 19 |       // Verify it's Python 3.8+
 20 |       const { stdout } = await execa(cmd, ['--version']);
 21 |       const match = stdout.match(/Python (\d+)\.(\d+)/);
 22 |       if (match) {
 23 |         const major = parseInt(match[1]);
 24 |         const minor = parseInt(match[2]);
 25 |         if (major >= 3 && minor >= 8) {
 26 |           return cmd;
 27 |         }
 28 |       }
 29 |     } catch (e) {
 30 |       // Continue to next command
 31 |     }
 32 |   }
 33 |   return null;
 34 | }
 35 | 
 36 | async function installFlutterMCP(pythonCmd, forceInstall = false) {
 37 |   const spinner = ora('Checking Flutter MCP Server installation...').start();
 38 |   
 39 |   try {
 40 |     // Check if already installed
 41 |     if (!forceInstall) {
 42 |       try {
 43 |         await execa(pythonCmd, ['-m', 'flutter_mcp', '--version']);
 44 |         spinner.succeed('Flutter MCP Server is ready');
 45 |         return true;
 46 |       } catch (e) {
 47 |         // Not installed, continue with installation
 48 |       }
 49 |     }
 50 |     
 51 |     // Install using pip
 52 |     spinner.text = 'Installing Flutter MCP Server from PyPI...';
 53 |     
 54 |     // For npx usage, install to user directory to avoid permission issues
 55 |     const isNpx = process.env.npm_execpath && process.env.npm_execpath.includes('npx');
 56 |     const pipArgs = ['-m', 'pip', 'install', '--user', 'flutter-mcp'];
 57 |     
 58 |     if (!isNpx) {
 59 |       // For global install, try without --user first
 60 |       pipArgs.splice(pipArgs.indexOf('--user'), 1);
 61 |     }
 62 |     
 63 |     await execa(pythonCmd, pipArgs, {
 64 |       stdio: 'inherit'
 65 |     });
 66 |     
 67 |     spinner.succeed('Flutter MCP Server installed successfully');
 68 |     return true;
 69 |   } catch (error) {
 70 |     spinner.fail('Failed to install Flutter MCP Server');
 71 |     console.error(error.message);
 72 |     return false;
 73 |   }
 74 | }
 75 | 
 76 | async function runFlutterMCP(pythonCmd, args) {
 77 |   try {
 78 |     // Run the server
 79 |     await execa(pythonCmd, ['-m', 'flutter_mcp', ...args], {
 80 |       stdio: 'inherit'
 81 |     });
 82 |   } catch (error) {
 83 |     if (error.exitCode !== 0) {
 84 |       console.error('Flutter MCP Server exited with error');
 85 |       process.exit(error.exitCode);
 86 |     }
 87 |   }
 88 | }
 89 | 
 90 | async function main() {
 91 |   const args = process.argv.slice(2);
 92 |   
 93 |   // Check for help flag
 94 |   if (args.includes('--help') || args.includes('-h')) {
 95 |     console.log(`
 96 | Flutter MCP Server - Real-time Flutter/Dart documentation for AI assistants
 97 | 
 98 | Usage: 
 99 |   npx flutter-mcp [options]              # One-time usage
100 |   npm install -g flutter-mcp             # Global installation
101 |   flutter-mcp [options]                  # After global install
102 | 
103 | Options:
104 |   --help, -h        Show this help message
105 |   --version, -v     Show version information
106 |   --install         Install/update the Python package
107 |   --stdio           Run in stdio mode (default for MCP clients)
108 |   --http            Run in HTTP mode
109 |   --sse             Run in Server-Sent Events mode
110 |   --port <port>     Port for HTTP/SSE mode (default: 3000)
111 |   
112 | Examples:
113 |   # Quick start with npx (no installation)
114 |   npx flutter-mcp
115 |   
116 |   # Install globally then use
117 |   npm install -g flutter-mcp
118 |   flutter-mcp
119 |   
120 |   # Use with Claude Desktop (stdio mode)
121 |   npx flutter-mcp --stdio
122 | 
123 | Claude Desktop Configuration:
124 |   {
125 |     "mcpServers": {
126 |       "flutter-docs": {
127 |         "command": "npx",
128 |         "args": ["flutter-mcp", "--stdio"]
129 |       }
130 |     }
131 |   }
132 | 
133 | For more information, visit: https://github.com/flutter-mcp/flutter-mcp
134 | `);
135 |     process.exit(0);
136 |   }
137 |   
138 |   // Find Python
139 |   const spinner = ora('Checking Python installation...').start();
140 |   const pythonCmd = await findPython();
141 |   
142 |   if (!pythonCmd) {
143 |     spinner.fail('Python 3.8+ is required but not found');
144 |     console.error(`
145 | Please install Python 3.8 or later:
146 | - macOS: brew install python3
147 | - Ubuntu/Debian: sudo apt install python3 python3-pip
148 | - Windows: https://www.python.org/downloads/
149 | `);
150 |     process.exit(1);
151 |   }
152 |   
153 |   spinner.succeed(`Found Python: ${pythonCmd}`);
154 |   
155 |   // Install Flutter MCP if needed
156 |   const forceInstall = args.includes('--install');
157 |   const installed = await installFlutterMCP(pythonCmd, forceInstall);
158 |   if (!installed) {
159 |     process.exit(1);
160 |   }
161 |   
162 |   // If --install flag was provided, exit here
163 |   if (args.includes('--install') && !args.includes('--stdio')) {
164 |     console.log('\nFlutter MCP Server is ready to use!');
165 |     process.exit(0);
166 |   }
167 |   
168 |   // Default to stdio mode if no transport specified
169 |   if (!args.includes('--http') && !args.includes('--sse') && !args.includes('--stdio')) {
170 |     args.push('--stdio');
171 |   }
172 |   
173 |   // Run the server
174 |   if (!args.includes('--stdio')) {
175 |     console.log('\nStarting Flutter MCP Server...\n');
176 |   }
177 |   await runFlutterMCP(pythonCmd, args);
178 | }
179 | 
180 | // Handle errors
181 | process.on('unhandledRejection', (error) => {
182 |   console.error('Unhandled error:', error);
183 |   process.exit(1);
184 | });
185 | 
186 | // Run main function
187 | main().catch((error) => {
188 |   console.error('Fatal error:', error);
189 |   process.exit(1);
190 | });
```

--------------------------------------------------------------------------------
/docs/token-management-implementation.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Token Management Implementation Plan
  2 | 
  3 | ## Overview
  4 | 
  5 | This document outlines the implementation of token management for Flutter MCP, inspired by Context7's simple approach but adapted for our client-side architecture.
  6 | 
  7 | ## Goals
  8 | 
  9 | 1. **Simple API**: Add optional `tokens` parameter to all documentation tools
 10 | 2. **Smart Truncation**: Preserve most important content when limits are reached
 11 | 3. **Performance**: Fast token counting without impacting response times
 12 | 4. **Transparency**: Clear indication when content is truncated
 13 | 5. **Context7-like UX**: Sensible defaults, no required parameters
 14 | 
 15 | ## Implementation Phases
 16 | 
 17 | ### Phase 1: Basic Token Management (Status: In Progress)
 18 | - [ ] Add `tokens` parameter to all documentation tools
 19 | - [ ] Implement basic token counting (word-based approximation)
 20 | - [ ] Simple truncation at section boundaries
 21 | - [ ] Update response format with token metadata
 22 | 
 23 | ### Phase 2: Smart Truncation (Status: Pending)
 24 | - [ ] Create priority-based content classification
 25 | - [ ] Implement Flutter-aware section detection
 26 | - [ ] Add intelligent truncation algorithm
 27 | - [ ] Preserve markdown formatting during truncation
 28 | 
 29 | ### Phase 3: Cache Integration (Status: Pending)
 30 | - [ ] Update cache schema to store token counts
 31 | - [ ] Modify cache read/write operations
 32 | - [ ] Ensure backward compatibility with existing cache
 33 | 
 34 | ### Phase 4: Testing & Documentation (Status: Pending)
 35 | - [ ] Unit tests for token counting
 36 | - [ ] Integration tests for truncation
 37 | - [ ] Update API documentation
 38 | - [ ] Add usage examples
 39 | 
 40 | ## Technical Design
 41 | 
 42 | ### Token Counting Strategy
 43 | 
 44 | **Approximation Method** (Default):
 45 | ```python
 46 | def approximate_tokens(text: str) -> int:
 47 |     """Fast token approximation: ~1.3 tokens per word"""
 48 |     return int(len(text.split()) * 1.3)
 49 | ```
 50 | 
 51 | **Accurate Counting** (Optional):
 52 | - Use tiktoken for GPT models
 53 | - Lazy-loaded to avoid startup overhead
 54 | - Configurable via environment variable
 55 | 
 56 | ### Default Token Limits
 57 | 
 58 | | Tool | Default | Minimum | Rationale |
 59 | |------|---------|---------|-----------|
 60 | | get_flutter_docs | 8,000 | 1,000 | Single class documentation |
 61 | | search_flutter_docs | 5,000 | 1,000 | Multiple search results |
 62 | | get_pub_package_info | 6,000 | 1,000 | Package info + README |
 63 | | process_flutter_mentions | 4,000 | 500 | Per mention |
 64 | 
 65 | ### Truncation Priority
 66 | 
 67 | 1. **CRITICAL**: Class description, constructor signatures
 68 | 2. **HIGH**: Common methods (build, setState), essential properties
 69 | 3. **MEDIUM**: Secondary methods, code examples
 70 | 4. **LOW**: Inherited members, see also sections
 71 | 5. **MINIMAL**: Related classes, external links
 72 | 
 73 | ### Response Format
 74 | 
 75 | ```json
 76 | {
 77 |   "content": "# Widget Name\n...",
 78 |   "source": "live|cache",
 79 |   "truncated": true,
 80 |   "token_count": 2000,
 81 |   "original_tokens": 5234,
 82 |   "sections_included": ["description", "constructors"],
 83 |   "sections_truncated": ["methods", "examples"],
 84 |   "truncation_note": "Documentation limited to 2000 tokens."
 85 | }
 86 | ```
 87 | 
 88 | ## Implementation Progress
 89 | 
 90 | ### ✅ Completed
 91 | - Created implementation plan document
 92 | - Added `tokens` parameter to all documentation tools
 93 | - Implemented `TokenManager` class with approximation and accurate counting
 94 | - Created `DocumentTruncator` class with section detection
 95 | - Updated tool signatures with validation
 96 | - Integrated token management into server processing pipeline
 97 | - Updated cache to store and retrieve token counts
 98 | - Added schema migration for existing cache databases
 99 | - Updated response format to include token metadata
100 | - Created comprehensive test suite
101 | - Added usage examples and demo script
102 | 
103 | ### 🎉 All phases complete!
104 | 
105 | ## Implementation Summary
106 | 
107 | ### What Was Built
108 | 
109 | 1. **TokenManager** (`src/flutter_mcp/token_manager.py`)
110 |    - Fast word-based approximation (default)
111 |    - Optional accurate counting with tiktoken
112 |    - Environment variable configuration
113 |    - ~1.3 tokens per word ratio
114 | 
115 | 2. **DocumentTruncator** (`src/flutter_mcp/truncation.py`)
116 |    - Smart section detection for Flutter docs
117 |    - Priority-based content preservation
118 |    - Maintains markdown formatting
119 |    - Graceful degradation for edge cases
120 | 
121 | 3. **Server Integration**
122 |    - All tools now accept optional `tokens` parameter
123 |    - Automatic truncation when limits exceeded
124 |    - Token metadata in all responses
125 |    - Transparent to existing users (backward compatible)
126 | 
127 | 4. **Cache Enhancement**
128 |    - Stores token counts with content
129 |    - Avoids re-counting for cached docs
130 |    - Schema migration for existing databases
131 |    - Statistics tracking for cached tokens
132 | 
133 | 5. **Testing & Documentation**
134 |    - Comprehensive test suite
135 |    - Interactive demo script
136 |    - Usage examples
137 | 
138 | ### Key Features
139 | 
140 | - **Simple like Context7**: Optional parameter, sensible defaults
141 | - **Fast**: Approximation takes <1ms for typical docs
142 | - **Smart**: Preserves most important content when truncating
143 | - **Transparent**: Users see token counts and truncation status
144 | - **Cached**: Token counts stored to avoid recalculation
145 | 
146 | ### Usage
147 | 
148 | ```python
149 | # Default usage - no change needed
150 | docs = await get_flutter_docs("Container")
151 | 
152 | # With token limit
153 | docs = await get_flutter_docs("Container", tokens=2000)
154 | 
155 | # Response includes token info
156 | {
157 |   "content": "...",
158 |   "token_count": 1998,
159 |   "truncated": true,
160 |   "truncation_note": "Documentation limited to 2000 tokens."
161 | }
162 | ```
163 | 
164 | ## Notes
165 | 
166 | - Using word-based approximation for performance (1.3 tokens/word)
167 | - Optional tiktoken integration for accuracy
168 | - Cache stores both content and token count
169 | - Backward compatible with existing cache entries
```

--------------------------------------------------------------------------------
/docs/planning/flutter-mcp-project-summary.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Flutter MCP Server Project - Complete Summary
  2 | 
  3 | ## Background: MCP Server Configuration Journey
  4 | 
  5 | ### Initial Setup - Three Main MCP Servers
  6 | 
  7 | 1. **Firebase MCP** (Account-wide access)
  8 |    - Official Firebase CLI MCP server
  9 |    - Access to all Firebase projects
 10 |    - No `--dir` flag for unscoped access
 11 |    - Authentication via `firebase login`
 12 | 
 13 | 2. **Supabase MCP** (Account-wide access)
 14 |    - Uses Personal Access Token (NOT project API keys)
 15 |    - Token from Account Settings → Access Tokens
 16 |    - `--read-only` flag recommended for safety
 17 |    - Access to all Supabase projects without `--project-ref`
 18 | 
 19 | 3. **ZEN MCP Server**
 20 |    - Docker-based multi-AI orchestration
 21 |    - Connects Claude with Gemini, O3, GPT-4o
 22 |    - Enables AI-to-AI conversations
 23 |    - Already running as Docker container
 24 | 
 25 | ### Configuration Files
 26 | 
 27 | **Claude Desktop** (`~/Library/Application Support/Claude/claude_desktop_config.json`):
 28 | ```json
 29 | {
 30 |   "mcpServers": {
 31 |     "firebase-all": {
 32 |       "command": "npx",
 33 |       "args": ["-y", "firebase-tools@latest", "experimental:mcp"]
 34 |     },
 35 |     "supabase-all": {
 36 |       "command": "npx",
 37 |       "args": [
 38 |         "-y",
 39 |         "@supabase/mcp-server-supabase@latest",
 40 |         "--read-only"
 41 |       ],
 42 |       "env": {
 43 |         "SUPABASE_ACCESS_TOKEN": "sbp_YOUR_TOKEN_HERE"
 44 |       }
 45 |     },
 46 |     "zen": {
 47 |       "command": "docker",
 48 |       "args": [
 49 |         "exec",
 50 |         "-i",
 51 |         "zen-mcp-server",
 52 |         "python",
 53 |         "server.py"
 54 |       ]
 55 |     }
 56 |   }
 57 | }
 58 | ```
 59 | 
 60 | **Claude Code** (stored in `~/.claude.json`):
 61 | ```bash
 62 | # Add globally with user scope
 63 | claude mcp add firebase-global -s user -- npx -y firebase-tools@latest experimental:mcp
 64 | claude mcp add supabase-global -s user -e SUPABASE_ACCESS_TOKEN=your_token -- npx -y @supabase/mcp-server-supabase@latest --read-only
 65 | claude mcp add zen -s user -- docker exec -i zen-mcp-server python server.py
 66 | ```
 67 | 
 68 | ## Context7 and Deepwiki Research
 69 | 
 70 | ### Context7 (by Upstash)
 71 | - **Purpose**: Real-time library documentation
 72 | - **Problem Solved**: Outdated API information in LLMs
 73 | - **Coverage**: 50+ JavaScript/Python libraries
 74 | - **Key Feature**: Dynamic documentation fetching
 75 | - **Cost**: Completely FREE, no API keys needed
 76 | - **Usage**: Add "use context7" to prompts
 77 | - **Architecture**: Local Node.js execution
 78 | 
 79 | ### Deepwiki (by Cognition Labs)
 80 | - **Purpose**: GitHub repository understanding
 81 | - **Problem Solved**: Quick codebase comprehension
 82 | - **Coverage**: 50,000+ indexed repositories
 83 | - **Key Feature**: AI-analyzed repository documentation
 84 | - **Cost**: Free for public repos
 85 | - **Architecture**: Remote SSE server
 86 | 
 87 | ### Why They Don't Work for Flutter
 88 | - Context7: Only supports JavaScript/Python libraries
 89 | - Deepwiki: Works for Flutter repos but doesn't understand Dart/Flutter APIs specifically
 90 | 
 91 | ## Flutter MCP Server Project Plan
 92 | 
 93 | ### Vision
 94 | Create a Context7-like MCP server specifically for Flutter/Dart ecosystem that provides:
 95 | - Real-time Flutter/Dart API documentation
 96 | - Pub.dev package documentation on-demand
 97 | - Flutter cookbook and samples
 98 | - Stack Overflow Flutter solutions
 99 | 
100 | ### Technical Decisions
101 | 
102 | 1. **Inspiration**: Context7's approach (real-time docs > static knowledge)
103 | 2. **Language**: Python (easier for Claude Code to write)
104 | 3. **Architecture**: On-demand fetching (better for marketing "supports ALL pub.dev packages")
105 | 4. **Distribution**: Public GitHub/npm package
106 | 
107 | ### Data Sources to Integrate
108 | - **Official APIs**: api.flutter.dev, api.dart.dev
109 | - **Package Registry**: pub.dev (on-demand fetching)
110 | - **Examples**: Flutter cookbook, official samples
111 | - **Community**: Stack Overflow Flutter tags
112 | 
113 | ### MVP Scope
114 | - Start with official Flutter/Dart API documentation only
115 | - Estimated time: 2-4 hours with Claude Code
116 | - Focus on working prototype first
117 | 
118 | ### Marketing Strategy
119 | - **Reddit Pitch**: "MCP server that gives Claude access to ALL pub.dev packages"
120 | - **Key Differentiator**: Always up-to-date Flutter/Dart documentation
121 | - **Target Audience**: Flutter developers using Claude/Cursor/VS Code
122 | 
123 | ### Technical Requirements
124 | 1. MCP protocol implementation in Python
125 | 2. Web scraping/API integration for documentation sources
126 | 3. Caching mechanism for performance
127 | 4. Simple installation via npx/pip
128 | 
129 | ### Development Approach
130 | 1. Use Claude Code to build the server
131 | 2. Start with minimal viable version
132 | 3. Test with personal projects
133 | 4. Expand to more sources
134 | 5. Release to community
135 | 
136 | ## Next Steps
137 | 
138 | 1. **Get MCP Documentation**: Need current MCP server development guide
139 | 2. **Create Project Structure**: Basic Python MCP server template
140 | 3. **MVP Features**:
141 |    - Connect to api.flutter.dev
142 |    - Parse and return documentation
143 |    - Handle basic queries
144 | 4. **Test & Iterate**: Use with Claude Desktop/Code
145 | 5. **Expand**: Add pub.dev, cookbook, etc.
146 | 6. **Release**: GitHub + announcement on r/FlutterDev
147 | 
148 | ## Resources Needed
149 | 
150 | - Current MCP server development documentation
151 | - Python MCP SDK examples
152 | - Flutter/Dart API endpoints
153 | - Pub.dev API documentation
154 | - Testing environment setup guide
155 | 
156 | ## Potential Challenges
157 | 
158 | 1. **API Rate Limits**: Need caching strategy
159 | 2. **Documentation Parsing**: Flutter docs structure complexity
160 | 3. **Performance**: Fast response times for good UX
161 | 4. **Maintenance**: Keeping up with Flutter updates
162 | 
163 | ## Success Metrics
164 | 
165 | - Working MVP in 4 hours
166 | - <1 second response time
167 | - Covers 100% of official Flutter/Dart APIs
168 | - Positive reception on Reddit/Twitter
169 | - 100+ GitHub stars in first month
170 | 
171 | ---
172 | 
173 | *This document summarizes the entire conversation about MCP servers configuration and the Flutter MCP server project idea from [Date: 2025-06-20]*
```

--------------------------------------------------------------------------------
/docs/VERSION_SPECIFICATION.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Version Specification System
  2 | 
  3 | The Flutter MCP server now supports advanced version specifications for pub.dev packages, allowing AI assistants to fetch documentation for specific package versions based on various constraint formats.
  4 | 
  5 | ## Overview
  6 | 
  7 | When referencing packages with `@flutter_mcp`, you can now specify version constraints similar to how they work in `pubspec.yaml` files. This ensures AI assistants get documentation that matches the exact version requirements of a project.
  8 | 
  9 | ## Supported Formats
 10 | 
 11 | ### 1. Exact Versions
 12 | 
 13 | Specify an exact version to fetch documentation for that specific release:
 14 | 
 15 | ```
 16 | @flutter_mcp riverpod:2.5.1
 17 | @flutter_mcp provider:6.0.5
 18 | @flutter_mcp dio:5.3.2
 19 | ```
 20 | 
 21 | ### 2. Caret Syntax (^)
 22 | 
 23 | The caret syntax allows compatible updates according to semantic versioning:
 24 | 
 25 | ```
 26 | @flutter_mcp provider:^6.0.0    # Allows >=6.0.0 <7.0.0
 27 | @flutter_mcp bloc:^8.1.0        # Allows >=8.1.0 <9.0.0
 28 | @flutter_mcp get:^4.6.5         # Allows >=4.6.5 <5.0.0
 29 | ```
 30 | 
 31 | For packages with 0.x.x versions, the caret is more restrictive:
 32 | - `^0.2.3` allows `>=0.2.3 <0.3.0`
 33 | - `^0.0.3` allows `>=0.0.3 <0.0.4`
 34 | 
 35 | ### 3. Version Ranges
 36 | 
 37 | Specify explicit version ranges using comparison operators:
 38 | 
 39 | ```
 40 | @flutter_mcp dio:>=5.0.0 <6.0.0    # Any 5.x version
 41 | @flutter_mcp http:>0.13.0 <=1.0.0  # Greater than 0.13.0, up to and including 1.0.0
 42 | @flutter_mcp provider:>=6.0.0       # 6.0.0 or higher
 43 | @flutter_mcp bloc:<9.0.0            # Any version below 9.0.0
 44 | ```
 45 | 
 46 | ### 4. Special Keywords
 47 | 
 48 | Use keywords to fetch specific version types:
 49 | 
 50 | ```
 51 | @flutter_mcp provider:latest   # Absolute latest version (including pre-releases)
 52 | @flutter_mcp riverpod:stable   # Latest stable version (no pre-releases)
 53 | @flutter_mcp bloc:dev          # Latest dev version
 54 | @flutter_mcp get:beta          # Latest beta version
 55 | @flutter_mcp dio:alpha         # Latest alpha version
 56 | ```
 57 | 
 58 | ### 5. No Version (Current Behavior)
 59 | 
 60 | When no version is specified, the system fetches the latest stable version:
 61 | 
 62 | ```
 63 | @flutter_mcp provider          # Latest stable version
 64 | @flutter_mcp riverpod          # Latest stable version
 65 | ```
 66 | 
 67 | ## Examples in Context
 68 | 
 69 | ### Example 1: Upgrading Dependencies
 70 | 
 71 | ```
 72 | I'm upgrading from @flutter_mcp provider:^5.0.0 to @flutter_mcp provider:^6.0.0.
 73 | What are the breaking changes I need to be aware of?
 74 | ```
 75 | 
 76 | ### Example 2: Testing Pre-release Features
 77 | 
 78 | ```
 79 | I want to try the new features in @flutter_mcp riverpod:beta.
 80 | Can you show me what's new compared to @flutter_mcp riverpod:stable?
 81 | ```
 82 | 
 83 | ### Example 3: Version Compatibility
 84 | 
 85 | ```
 86 | My project uses @flutter_mcp dio:>=5.0.0 <6.0.0 for networking.
 87 | Is this compatible with @flutter_mcp retrofit:^4.0.0?
 88 | ```
 89 | 
 90 | ### Example 4: Legacy Code
 91 | 
 92 | ```
 93 | I'm maintaining legacy code that uses @flutter_mcp provider:5.0.0.
 94 | Can you help me understand the API from that specific version?
 95 | ```
 96 | 
 97 | ## How It Works
 98 | 
 99 | ### Version Resolution
100 | 
101 | 1. **Parsing**: The system parses the version specification to understand the constraint type
102 | 2. **Resolution**: For constraints (not exact versions), the system queries pub.dev to find all available versions
103 | 3. **Selection**: The highest version that satisfies the constraint is selected
104 | 4. **Fetching**: Documentation for the selected version is retrieved and cached
105 | 
106 | ### Caching
107 | 
108 | Version-specific documentation is cached separately:
109 | - Cache key includes the package name and resolved version
110 | - Different version constraints that resolve to the same version share the cache
111 | - Cache duration: 12 hours for package documentation
112 | 
113 | ### Error Handling
114 | 
115 | The system provides helpful error messages:
116 | - If a version doesn't exist: Lists available versions
117 | - If constraint can't be resolved: Explains why
118 | - If package doesn't exist: Standard package not found error
119 | 
120 | ## Implementation Details
121 | 
122 | ### Version Parser
123 | 
124 | The `VersionParser` class handles parsing of version specifications:
125 | - Regex patterns for different constraint formats
126 | - Semantic version comparison logic
127 | - Support for pre-release versions
128 | 
129 | ### Version Resolver
130 | 
131 | The `VersionResolver` class interfaces with pub.dev API:
132 | - Fetches available versions from pub.dev
133 | - Applies constraint logic to find best match
134 | - Handles special keywords (latest, stable, etc.)
135 | 
136 | ### Integration
137 | 
138 | The version system is fully integrated with:
139 | - `process_flutter_mentions`: Parses mentions with version specs
140 | - `get_pub_package_info`: Fetches version-specific documentation
141 | - Cache system: Version-aware cache keys
142 | 
143 | ## Best Practices
144 | 
145 | 1. **Use Caret for Flexibility**: `^` allows compatible updates
146 |    ```
147 |    @flutter_mcp provider:^6.0.0
148 |    ```
149 | 
150 | 2. **Exact Versions for Reproducibility**: When you need specific behavior
151 |    ```
152 |    @flutter_mcp riverpod:2.5.1
153 |    ```
154 | 
155 | 3. **Ranges for Compatibility**: When working with multiple packages
156 |    ```
157 |    @flutter_mcp dio:>=5.0.0 <6.0.0
158 |    ```
159 | 
160 | 4. **Keywords for Exploration**: Testing new features
161 |    ```
162 |    @flutter_mcp bloc:beta
163 |    ```
164 | 
165 | ## Limitations
166 | 
167 | 1. **Flutter/Dart Classes**: Version specifications only work with pub.dev packages, not Flutter framework classes
168 |    - ✅ `@flutter_mcp provider:^6.0.0`
169 |    - ❌ `@flutter_mcp material.AppBar:^3.0.0`
170 | 
171 | 2. **Version Availability**: Only versions published on pub.dev are accessible
172 | 
173 | 3. **Rate Limiting**: Version resolution requires additional API calls, subject to rate limits
174 | 
175 | ## Future Enhancements
176 | 
177 | Potential future improvements:
178 | 1. Flutter SDK version-specific documentation
179 | 2. Git commit/branch references for packages
180 | 3. Local path references for development
181 | 4. Version comparison tools
182 | 5. Migration guide generation between versions
```

--------------------------------------------------------------------------------
/ERROR_HANDLING.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Flutter MCP Server - Error Handling & Resilience
  2 | 
  3 | This document describes the comprehensive error handling and resilience features implemented in the Flutter MCP Server.
  4 | 
  5 | ## Overview
  6 | 
  7 | The Flutter MCP Server is designed to be highly resilient and provide a good user experience even when external services are unavailable or experiencing issues. The server implements multiple layers of error handling, retry logic, and graceful degradation.
  8 | 
  9 | ## Error Handling Features
 10 | 
 11 | ### 1. Retry Logic with Exponential Backoff
 12 | 
 13 | All HTTP requests implement automatic retry with exponential backoff:
 14 | 
 15 | - **Max retries**: 3 attempts
 16 | - **Base delay**: 1 second
 17 | - **Max delay**: 16 seconds
 18 | - **Jitter**: Random 0-1 second added to prevent thundering herd
 19 | - **Smart retries**: Only retries on network errors and 5xx server errors, not 4xx client errors
 20 | 
 21 | ```python
 22 | @with_retry(max_retries=3)
 23 | async def fetch_data():
 24 |     # Automatic retry on network failures
 25 |     pass
 26 | ```
 27 | 
 28 | ### 2. Comprehensive Error Types
 29 | 
 30 | The server categorizes errors for better handling:
 31 | 
 32 | - `NetworkError`: Connection failures, timeouts
 33 | - `DocumentationNotFoundError`: Resource not found (404)
 34 | - `RateLimitError`: Rate limit exceeded (429)
 35 | - `CacheError`: Cache operation failures
 36 | 
 37 | ### 3. User-Friendly Error Responses
 38 | 
 39 | All errors return structured responses with:
 40 | 
 41 | ```json
 42 | {
 43 |   "error": true,
 44 |   "error_type": "not_found",
 45 |   "message": "Documentation not found for widgets.NonExistentWidget",
 46 |   "suggestions": [
 47 |     "Check if 'NonExistentWidget' is spelled correctly",
 48 |     "Verify that 'NonExistentWidget' exists in the 'widgets' library",
 49 |     "Common libraries: widgets, material, cupertino, painting, rendering",
 50 |     "Try searching with: search_flutter_docs('NonExistentWidget')"
 51 |   ],
 52 |   "context": {
 53 |     "class": "NonExistentWidget",
 54 |     "library": "widgets",
 55 |     "status_code": 404
 56 |   },
 57 |   "timestamp": "2024-01-20T10:30:00Z"
 58 | }
 59 | ```
 60 | 
 61 | ### 4. Circuit Breaker Pattern
 62 | 
 63 | Prevents cascading failures when external services are down:
 64 | 
 65 | - **Failure threshold**: 5 consecutive failures
 66 | - **Recovery timeout**: 60 seconds
 67 | - **States**: CLOSED (normal), OPEN (failing), HALF-OPEN (testing)
 68 | 
 69 | ```python
 70 | flutter_docs_circuit = CircuitBreaker(
 71 |     failure_threshold=5,
 72 |     recovery_timeout=60.0
 73 | )
 74 | ```
 75 | 
 76 | ### 5. Graceful Degradation
 77 | 
 78 | The server continues operating even when some components fail:
 79 | 
 80 | - **Cache failures**: Continue without caching
 81 | - **README fetch failures**: Return package info without README
 82 | - **Enrichment failures**: Return search results without full documentation
 83 | 
 84 | ### 6. Health Monitoring
 85 | 
 86 | Comprehensive health check system:
 87 | 
 88 | ```python
 89 | # Health check with timeout protection
 90 | async def health_check():
 91 |     # Tests Flutter docs API
 92 |     # Tests pub.dev API  
 93 |     # Tests cache functionality
 94 |     # Returns detailed status for each component
 95 | ```
 96 | 
 97 | ### 7. Timeout Protection
 98 | 
 99 | All operations have configurable timeouts:
100 | 
101 | - **Default timeout**: 30 seconds
102 | - **Connection timeout**: 10 seconds
103 | - **Health check timeout**: 10 seconds
104 | 
105 | ### 8. Rate Limiting
106 | 
107 | Respectful rate limiting for external APIs:
108 | 
109 | - **Default rate**: 2 requests/second
110 | - **Adjustable during high load**
111 | - **Per-service rate limiters**
112 | 
113 | ## Error Scenarios Handled
114 | 
115 | ### Network Errors
116 | 
117 | - Connection timeouts
118 | - DNS resolution failures
119 | - Connection refused
120 | - Network unreachable
121 | 
122 | **User Experience**: Clear message about network issues with retry suggestions
123 | 
124 | ### API Errors
125 | 
126 | - 404 Not Found: Helpful suggestions for correct names/formats
127 | - 429 Rate Limited: Advises waiting and provides retry timing
128 | - 500-599 Server Errors: Indicates external service issues
129 | - Invalid responses: Handles malformed JSON/HTML
130 | 
131 | ### Input Validation
132 | 
133 | - Invalid class names
134 | - Invalid package names (must be lowercase with underscores)
135 | - Malformed queries
136 | - Empty inputs
137 | 
138 | ### Cache Errors
139 | 
140 | - Cache initialization failures: Falls back to no-cache mode
141 | - Cache read/write errors: Logged but don't fail requests
142 | - Corrupted cache entries: Automatic cleanup
143 | 
144 | ## Testing Error Handling
145 | 
146 | Run the error handling test suite:
147 | 
148 | ```bash
149 | python test_error_handling.py
150 | ```
151 | 
152 | This tests:
153 | 1. Invalid Flutter class names
154 | 2. Invalid library names
155 | 3. Non-existent packages
156 | 4. Invalid package name formats
157 | 5. Search with no results
158 | 6. Mention processing with errors
159 | 7. Health check functionality
160 | 8. Graceful degradation
161 | 
162 | ## Logging
163 | 
164 | Structured logging with contextual information:
165 | 
166 | ```python
167 | logger.error(
168 |     "http_error",
169 |     status_code=404,
170 |     url="https://api.flutter.dev/...",
171 |     class_name="NonExistentWidget",
172 |     library="widgets"
173 | )
174 | ```
175 | 
176 | ## Recovery Mechanisms
177 | 
178 | ### Automatic Recovery
179 | 
180 | 1. **Cache clearing**: After 3 consecutive failures
181 | 2. **Connection pool reset**: After 5 consecutive failures  
182 | 3. **Rate limit reduction**: After 7 consecutive failures
183 | 
184 | ### Manual Recovery
185 | 
186 | - Restart server to reset all circuit breakers
187 | - Clear cache directory to remove corrupted data
188 | - Check logs for specific error patterns
189 | 
190 | ## Best Practices
191 | 
192 | 1. **Always check for errors** in responses:
193 |    ```python
194 |    result = await get_flutter_docs("Widget", "widgets")
195 |    if result.get("error"):
196 |        # Handle error
197 |    ```
198 | 
199 | 2. **Use suggestions** provided in error responses
200 | 3. **Implement backoff** when seeing rate limit errors
201 | 4. **Monitor health endpoint** for service status
202 | 
203 | ## Configuration
204 | 
205 | Error handling can be configured via environment variables:
206 | 
207 | ```bash
208 | # Retry configuration
209 | MAX_RETRIES=3
210 | BASE_RETRY_DELAY=1.0
211 | MAX_RETRY_DELAY=16.0
212 | 
213 | # Timeout configuration  
214 | DEFAULT_TIMEOUT=30.0
215 | CONNECTION_TIMEOUT=10.0
216 | 
217 | # Circuit breaker
218 | FAILURE_THRESHOLD=5
219 | RECOVERY_TIMEOUT=60.0
220 | 
221 | # Rate limiting
222 | REQUESTS_PER_SECOND=2.0
223 | ```
224 | 
225 | ## Monitoring
226 | 
227 | Monitor these metrics for service health:
228 | 
229 | - Error rates by type
230 | - Circuit breaker state changes
231 | - Cache hit/miss rates
232 | - Response times
233 | - Retry counts
234 | 
235 | ## Future Improvements
236 | 
237 | - [ ] Implement request queuing during rate limits
238 | - [ ] Add fallback to cached documentation during outages
239 | - [ ] Implement progressive retry delays based on error type
240 | - [ ] Add webhook notifications for circuit breaker state changes
241 | - [ ] Implement request deduplication
```

--------------------------------------------------------------------------------
/src/flutter_mcp/token_manager.py:
--------------------------------------------------------------------------------

```python
  1 | """Token counting module for Flutter MCP server.
  2 | 
  3 | Provides both approximate and accurate token counting methods with
  4 | configurable behavior via environment variables.
  5 | """
  6 | 
  7 | import os
  8 | import re
  9 | from typing import Optional, Union
 10 | import structlog
 11 | 
 12 | logger = structlog.get_logger(__name__)
 13 | 
 14 | 
 15 | class TokenManager:
 16 |     """Manages token counting with both approximation and accurate methods."""
 17 |     
 18 |     # Average tokens per word based on empirical observations
 19 |     TOKENS_PER_WORD = 1.3
 20 |     
 21 |     # Word splitting pattern
 22 |     WORD_PATTERN = re.compile(r'\b\w+\b')
 23 |     
 24 |     def __init__(self):
 25 |         """Initialize the TokenManager."""
 26 |         self._tiktoken = None
 27 |         self._encoder = None
 28 |         self._accurate_mode = self._get_accurate_mode()
 29 |         
 30 |         logger.info(
 31 |             "TokenManager initialized",
 32 |             accurate_mode=self._accurate_mode
 33 |         )
 34 |     
 35 |     def _get_accurate_mode(self) -> bool:
 36 |         """Check if accurate token counting is enabled via environment variable."""
 37 |         env_value = os.environ.get('FLUTTER_MCP_ACCURATE_TOKENS', 'false').lower()
 38 |         return env_value in ('true', '1', 'yes', 'on')
 39 |     
 40 |     def _ensure_tiktoken(self) -> bool:
 41 |         """Lazy load tiktoken if needed and available.
 42 |         
 43 |         Returns:
 44 |             bool: True if tiktoken is available, False otherwise.
 45 |         """
 46 |         if self._tiktoken is None:
 47 |             try:
 48 |                 import tiktoken
 49 |                 self._tiktoken = tiktoken
 50 |                 # Use cl100k_base encoding (used by GPT-3.5/GPT-4)
 51 |                 self._encoder = tiktoken.get_encoding("cl100k_base")
 52 |                 logger.info("Tiktoken loaded successfully")
 53 |                 return True
 54 |             except ImportError:
 55 |                 logger.warning(
 56 |                     "Tiktoken not available, falling back to approximation",
 57 |                     hint="Install with: pip install tiktoken"
 58 |                 )
 59 |                 return False
 60 |         return True
 61 |     
 62 |     def approximate_tokens(self, text: str) -> int:
 63 |         """Approximate token count using word-based estimation.
 64 |         
 65 |         This method is fast and doesn't require external dependencies.
 66 |         Uses a simple heuristic of 1.3 tokens per word.
 67 |         
 68 |         Args:
 69 |             text: The text to count tokens for.
 70 |             
 71 |         Returns:
 72 |             int: Approximate number of tokens.
 73 |         """
 74 |         if not text:
 75 |             return 0
 76 |         
 77 |         # Count words using regex pattern
 78 |         words = self.WORD_PATTERN.findall(text)
 79 |         word_count = len(words)
 80 |         
 81 |         # Apply multiplier for approximation
 82 |         token_count = int(word_count * self.TOKENS_PER_WORD)
 83 |         
 84 |         logger.debug(
 85 |             "Approximate token count",
 86 |             word_count=word_count,
 87 |             token_count=token_count,
 88 |             text_length=len(text)
 89 |         )
 90 |         
 91 |         return token_count
 92 |     
 93 |     def accurate_tokens(self, text: str) -> Optional[int]:
 94 |         """Count tokens accurately using tiktoken.
 95 |         
 96 |         This method requires the tiktoken library to be installed.
 97 |         It provides exact token counts but is slower than approximation.
 98 |         
 99 |         Args:
100 |             text: The text to count tokens for.
101 |             
102 |         Returns:
103 |             Optional[int]: Exact number of tokens, or None if tiktoken unavailable.
104 |         """
105 |         if not text:
106 |             return 0
107 |         
108 |         if not self._ensure_tiktoken():
109 |             return None
110 |         
111 |         try:
112 |             tokens = self._encoder.encode(text)
113 |             token_count = len(tokens)
114 |             
115 |             logger.debug(
116 |                 "Accurate token count",
117 |                 token_count=token_count,
118 |                 text_length=len(text)
119 |             )
120 |             
121 |             return token_count
122 |         except Exception as e:
123 |             logger.error(
124 |                 "Error counting tokens with tiktoken",
125 |                 error=str(e),
126 |                 text_length=len(text)
127 |             )
128 |             return None
129 |     
130 |     def count_tokens(self, text: str, force_accurate: bool = False) -> int:
131 |         """Count tokens using the configured method.
132 |         
133 |         By default, uses the method configured via FLUTTER_MCP_ACCURATE_TOKENS
134 |         environment variable. Can be overridden with force_accurate parameter.
135 |         
136 |         Args:
137 |             text: The text to count tokens for.
138 |             force_accurate: Force accurate counting regardless of configuration.
139 |             
140 |         Returns:
141 |             int: Number of tokens (approximate or accurate based on configuration).
142 |         """
143 |         if not text:
144 |             return 0
145 |         
146 |         # Determine which method to use
147 |         use_accurate = force_accurate or self._accurate_mode
148 |         
149 |         if use_accurate:
150 |             # Try accurate counting first
151 |             accurate_count = self.accurate_tokens(text)
152 |             if accurate_count is not None:
153 |                 return accurate_count
154 |             
155 |             # Fall back to approximation if accurate counting fails
156 |             logger.info(
157 |                 "Falling back to approximation",
158 |                 reason="Accurate counting failed or unavailable"
159 |             )
160 |         
161 |         # Use approximation
162 |         return self.approximate_tokens(text)
163 |     
164 |     def set_accurate_mode(self, enabled: bool) -> None:
165 |         """Dynamically enable or disable accurate token counting.
166 |         
167 |         Args:
168 |             enabled: Whether to use accurate token counting.
169 |         """
170 |         self._accurate_mode = enabled
171 |         logger.info(
172 |             "Token counting mode changed",
173 |             accurate_mode=enabled
174 |         )
175 |     
176 |     def get_mode(self) -> str:
177 |         """Get the current token counting mode.
178 |         
179 |         Returns:
180 |             str: 'accurate' if using tiktoken, 'approximate' otherwise.
181 |         """
182 |         return 'accurate' if self._accurate_mode else 'approximate'
183 |     
184 |     def estimate_cost(
185 |         self, 
186 |         token_count: int, 
187 |         cost_per_1k_tokens: float = 0.002
188 |     ) -> float:
189 |         """Estimate cost based on token count.
190 |         
191 |         Args:
192 |             token_count: Number of tokens.
193 |             cost_per_1k_tokens: Cost per 1000 tokens (default: $0.002).
194 |             
195 |         Returns:
196 |             float: Estimated cost in dollars.
197 |         """
198 |         return (token_count / 1000) * cost_per_1k_tokens
199 | 
200 | 
201 | # Module-level instance for convenience
202 | _token_manager = TokenManager()
203 | 
204 | # Expose main methods at module level
205 | approximate_tokens = _token_manager.approximate_tokens
206 | accurate_tokens = _token_manager.accurate_tokens
207 | count_tokens = _token_manager.count_tokens
208 | set_accurate_mode = _token_manager.set_accurate_mode
209 | get_mode = _token_manager.get_mode
210 | estimate_cost = _token_manager.estimate_cost
211 | 
212 | 
213 | def get_token_manager() -> TokenManager:
214 |     """Get the singleton TokenManager instance.
215 |     
216 |     Returns:
217 |         TokenManager: The module-level token manager instance.
218 |     """
219 |     return _token_manager
```

--------------------------------------------------------------------------------
/src/flutter_mcp/recovery.py:
--------------------------------------------------------------------------------

```python
  1 | """
  2 | Recovery mechanisms for Flutter MCP Server.
  3 | 
  4 | This module provides automatic recovery and self-healing capabilities
  5 | for the Flutter documentation server.
  6 | """
  7 | 
  8 | import asyncio
  9 | import time
 10 | from typing import Dict, Any, Optional, Callable
 11 | from datetime import datetime, timedelta
 12 | import structlog
 13 | 
 14 | logger = structlog.get_logger()
 15 | 
 16 | 
 17 | class HealthMonitor:
 18 |     """
 19 |     Monitors service health and triggers recovery actions.
 20 |     """
 21 |     
 22 |     def __init__(self, check_interval: float = 300.0):  # 5 minutes
 23 |         self.check_interval = check_interval
 24 |         self.last_check = None
 25 |         self.consecutive_failures = 0
 26 |         self.recovery_actions = []
 27 |         self.is_monitoring = False
 28 |         
 29 |     def add_recovery_action(self, action: Callable, threshold: int = 3):
 30 |         """Add a recovery action to trigger after threshold failures."""
 31 |         self.recovery_actions.append({
 32 |             "action": action,
 33 |             "threshold": threshold,
 34 |             "triggered": False
 35 |         })
 36 |     
 37 |     async def start_monitoring(self, health_check_func: Callable):
 38 |         """Start continuous health monitoring."""
 39 |         self.is_monitoring = True
 40 |         logger.info("health_monitoring_started", interval=self.check_interval)
 41 |         
 42 |         while self.is_monitoring:
 43 |             try:
 44 |                 # Perform health check
 45 |                 result = await health_check_func()
 46 |                 status = result.get("status", "unknown")
 47 |                 
 48 |                 if status in ["failed", "degraded"]:
 49 |                     self.consecutive_failures += 1
 50 |                     logger.warning(
 51 |                         "health_check_failed",
 52 |                         status=status,
 53 |                         consecutive_failures=self.consecutive_failures
 54 |                     )
 55 |                     
 56 |                     # Trigger recovery actions if needed
 57 |                     await self._trigger_recovery_actions()
 58 |                 else:
 59 |                     if self.consecutive_failures > 0:
 60 |                         logger.info("health_recovered", previous_failures=self.consecutive_failures)
 61 |                     self.consecutive_failures = 0
 62 |                     self._reset_recovery_actions()
 63 |                 
 64 |                 self.last_check = datetime.utcnow()
 65 |                 
 66 |             except Exception as e:
 67 |                 logger.error(
 68 |                     "health_monitor_error",
 69 |                     error=str(e),
 70 |                     error_type=type(e).__name__
 71 |                 )
 72 |                 self.consecutive_failures += 1
 73 |             
 74 |             # Wait for next check
 75 |             await asyncio.sleep(self.check_interval)
 76 |     
 77 |     async def _trigger_recovery_actions(self):
 78 |         """Trigger appropriate recovery actions based on failure count."""
 79 |         for action_config in self.recovery_actions:
 80 |             if (self.consecutive_failures >= action_config["threshold"] and 
 81 |                 not action_config["triggered"]):
 82 |                 try:
 83 |                     logger.info(
 84 |                         "triggering_recovery_action",
 85 |                         threshold=action_config["threshold"],
 86 |                         failures=self.consecutive_failures
 87 |                     )
 88 |                     await action_config["action"]()
 89 |                     action_config["triggered"] = True
 90 |                 except Exception as e:
 91 |                     logger.error(
 92 |                         "recovery_action_failed",
 93 |                         error=str(e),
 94 |                         error_type=type(e).__name__
 95 |                     )
 96 |     
 97 |     def _reset_recovery_actions(self):
 98 |         """Reset triggered flags on recovery actions."""
 99 |         for action_config in self.recovery_actions:
100 |             action_config["triggered"] = False
101 |     
102 |     def stop_monitoring(self):
103 |         """Stop health monitoring."""
104 |         self.is_monitoring = False
105 |         logger.info("health_monitoring_stopped")
106 | 
107 | 
108 | class CacheRecovery:
109 |     """
110 |     Handles cache-related recovery operations.
111 |     """
112 |     
113 |     @staticmethod
114 |     async def clear_corrupted_entries(cache_manager):
115 |         """Clear potentially corrupted cache entries."""
116 |         try:
117 |             logger.info("clearing_corrupted_cache_entries")
118 |             # Implementation depends on cache manager interface
119 |             # This is a placeholder for the actual implementation
120 |             stats = cache_manager.get_stats()
121 |             logger.info("cache_recovery_completed", stats=stats)
122 |         except Exception as e:
123 |             logger.error("cache_recovery_failed", error=str(e))
124 | 
125 | 
126 | class ConnectionPoolRecovery:
127 |     """
128 |     Manages HTTP connection pool recovery.
129 |     """
130 |     
131 |     @staticmethod
132 |     async def reset_connection_pools():
133 |         """Reset all HTTP connection pools."""
134 |         logger.info("resetting_connection_pools")
135 |         # Force garbage collection of old connections
136 |         import gc
137 |         gc.collect()
138 |         logger.info("connection_pools_reset")
139 | 
140 | 
141 | class RateLimiterRecovery:
142 |     """
143 |     Handles rate limiter recovery and adjustment.
144 |     """
145 |     
146 |     @staticmethod
147 |     async def adjust_rate_limits(rate_limiter, factor: float = 0.5):
148 |         """Temporarily reduce rate limits during recovery."""
149 |         original_rate = 1.0 / rate_limiter.min_interval
150 |         new_rate = original_rate * factor
151 |         rate_limiter.min_interval = 1.0 / new_rate
152 |         
153 |         logger.info(
154 |             "rate_limits_adjusted",
155 |             original_rate=original_rate,
156 |             new_rate=new_rate,
157 |             factor=factor
158 |         )
159 |         
160 |         # Reset after 5 minutes
161 |         await asyncio.sleep(300)
162 |         rate_limiter.min_interval = 1.0 / original_rate
163 |         logger.info("rate_limits_restored", rate=original_rate)
164 | 
165 | 
166 | async def create_recovery_system(cache_manager, rate_limiter, health_check_func):
167 |     """
168 |     Create and configure the recovery system.
169 |     
170 |     Returns:
171 |         HealthMonitor: Configured health monitor instance
172 |     """
173 |     monitor = HealthMonitor(check_interval=300.0)  # 5 minutes
174 |     
175 |     # Add recovery actions with increasing severity
176 |     
177 |     # Level 1: Clear cache (after 3 failures)
178 |     async def clear_cache():
179 |         await CacheRecovery.clear_corrupted_entries(cache_manager)
180 |     
181 |     monitor.add_recovery_action(clear_cache, threshold=3)
182 |     
183 |     # Level 2: Reset connections (after 5 failures)
184 |     async def reset_connections():
185 |         await ConnectionPoolRecovery.reset_connection_pools()
186 |     
187 |     monitor.add_recovery_action(reset_connections, threshold=5)
188 |     
189 |     # Level 3: Reduce rate limits (after 7 failures)
190 |     async def reduce_rates():
191 |         await RateLimiterRecovery.adjust_rate_limits(rate_limiter, factor=0.5)
192 |     
193 |     monitor.add_recovery_action(reduce_rates, threshold=7)
194 |     
195 |     # Start monitoring in background
196 |     asyncio.create_task(monitor.start_monitoring(health_check_func))
197 |     
198 |     return monitor
199 | 
200 | 
201 | class GracefulShutdown:
202 |     """
203 |     Handles graceful shutdown of the server.
204 |     """
205 |     
206 |     def __init__(self):
207 |         self.shutdown_handlers = []
208 |         self.is_shutting_down = False
209 |     
210 |     def add_handler(self, handler: Callable):
211 |         """Add a shutdown handler."""
212 |         self.shutdown_handlers.append(handler)
213 |     
214 |     async def shutdown(self):
215 |         """Perform graceful shutdown."""
216 |         if self.is_shutting_down:
217 |             return
218 |         
219 |         self.is_shutting_down = True
220 |         logger.info("graceful_shutdown_started")
221 |         
222 |         # Execute all shutdown handlers
223 |         for handler in self.shutdown_handlers:
224 |             try:
225 |                 await handler()
226 |             except Exception as e:
227 |                 logger.error(
228 |                     "shutdown_handler_error",
229 |                     error=str(e),
230 |                     error_type=type(e).__name__
231 |                 )
232 |         
233 |         logger.info("graceful_shutdown_completed")
```

--------------------------------------------------------------------------------
/docs/truncation-algorithm.md:
--------------------------------------------------------------------------------

```markdown
  1 | # Smart Truncation Algorithm for Flutter/Dart Documentation
  2 | 
  3 | ## Overview
  4 | 
  5 | The smart truncation algorithm is designed to intelligently reduce Flutter and Dart documentation to fit within token limits while preserving the most critical information for developers. This algorithm uses a priority-based system to ensure that essential information is retained even under severe token constraints.
  6 | 
  7 | ## Key Features
  8 | 
  9 | ### 1. Priority-Based Content Classification
 10 | 
 11 | The algorithm classifies documentation content into five priority levels:
 12 | 
 13 | - **CRITICAL (1)**: Must always be retained
 14 |   - Class descriptions
 15 |   - Constructor signatures
 16 |   
 17 | - **HIGH (2)**: Retained whenever possible
 18 |   - Primary method signatures (build, createState, initState, dispose)
 19 |   - Common properties (child, children, padding, margin, etc.)
 20 |   - Constructor descriptions
 21 | 
 22 | - **MEDIUM (3)**: Retained if space allows
 23 |   - Secondary methods
 24 |   - Less common properties
 25 |   - First 2 code examples
 26 |   
 27 | - **LOW (4)**: First to be removed
 28 |   - Private methods
 29 |   - Verbose method descriptions
 30 |   - Additional code examples (3+)
 31 |   
 32 | - **MINIMAL (5)**: Removed first
 33 |   - Inherited members
 34 |   - See also sections
 35 |   - Related classes
 36 | 
 37 | ### 2. Intelligent Section Parsing
 38 | 
 39 | The algorithm parses Flutter documentation into semantic sections:
 40 | 
 41 | ```python
 42 | sections = [
 43 |     "description",      # Class overview
 44 |     "constructors",     # Constructor signatures and docs
 45 |     "properties",       # Widget properties
 46 |     "methods",          # Class methods
 47 |     "examples"          # Code examples
 48 | ]
 49 | ```
 50 | 
 51 | Each section is further broken down into sub-components with individual priorities.
 52 | 
 53 | ### 3. Flutter-Aware Prioritization
 54 | 
 55 | The algorithm has built-in knowledge of Flutter's widget hierarchy and common patterns:
 56 | 
 57 | #### High-Priority Widgets
 58 | ```python
 59 | HIGH_PRIORITY_WIDGETS = {
 60 |     "Container", "Row", "Column", "Text", "Image", "Scaffold",
 61 |     "AppBar", "ListView", "GridView", "Stack", "Positioned",
 62 |     "Center", "Padding", "SizedBox", "Expanded", "Flexible",
 63 |     # ... and more
 64 | }
 65 | ```
 66 | 
 67 | #### High-Priority Methods
 68 | ```python
 69 | HIGH_PRIORITY_METHODS = {
 70 |     "build", "createState", "initState", "dispose", "setState",
 71 |     "didChangeDependencies", "didUpdateWidget", "deactivate"
 72 | }
 73 | ```
 74 | 
 75 | #### High-Priority Properties
 76 | ```python
 77 | HIGH_PRIORITY_PROPERTIES = {
 78 |     "child", "children", "width", "height", "color", "padding",
 79 |     "margin", "alignment", "decoration", "style", "onPressed",
 80 |     "onTap", "controller", "value", "enabled", "visible"
 81 | }
 82 | ```
 83 | 
 84 | ### 4. Truncation Strategies
 85 | 
 86 | The algorithm supports multiple truncation strategies:
 87 | 
 88 | #### Balanced (Default)
 89 | Maintains a good mix of all documentation types:
 90 | - Keeps description, main constructors, key properties, and primary methods
 91 | - Includes 1-2 code examples if space allows
 92 | - Best for general-purpose documentation
 93 | 
 94 | #### Signatures
 95 | Prioritizes method and constructor signatures:
 96 | - Maximizes retention of code signatures
 97 | - Reduces or removes descriptions
 98 | - Ideal when the user needs API reference information
 99 | 
100 | #### Examples
101 | Prioritizes code examples:
102 | - Keeps more code examples than other strategies
103 | - Useful for learning and implementation guidance
104 | 
105 | #### Minimal
106 | Keeps only the most essential information:
107 | - Class description
108 | - Primary constructor
109 | - build() method for widgets
110 | - child/children properties
111 | 
112 | ### 5. Smart Code Truncation
113 | 
114 | When truncating code blocks, the algorithm:
115 | - Preserves syntactic validity when possible
116 | - Balances braces and brackets
117 | - Truncates at line boundaries
118 | - Adds ellipsis comments to indicate truncation
119 | 
120 | Example:
121 | ```dart
122 | Container(
123 |   width: 200,
124 |   height: 200,
125 |   child: Column(
126 |     children: [
127 |       Text('Line 1'),
128 |       // ...
129 |     ],
130 |   ),
131 | )
132 | ```
133 | 
134 | ### 6. Progressive Truncation
135 | 
136 | The algorithm applies truncation progressively:
137 | 
138 | 1. Calculate total token count
139 | 2. If under limit, return unchanged
140 | 3. Remove MINIMAL priority content
141 | 4. Remove LOW priority content
142 | 5. Reduce MEDIUM priority content
143 | 6. Trim HIGH priority content (descriptions only)
144 | 7. CRITICAL content is never removed
145 | 
146 | ## Usage Examples
147 | 
148 | ### Basic Usage
149 | 
150 | ```python
151 | from flutter_mcp.truncation import truncate_flutter_docs
152 | 
153 | # Truncate to 4000 tokens with balanced strategy
154 | truncated_doc = truncate_flutter_docs(
155 |     content=original_documentation,
156 |     class_name="Container",
157 |     max_tokens=4000,
158 |     strategy="balanced"
159 | )
160 | ```
161 | 
162 | ### Advanced Usage with Metadata
163 | 
164 | ```python
165 | from flutter_mcp.truncation import AdaptiveTruncator
166 | 
167 | truncator = AdaptiveTruncator(max_tokens=2000)
168 | truncated_doc, metadata = truncator.truncate_with_strategy(
169 |     doc_content=original_documentation,
170 |     class_name="ListView",
171 |     library="widgets",
172 |     strategy="signatures"
173 | )
174 | 
175 | print(f"Compression ratio: {metadata['compression_ratio']:.1%}")
176 | print(f"Was truncated: {metadata['was_truncated']}")
177 | ```
178 | 
179 | ### Integration with MCP Server
180 | 
181 | ```python
182 | # In the MCP tool
183 | @mcp.tool()
184 | async def get_flutter_docs(
185 |     class_name: str, 
186 |     library: str = "widgets",
187 |     max_tokens: int = None  # Optional truncation
188 | ) -> Dict[str, Any]:
189 |     # Fetch documentation...
190 |     
191 |     # Apply smart truncation if requested
192 |     if max_tokens:
193 |         content = truncate_flutter_docs(
194 |             content,
195 |             class_name,
196 |             max_tokens=max_tokens,
197 |             strategy="balanced"
198 |         )
199 | ```
200 | 
201 | ## Token Limits and Recommendations
202 | 
203 | | Use Case | Recommended Token Limit | Strategy |
204 | |----------|------------------------|----------|
205 | | Quick reference | 500-1000 | minimal |
206 | | API overview | 2000-4000 | signatures |
207 | | Learning/Tutorial | 4000-8000 | examples |
208 | | Full documentation | 8000+ | balanced |
209 | 
210 | ## Implementation Details
211 | 
212 | ### Token Estimation
213 | 
214 | The algorithm uses a simple but effective token estimation:
215 | - English text: ~4 characters per token
216 | - Code: ~3 characters per token
217 | 
218 | This provides a good approximation for planning truncation without requiring actual tokenization.
219 | 
220 | ### Section Preservation
221 | 
222 | When a section must be truncated:
223 | 1. Code sections are truncated at line boundaries
224 | 2. Text sections are truncated at sentence boundaries
225 | 3. Lists are truncated at item boundaries
226 | 4. A truncation notice is always added
227 | 
228 | ### Example Output
229 | 
230 | Original documentation: 15,000 characters (~3,750 tokens)
231 | Truncated to 1,000 tokens:
232 | 
233 | ```markdown
234 | # Container (Truncated Documentation)
235 | 
236 | ## Description
237 | A convenience widget that combines common painting, positioning, and sizing widgets.
238 | 
239 | ## Constructors
240 | ### Container({Key? key, AlignmentGeometry? alignment, ...})
241 | ```dart
242 | Container({
243 |   Key? key,
244 |   this.alignment,
245 |   this.padding,
246 |   this.color,
247 |   this.decoration,
248 |   double? width,
249 |   double? height,
250 |   this.child,
251 | })
252 | ```
253 | 
254 | ## Properties
255 | - **child**: The child contained by the container
256 | - **padding**: Empty space to inscribe inside the decoration
257 | - **color**: The color to paint behind the child
258 | - **width**: Container width constraint
259 | - **height**: Container height constraint
260 | 
261 | ## Methods
262 | ### build(BuildContext context)
263 | ```dart
264 | @override
265 | Widget build(BuildContext context) {
266 |   // ... (truncated)
267 | }
268 | ```
269 | 
270 | ---
271 | *Note: This documentation has been intelligently truncated to fit within token limits. Some sections may have been removed or shortened.*
272 | ```
273 | 
274 | ## Performance Considerations
275 | 
276 | The truncation algorithm is designed to be efficient:
277 | - O(n) parsing of documentation
278 | - O(n log n) sorting of sections by priority
279 | - O(n) reconstruction of truncated documentation
280 | 
281 | Typical truncation takes <50ms for large documents.
282 | 
283 | ## Future Enhancements
284 | 
285 | Potential improvements to the algorithm:
286 | 
287 | 1. **ML-based importance scoring**: Use machine learning to determine section importance based on usage patterns
288 | 2. **Context-aware truncation**: Adjust priorities based on the user's query context
289 | 3. **Cross-reference preservation**: Maintain links between related classes when truncating
290 | 4. **Incremental loading**: Support progressive disclosure of truncated content
291 | 5. **Custom priority profiles**: Allow users to define their own priority preferences
292 | 
293 | ## Conclusion
294 | 
295 | The smart truncation algorithm ensures that Flutter/Dart documentation remains useful even under severe token constraints. By understanding the structure and importance of different documentation sections, it preserves the most critical information while gracefully degrading less essential content.
```
Page 1/3FirstPrevNextLast