ai-doc-creator 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. ai_doc_creator-2.2.0/LICENSE +21 -0
  2. ai_doc_creator-2.2.0/PKG-INFO +211 -0
  3. ai_doc_creator-2.2.0/README.md +163 -0
  4. ai_doc_creator-2.2.0/ai_doc_creator/__init__.py +3 -0
  5. ai_doc_creator-2.2.0/ai_doc_creator/cli.py +100 -0
  6. ai_doc_creator-2.2.0/ai_doc_creator/core/__init__.py +1 -0
  7. ai_doc_creator-2.2.0/ai_doc_creator/core/backends.py +126 -0
  8. ai_doc_creator-2.2.0/ai_doc_creator/core/cache.py +71 -0
  9. ai_doc_creator-2.2.0/ai_doc_creator/core/config.py +92 -0
  10. ai_doc_creator-2.2.0/ai_doc_creator/core/diagrams.py +212 -0
  11. ai_doc_creator-2.2.0/ai_doc_creator/core/doc_writer.py +43 -0
  12. ai_doc_creator-2.2.0/ai_doc_creator/core/file_traverser.py +76 -0
  13. ai_doc_creator-2.2.0/ai_doc_creator/core/graph.py +157 -0
  14. ai_doc_creator-2.2.0/ai_doc_creator/core/guards.py +104 -0
  15. ai_doc_creator-2.2.0/ai_doc_creator/core/logging_config.py +49 -0
  16. ai_doc_creator-2.2.0/ai_doc_creator/core/profiles.py +91 -0
  17. ai_doc_creator-2.2.0/ai_doc_creator/core/ratelimit.py +106 -0
  18. ai_doc_creator-2.2.0/ai_doc_creator/core/retry.py +53 -0
  19. ai_doc_creator-2.2.0/ai_doc_creator/core/sources.py +104 -0
  20. ai_doc_creator-2.2.0/ai_doc_creator/server.py +629 -0
  21. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/PKG-INFO +211 -0
  22. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/SOURCES.txt +41 -0
  23. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/dependency_links.txt +1 -0
  24. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/entry_points.txt +3 -0
  25. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/requires.txt +27 -0
  26. ai_doc_creator-2.2.0/ai_doc_creator.egg-info/top_level.txt +1 -0
  27. ai_doc_creator-2.2.0/pyproject.toml +68 -0
  28. ai_doc_creator-2.2.0/setup.cfg +4 -0
  29. ai_doc_creator-2.2.0/tests/test_backends.py +212 -0
  30. ai_doc_creator-2.2.0/tests/test_cache.py +72 -0
  31. ai_doc_creator-2.2.0/tests/test_config.py +93 -0
  32. ai_doc_creator-2.2.0/tests/test_diagrams.py +144 -0
  33. ai_doc_creator-2.2.0/tests/test_graph.py +110 -0
  34. ai_doc_creator-2.2.0/tests/test_guards.py +127 -0
  35. ai_doc_creator-2.2.0/tests/test_logging_config.py +46 -0
  36. ai_doc_creator-2.2.0/tests/test_mcp_tools.py +312 -0
  37. ai_doc_creator-2.2.0/tests/test_phase4_server.py +292 -0
  38. ai_doc_creator-2.2.0/tests/test_phase5_integration.py +87 -0
  39. ai_doc_creator-2.2.0/tests/test_pr_push.py +130 -0
  40. ai_doc_creator-2.2.0/tests/test_profiles.py +63 -0
  41. ai_doc_creator-2.2.0/tests/test_ratelimit.py +110 -0
  42. ai_doc_creator-2.2.0/tests/test_retry.py +61 -0
  43. ai_doc_creator-2.2.0/tests/test_sources.py +112 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Dharmik Raval
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,211 @@
1
+ Metadata-Version: 2.4
2
+ Name: ai-doc-creator
3
+ Version: 2.2.0
4
+ Summary: AI-powered documentation generator for repos and local projects — MCP server + CLI, any LLM provider or keyless via MCP host sampling.
5
+ Author: Dharmik Raval
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/dharmikraval1/ai-document-creator
8
+ Project-URL: Repository, https://github.com/dharmikraval1/ai-document-creator
9
+ Project-URL: Issues, https://github.com/dharmikraval1/ai-document-creator/issues
10
+ Keywords: mcp,documentation,ai,llm,docs-generator,model-context-protocol
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Topic :: Documentation
17
+ Classifier: Topic :: Software Development :: Documentation
18
+ Requires-Python: >=3.11
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: mcp>=1.10
22
+ Requires-Dist: langchain>=0.3
23
+ Requires-Dist: langchain-core>=0.3
24
+ Requires-Dist: langchain-community>=0.3
25
+ Requires-Dist: langchain-openai>=0.3
26
+ Requires-Dist: langchain-anthropic>=0.3
27
+ Requires-Dist: langchain-aws>=0.2
28
+ Requires-Dist: langchain-ollama>=0.2
29
+ Requires-Dist: langgraph>=0.3
30
+ Requires-Dist: openai>=1.60
31
+ Requires-Dist: boto3>=1.35
32
+ Requires-Dist: gitpython>=3.1
33
+ Requires-Dist: PyGithub>=2.5
34
+ Requires-Dist: python-dotenv>=1.0
35
+ Requires-Dist: pydantic>=2.9
36
+ Requires-Dist: tenacity>=8.5
37
+ Requires-Dist: tiktoken>=0.8
38
+ Requires-Dist: typing-extensions>=4.12
39
+ Requires-Dist: uvicorn>=0.30
40
+ Provides-Extra: dev
41
+ Requires-Dist: pytest; extra == "dev"
42
+ Requires-Dist: pytest-asyncio; extra == "dev"
43
+ Requires-Dist: flake8; extra == "dev"
44
+ Requires-Dist: black; extra == "dev"
45
+ Requires-Dist: isort; extra == "dev"
46
+ Requires-Dist: mypy; extra == "dev"
47
+ Dynamic: license-file
48
+
49
+ # AI Document Creator
50
+
51
+ [![CI](https://github.com/dharmikraval1/ai-document-creator/actions/workflows/ci.yml/badge.svg)](https://github.com/dharmikraval1/ai-document-creator/actions/workflows/ci.yml)
52
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
53
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](pyproject.toml)
54
+
55
+ AI-powered documentation generator, exposed as an **MCP server** and a **CLI**. Point it at a **GitHub repository** or a **local project** and it writes per-file docs plus a synthesized `README.md` — using **any LLM** (Anthropic, OpenAI, Azure OpenAI, AWS Bedrock, Ollama) with your key, or **your MCP host's own model via sampling with no key at all**.
56
+
57
+ 📖 **New here? The step-by-step guide for every setup is in [USAGE.md](USAGE.md).**
58
+
59
+ ## Use it in 60 seconds
60
+
61
+ ### Option A — run it locally in your MCP host (recommended)
62
+
63
+ With [uv](https://docs.astral.sh/uv/) installed, no clone, no venv:
64
+
65
+ ```bash
66
+ # Claude Code
67
+ claude mcp add ai-doc-creator -- uvx --from ai-doc-creator ai-doc-creator-mcp
68
+ ```
69
+
70
+ Claude Desktop / Cursor / any MCP host (`mcpServers` JSON):
71
+
72
+ ```json
73
+ {
74
+ "mcpServers": {
75
+ "ai-doc-creator": {
76
+ "command": "uvx",
77
+ "args": ["--from", "ai-doc-creator", "ai-doc-creator-mcp"],
78
+ "env": { "ANTHROPIC_API_KEY": "sk-..." }
79
+ }
80
+ }
81
+ }
82
+ ```
83
+
84
+ The `env` block is optional — leave it out and the server uses your MCP host's model via sampling (zero API cost).
85
+
86
+ > Until the package is on PyPI you can substitute
87
+ > `uvx --from git+https://github.com/dharmikraval1/ai-document-creator ai-doc-creator-mcp`.
88
+
89
+ ### Option B — use a hosted endpoint (nothing to install)
90
+
91
+ Point your MCP host at a deployment's Streamable HTTP endpoint and bring your own key in headers:
92
+
93
+ ```json
94
+ {
95
+ "mcpServers": {
96
+ "ai-doc-creator": {
97
+ "type": "http",
98
+ "url": "https://<your-deployment-host>/mcp",
99
+ "headers": {
100
+ "X-Provider-API-Key": "sk-...",
101
+ "X-Provider": "anthropic"
102
+ }
103
+ }
104
+ }
105
+ }
106
+ ```
107
+
108
+ Keys travel in **headers**, never in tool arguments, so they stay out of chat transcripts and logs. Legacy clients can still connect via `https://<host>/sse`.
109
+
110
+ ### Option C — GitHub Action (docs that update themselves)
111
+
112
+ ```yaml
113
+ - uses: dharmikraval1/ai-document-creator@v2
114
+ env:
115
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
116
+ ```
117
+
118
+ Regenerates your repo's docs on every push — full workflow example in [USAGE.md](USAGE.md#5-github-action--docs-that-update-themselves).
119
+
120
+ ### Option D — CLI
121
+
122
+ ```bash
123
+ pip install ai-doc-creator # or: pip install git+https://github.com/dharmikraval1/ai-document-creator
124
+ ai-doc-creator --repo https://github.com/user/repo --output docs
125
+ ai-doc-creator --path . --provider ollama --model llama3.1
126
+ ```
127
+
128
+ The CLI needs a provider key (there is no MCP host to sample from).
129
+
130
+ ## MCP tools
131
+
132
+ | Tool | What it does |
133
+ |---|---|
134
+ | `document_repo(repo_url, ...)` | Clone a GitHub repo and document it. `push_as_pr=True` opens a PR with the docs; `return_docs=True` inlines the generated markdown in the response (capped by `MAX_INLINE_DOC_KB`). |
135
+ | `document_local_project(path, ...)` | Document a folder on the machine the server runs on. Disabled on hosted deployments unless the operator sets `LOCAL_ROOT`. |
136
+ | `check_doc_drift(path, output_dir)` | Report new/modified/deleted files since the last documentation run (no LLM calls). |
137
+
138
+ All documentation runs are **incremental** by default: a content-hash manifest skips unchanged files, so re-runs only pay for what changed.
139
+
140
+ ### Diagrams & output profiles
141
+
142
+ Every generated README ends with **Mermaid architecture diagrams** — a project-structure chart and a module-dependency graph computed by static analysis (Python + JS/TS imports), so they're always syntactically valid. Complex files also get model-drawn flow charts, and every model-drawn diagram is validated before shipping (invalid ones are downgraded to plain text, never broken pages). Disable with `diagrams=false` / `--no-diagrams`.
143
+
144
+ Pick a documentation style with `profile` (`--profile` on the CLI):
145
+
146
+ | Profile | Focus |
147
+ |---|---|
148
+ | `readme` (default) | Classic README: overview, install, usage |
149
+ | `api` | API reference: signatures, params, returns, errors |
150
+ | `architecture` | Components, data flow, design decisions + diagrams |
151
+ | `tutorial` | Guided walkthrough for newcomers |
152
+
153
+ ## How it works
154
+
155
+ Two independent choices over one async pipeline:
156
+
157
+ - **Source** — `GitSource` (clone a URL) or `LocalSource` (read a path).
158
+ - **Backend** — `ProviderBackend` (any provider, via env key or per-request header key) or `SamplingBackend` (the MCP host's model). `pick_backend` chooses: an explicit key wins; otherwise a configured provider; otherwise host sampling; otherwise a clear error.
159
+
160
+ The pipeline traverses files, generates per-file docs concurrently (bounded by a semaphore), then synthesizes a top-level `README.md`.
161
+
162
+ ## LLM providers
163
+
164
+ | Provider | Configure via |
165
+ |---|---|
166
+ | Anthropic | `ANTHROPIC_API_KEY` env, or `X-Provider-API-Key` header |
167
+ | OpenAI | `OPENAI_API_KEY` env, or header |
168
+ | Azure OpenAI | `AZURE_OPENAI_API_KEY` + endpoint/deployment (see `.env.example`), or header |
169
+ | AWS Bedrock | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (env only) |
170
+ | Ollama (local) | `provider="ollama"` (no key) |
171
+ | None | MCP host sampling — the host's model writes the docs |
172
+
173
+ ## Hosting your own public endpoint
174
+
175
+ [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/dharmikraval1/ai-document-creator)
176
+
177
+ One click via the included [`render.yaml`](render.yaml) blueprint — it enables auto-deploy on every push to `main`, health checks, and safe public defaults (`BYOK_ONLY=true`, rate limiting on, Render hostname auto-allowed).
178
+
179
+ The `Dockerfile` also runs anywhere that supplies a `PORT` (Fly.io, Railway, ...). The server serves Streamable HTTP at `/mcp`, legacy SSE at `/sse`, and a health probe at `/health`.
180
+
181
+ Recommended env for a public deployment:
182
+
183
+ | Variable | Value | Why |
184
+ |---|---|---|
185
+ | `MCP_ALLOWED_HOSTS` | your public hostname (e.g. `your-app.onrender.com`) | DNS-rebinding protection rejects unknown Host headers |
186
+ | `BYOK_ONLY` | `true` | never spend *your* keys on strangers — users bring keys in headers or use sampling |
187
+ | `RATE_LIMIT_RPM` | `20` (default) | per-client request cap; `0` disables |
188
+ | `LOG_FORMAT` | `json` | structured logs |
189
+ | `MCP_TRANSPORT` | `both` (default) / `streamable-http` / `sse` | which HTTP transports to serve |
190
+
191
+ ## Security model
192
+
193
+ - **Keys**: header-only intake for remote users; passed explicitly to the provider client; never written to env, logs, or `repr()`; `BYOK_ONLY=true` guarantees the server's own keys are never used for requests.
194
+ - **SSRF**: repo URLs must be HTTPS and must not resolve to private/reserved address space; DNS-rebinding protection on the HTTP transports.
195
+ - **Filesystem**: hosted deployments refuse local-filesystem tools (unless `LOCAL_ROOT` opts in) and write repo docs to per-request temp dirs — callers can't read or write server paths.
196
+ - **Abuse limits**: per-client rate limit, bounded pipeline concurrency, pipeline timeout, repo-size cap, per-file-size cap.
197
+
198
+ ## Development
199
+
200
+ ```bash
201
+ python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
202
+ pip install -e ".[dev]"
203
+ pytest -q # 157 tests
204
+ flake8 && mypy ai_doc_creator --ignore-missing-imports
205
+ ```
206
+
207
+ Design specs, implementation plans, and phase status live in [planning/](planning/).
208
+
209
+ ## License
210
+
211
+ [MIT](LICENSE)
@@ -0,0 +1,163 @@
1
+ # AI Document Creator
2
+
3
+ [![CI](https://github.com/dharmikraval1/ai-document-creator/actions/workflows/ci.yml/badge.svg)](https://github.com/dharmikraval1/ai-document-creator/actions/workflows/ci.yml)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
5
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue)](pyproject.toml)
6
+
7
+ AI-powered documentation generator, exposed as an **MCP server** and a **CLI**. Point it at a **GitHub repository** or a **local project** and it writes per-file docs plus a synthesized `README.md` — using **any LLM** (Anthropic, OpenAI, Azure OpenAI, AWS Bedrock, Ollama) with your key, or **your MCP host's own model via sampling with no key at all**.
8
+
9
+ 📖 **New here? The step-by-step guide for every setup is in [USAGE.md](USAGE.md).**
10
+
11
+ ## Use it in 60 seconds
12
+
13
+ ### Option A — run it locally in your MCP host (recommended)
14
+
15
+ With [uv](https://docs.astral.sh/uv/) installed, no clone, no venv:
16
+
17
+ ```bash
18
+ # Claude Code
19
+ claude mcp add ai-doc-creator -- uvx --from ai-doc-creator ai-doc-creator-mcp
20
+ ```
21
+
22
+ Claude Desktop / Cursor / any MCP host (`mcpServers` JSON):
23
+
24
+ ```json
25
+ {
26
+ "mcpServers": {
27
+ "ai-doc-creator": {
28
+ "command": "uvx",
29
+ "args": ["--from", "ai-doc-creator", "ai-doc-creator-mcp"],
30
+ "env": { "ANTHROPIC_API_KEY": "sk-..." }
31
+ }
32
+ }
33
+ }
34
+ ```
35
+
36
+ The `env` block is optional — leave it out and the server uses your MCP host's model via sampling (zero API cost).
37
+
38
+ > Until the package is on PyPI you can substitute
39
+ > `uvx --from git+https://github.com/dharmikraval1/ai-document-creator ai-doc-creator-mcp`.
40
+
41
+ ### Option B — use a hosted endpoint (nothing to install)
42
+
43
+ Point your MCP host at a deployment's Streamable HTTP endpoint and bring your own key in headers:
44
+
45
+ ```json
46
+ {
47
+ "mcpServers": {
48
+ "ai-doc-creator": {
49
+ "type": "http",
50
+ "url": "https://<your-deployment-host>/mcp",
51
+ "headers": {
52
+ "X-Provider-API-Key": "sk-...",
53
+ "X-Provider": "anthropic"
54
+ }
55
+ }
56
+ }
57
+ }
58
+ ```
59
+
60
+ Keys travel in **headers**, never in tool arguments, so they stay out of chat transcripts and logs. Legacy clients can still connect via `https://<host>/sse`.
61
+
62
+ ### Option C — GitHub Action (docs that update themselves)
63
+
64
+ ```yaml
65
+ - uses: dharmikraval1/ai-document-creator@v2
66
+ env:
67
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
68
+ ```
69
+
70
+ Regenerates your repo's docs on every push — full workflow example in [USAGE.md](USAGE.md#5-github-action--docs-that-update-themselves).
71
+
72
+ ### Option D — CLI
73
+
74
+ ```bash
75
+ pip install ai-doc-creator # or: pip install git+https://github.com/dharmikraval1/ai-document-creator
76
+ ai-doc-creator --repo https://github.com/user/repo --output docs
77
+ ai-doc-creator --path . --provider ollama --model llama3.1
78
+ ```
79
+
80
+ The CLI needs a provider key (there is no MCP host to sample from).
81
+
82
+ ## MCP tools
83
+
84
+ | Tool | What it does |
85
+ |---|---|
86
+ | `document_repo(repo_url, ...)` | Clone a GitHub repo and document it. `push_as_pr=True` opens a PR with the docs; `return_docs=True` inlines the generated markdown in the response (capped by `MAX_INLINE_DOC_KB`). |
87
+ | `document_local_project(path, ...)` | Document a folder on the machine the server runs on. Disabled on hosted deployments unless the operator sets `LOCAL_ROOT`. |
88
+ | `check_doc_drift(path, output_dir)` | Report new/modified/deleted files since the last documentation run (no LLM calls). |
89
+
90
+ All documentation runs are **incremental** by default: a content-hash manifest skips unchanged files, so re-runs only pay for what changed.
91
+
92
+ ### Diagrams & output profiles
93
+
94
+ Every generated README ends with **Mermaid architecture diagrams** — a project-structure chart and a module-dependency graph computed by static analysis (Python + JS/TS imports), so they're always syntactically valid. Complex files also get model-drawn flow charts, and every model-drawn diagram is validated before shipping (invalid ones are downgraded to plain text, never broken pages). Disable with `diagrams=false` / `--no-diagrams`.
95
+
96
+ Pick a documentation style with `profile` (`--profile` on the CLI):
97
+
98
+ | Profile | Focus |
99
+ |---|---|
100
+ | `readme` (default) | Classic README: overview, install, usage |
101
+ | `api` | API reference: signatures, params, returns, errors |
102
+ | `architecture` | Components, data flow, design decisions + diagrams |
103
+ | `tutorial` | Guided walkthrough for newcomers |
104
+
105
+ ## How it works
106
+
107
+ Two independent choices over one async pipeline:
108
+
109
+ - **Source** — `GitSource` (clone a URL) or `LocalSource` (read a path).
110
+ - **Backend** — `ProviderBackend` (any provider, via env key or per-request header key) or `SamplingBackend` (the MCP host's model). `pick_backend` chooses: an explicit key wins; otherwise a configured provider; otherwise host sampling; otherwise a clear error.
111
+
112
+ The pipeline traverses files, generates per-file docs concurrently (bounded by a semaphore), then synthesizes a top-level `README.md`.
113
+
114
+ ## LLM providers
115
+
116
+ | Provider | Configure via |
117
+ |---|---|
118
+ | Anthropic | `ANTHROPIC_API_KEY` env, or `X-Provider-API-Key` header |
119
+ | OpenAI | `OPENAI_API_KEY` env, or header |
120
+ | Azure OpenAI | `AZURE_OPENAI_API_KEY` + endpoint/deployment (see `.env.example`), or header |
121
+ | AWS Bedrock | `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (env only) |
122
+ | Ollama (local) | `provider="ollama"` (no key) |
123
+ | None | MCP host sampling — the host's model writes the docs |
124
+
125
+ ## Hosting your own public endpoint
126
+
127
+ [![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/dharmikraval1/ai-document-creator)
128
+
129
+ One click via the included [`render.yaml`](render.yaml) blueprint — it enables auto-deploy on every push to `main`, health checks, and safe public defaults (`BYOK_ONLY=true`, rate limiting on, Render hostname auto-allowed).
130
+
131
+ The `Dockerfile` also runs anywhere that supplies a `PORT` (Fly.io, Railway, ...). The server serves Streamable HTTP at `/mcp`, legacy SSE at `/sse`, and a health probe at `/health`.
132
+
133
+ Recommended env for a public deployment:
134
+
135
+ | Variable | Value | Why |
136
+ |---|---|---|
137
+ | `MCP_ALLOWED_HOSTS` | your public hostname (e.g. `your-app.onrender.com`) | DNS-rebinding protection rejects unknown Host headers |
138
+ | `BYOK_ONLY` | `true` | never spend *your* keys on strangers — users bring keys in headers or use sampling |
139
+ | `RATE_LIMIT_RPM` | `20` (default) | per-client request cap; `0` disables |
140
+ | `LOG_FORMAT` | `json` | structured logs |
141
+ | `MCP_TRANSPORT` | `both` (default) / `streamable-http` / `sse` | which HTTP transports to serve |
142
+
143
+ ## Security model
144
+
145
+ - **Keys**: header-only intake for remote users; passed explicitly to the provider client; never written to env, logs, or `repr()`; `BYOK_ONLY=true` guarantees the server's own keys are never used for requests.
146
+ - **SSRF**: repo URLs must be HTTPS and must not resolve to private/reserved address space; DNS-rebinding protection on the HTTP transports.
147
+ - **Filesystem**: hosted deployments refuse local-filesystem tools (unless `LOCAL_ROOT` opts in) and write repo docs to per-request temp dirs — callers can't read or write server paths.
148
+ - **Abuse limits**: per-client rate limit, bounded pipeline concurrency, pipeline timeout, repo-size cap, per-file-size cap.
149
+
150
+ ## Development
151
+
152
+ ```bash
153
+ python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
154
+ pip install -e ".[dev]"
155
+ pytest -q # 157 tests
156
+ flake8 && mypy ai_doc_creator --ignore-missing-imports
157
+ ```
158
+
159
+ Design specs, implementation plans, and phase status live in [planning/](planning/).
160
+
161
+ ## License
162
+
163
+ [MIT](LICENSE)
@@ -0,0 +1,3 @@
1
+ """AI Document Creator — AI-powered documentation generator (MCP server + CLI)."""
2
+
3
+ __version__ = "2.2.0"
@@ -0,0 +1,100 @@
1
+ # ai_doc_creator/cli.py
2
+ import argparse
3
+ import asyncio
4
+ import logging
5
+ import sys
6
+
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
10
+
11
+ from .core.config import resolve_config # noqa: E402
12
+ from .core.backends import pick_backend, BackendError # noqa: E402
13
+ from .core.sources import GitSource, LocalSource # noqa: E402
14
+ from .core.file_traverser import FileTraverser # noqa: E402
15
+ from .core.graph import app # noqa: E402
16
+ from .core.doc_writer import DocumentationWriter # noqa: E402
17
+
18
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ async def run(source, output_dir, config):
23
+ repo_path = None
24
+ try:
25
+ repo_path = source.prepare()
26
+ files = list(FileTraverser(repo_path, max_file_size_kb=config.max_file_size_kb).traverse())
27
+ logger.info("Found %d files to process.", len(files))
28
+ if not files:
29
+ logger.warning("No files found to document. Exiting.")
30
+ return
31
+
32
+ backend = pick_backend(config, ctx=None) # CLI has no host -> requires a provider key
33
+ final_state = await app.ainvoke(
34
+ {
35
+ "repo_path": repo_path,
36
+ "files": files,
37
+ "documents": {},
38
+ "index_content": "",
39
+ "backend": backend,
40
+ "max_concurrency": config.max_concurrency,
41
+ "profile": config.profile,
42
+ "diagrams": config.diagrams,
43
+ }
44
+ )
45
+
46
+ DocumentationWriter(output_dir).write_docs(
47
+ final_state["documents"], final_state["index_content"]
48
+ )
49
+ logger.info("Documentation generation complete!")
50
+ finally:
51
+ if source:
52
+ source.cleanup()
53
+
54
+
55
+ def main():
56
+ parser = argparse.ArgumentParser(description="AI Document Creator")
57
+ group = parser.add_mutually_exclusive_group(required=True)
58
+ group.add_argument("--repo", help="GitHub repository URL")
59
+ group.add_argument("--path", help="Local project directory")
60
+ parser.add_argument("--output", default="docs", help="Output directory")
61
+ parser.add_argument(
62
+ "--provider", default=None, help="LLM provider (anthropic/openai/azure/bedrock/ollama)"
63
+ )
64
+ parser.add_argument("--model", default=None, help="Model name override")
65
+ parser.add_argument(
66
+ "--profile",
67
+ default="readme",
68
+ choices=["readme", "api", "architecture", "tutorial"],
69
+ help="Documentation style (default: readme)",
70
+ )
71
+ parser.add_argument(
72
+ "--no-diagrams",
73
+ action="store_true",
74
+ help="Disable Mermaid architecture diagrams and flow charts",
75
+ )
76
+ args = parser.parse_args()
77
+
78
+ config = resolve_config(
79
+ provider=args.provider,
80
+ model=args.model,
81
+ profile=args.profile,
82
+ diagrams=not args.no_diagrams,
83
+ )
84
+ source = GitSource(args.repo) if args.repo else LocalSource(args.path)
85
+
86
+ try:
87
+ asyncio.run(run(source, args.output, config))
88
+ except BackendError as exc:
89
+ logger.error("%s", exc)
90
+ sys.exit(1)
91
+ except Exception as exc:
92
+ logger.error("An error occurred: %s", exc)
93
+ import traceback
94
+
95
+ traceback.print_exc()
96
+ sys.exit(1)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
@@ -0,0 +1 @@
1
+ """Core pipeline: config, backends, sources, guards, graph, cache, writer."""
@@ -0,0 +1,126 @@
1
+ # core/backends.py
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from abc import ABC, abstractmethod
6
+
7
+ from langchain.chat_models import init_chat_model # imported at top so tests can monkeypatch it
8
+
9
+ from .config import DocConfig
10
+
11
+
12
+ class BackendError(RuntimeError):
13
+ """Raised when no usable LLM backend can be constructed."""
14
+
15
+
16
+ def _content_to_text(content) -> str:
17
+ """Flatten a chat model response (str, or list of content blocks) to plain text."""
18
+ if isinstance(content, str):
19
+ return content
20
+ if isinstance(content, list):
21
+ parts: list[str] = []
22
+ for block in content:
23
+ if isinstance(block, str):
24
+ parts.append(block)
25
+ elif isinstance(block, dict) and block.get("type") == "text":
26
+ parts.append(block.get("text", ""))
27
+ return "".join(parts)
28
+ return str(content)
29
+
30
+
31
+ class CompletionBackend(ABC):
32
+ """Generates text from a prompt. The only thing the pipeline knows about an LLM."""
33
+
34
+ @abstractmethod
35
+ async def complete(self, prompt: str) -> str: ...
36
+
37
+
38
+ class FakeBackend(CompletionBackend):
39
+ """Deterministic backend for tests — never calls a real model."""
40
+
41
+ def __init__(self, response: str = "FAKE DOC"):
42
+ self.response = response
43
+ self.calls: list[str] = []
44
+
45
+ async def complete(self, prompt: str) -> str:
46
+ self.calls.append(prompt)
47
+ return self.response
48
+
49
+
50
+ class ProviderBackend(CompletionBackend):
51
+ """Calls a real provider (anthropic/openai/azure/bedrock/ollama) via LangChain."""
52
+
53
+ def __init__(self, config: DocConfig):
54
+ if not config.has_provider:
55
+ raise BackendError("ProviderBackend requires a provider")
56
+ if config.provider == "azure":
57
+ self._model = self._build_azure(config)
58
+ else:
59
+ # Pass model + provider separately so model names containing ':'
60
+ # (e.g. bedrock 'amazon.nova-pro-v1:0') are never mis-parsed.
61
+ # An explicit per-request key (BYOK) wins over any env credential.
62
+ extra: dict = {}
63
+ if config.api_key:
64
+ extra["api_key"] = config.api_key
65
+ self._model = init_chat_model(
66
+ model=config.resolved_model,
67
+ model_provider=config.lc_provider,
68
+ temperature=0,
69
+ **extra,
70
+ )
71
+
72
+ @staticmethod
73
+ def _build_azure(config: DocConfig):
74
+ from langchain_openai import AzureChatOpenAI
75
+
76
+ from pydantic import SecretStr
77
+
78
+ raw_key = config.api_key or os.getenv("AZURE_OPENAI_API_KEY")
79
+ return AzureChatOpenAI(
80
+ azure_deployment=config.model or os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME", "gpt-4o"),
81
+ api_version=os.getenv("AZURE_OPENAI_API_VERSION", "2024-12-01-preview"),
82
+ azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
83
+ api_key=SecretStr(raw_key) if raw_key else None,
84
+ temperature=0,
85
+ )
86
+
87
+ async def complete(self, prompt: str) -> str:
88
+ result = await self._model.ainvoke(prompt)
89
+ return _content_to_text(getattr(result, "content", result))
90
+
91
+
92
+ class SamplingBackend(CompletionBackend):
93
+ """Asks the MCP host's own model to generate — zero API cost to the operator."""
94
+
95
+ def __init__(self, ctx, max_tokens: int = 4096):
96
+ self._ctx = ctx
97
+ self._max_tokens = max_tokens
98
+
99
+ async def complete(self, prompt: str) -> str:
100
+ from mcp.types import SamplingMessage, TextContent
101
+
102
+ result = await self._ctx.session.create_message(
103
+ messages=[
104
+ SamplingMessage(role="user", content=TextContent(type="text", text=prompt))
105
+ ],
106
+ max_tokens=self._max_tokens,
107
+ )
108
+ content = result.content
109
+ return content.text if getattr(content, "type", None) == "text" else str(content)
110
+
111
+
112
+ def pick_backend(config: DocConfig, ctx=None) -> CompletionBackend:
113
+ """Choose a backend: provider key → retry-wrapped ProviderBackend;
114
+ MCP host ctx → SamplingBackend; otherwise raise BackendError.
115
+ """
116
+ from .retry import with_retry
117
+
118
+ if config.has_provider:
119
+ return with_retry(ProviderBackend(config))
120
+ if ctx is not None:
121
+ return SamplingBackend(ctx)
122
+ raise BackendError(
123
+ "No LLM available. Set a provider key (ANTHROPIC_API_KEY / OPENAI_API_KEY / "
124
+ "AZURE_OPENAI_API_KEY / AWS credentials), pass provider='ollama' for a local model, "
125
+ "or run inside an MCP host that supports sampling."
126
+ )