Files
chatgpt-mcp/PROJECT_STATE.md
T

251 lines
13 KiB
Markdown

# PROJECT_STATE.md
## Project
ChatGPT MCP Server
## Status
Planning complete. Phase 0 complete. Phase 1 complete. Phase 2 complete. Phase 3 complete. Phase 4 complete. Task 5.1 complete. Task 5.2 complete. Task 5.3 complete. Task 5.4 complete. Task 5.5 complete. Phase 6 complete. Phase 7 complete. Phase 8 complete (Task 8.0 — Manual Export Provider). Phase 9 complete (Task 9.1 — Ollama Provider).
## Current Phase
All planned phases complete. Provider abstraction (Phase 6), integration tests (Phase 7), manual export provider (Phase 8), and Ollama provider (Phase 9) finished. **3 supported providers: openai, manual, ollama.**
## Completed Tasks
- Task 0.1 — Create repository skeleton ✅
- Task 0.2 — package.json with dependencies ✅
- Task 1.1 — Configuration loader ✅
- Task 1.2 — Secret redaction utility (`src/utils/redact.js`) ✅
- Task 1.3 — Context budget utility (`src/utils/context-budget.js`) ✅
- Task 1.4 — Safe logging helper (`src/utils/logging.js`) ✅
- Task 2.1 — OpenAI client wrapper (`src/openai/client.js`) ✅
- Task 2.2 — Response builder (`src/openai/responses.js`) ✅
- Task 2.3 — Error handling and edge cases for OpenAI integration (tests) ✅
- Task 3.1 — Zod input validation schemas (`src/tools/schemas.js`, `test/tools/schemas.test.js`) ✅
- Task 3.2 — Base prompt template (`src/prompts/base.js`, `test/prompts/base.test.js`) ✅
- Task 3.3 — ask_chatgpt prompt builder (`src/prompts/ask-chatgpt.js`, `test/prompts/ask-chatgpt.test.js`) ✅
- Task 3.4 — review_plan prompt builder (`src/prompts/review-plan.js`, `test/prompts/review-plan.test.js`) ✅
- Task 3.5 — review_code prompt builder (`src/prompts/review-code.js`, `test/prompts/review-code.test.js`) ✅
- Task 3.6 — debug_issue prompt builder (`src/prompts/debug-issue.js`, `test/prompts/debug-issue.test.js`) ✅
- Task 3.7 — architecture_review prompt builder (`src/prompts/architecture-review.js`, `test/prompts/architecture-review.test.js`) ✅
- Task 4.1 — ask_chatgpt MCP tool handler (`src/tools/ask-chatgpt.js`, `test/tools/ask-chatgpt.test.js`) ✅
- Task 4.2 — review_plan MCP tool handler (`src/tools/review-plan.js`, `test/tools/review-plan.test.js`) ✅
- Task 4.3 — review_code MCP tool handler (`src/tools/review-code.js`, `test/tools/review-code.test.js`) ✅
- Task 4.4 — debug_issue tool handler (`src/tools/debug-issue.js`, `test/tools/debug-issue.test.js`) ✅
- Task 4.5 — architecture_review tool handler (`src/tools/architecture-review.js`, `test/tools/architecture-review.test.js`) ✅
- Task 5.1 — MCP server skeleton (`src/server.js`) ✅
- Task 5.2 — ask_chatgpt MCP tool registered on the server ✅
**ask_chatgpt registration details:**
- `src/server.js` registers `ask_chatgpt` with `registerTool()` using the shared `baseInputSchema`.
- All three external deps injected: `loadConfig`, `createOpenAIClient`, `sendOpenAIResponse`.
- Returns structured MCP tool result: `{ content: [{ type: "text", text }], isError, warnings }`.
**Smoke test results (all passing):**
- initialize → server returns `chatgpt-mcp` v0.1.0 ✅
- tools/list → exposes `ask_chatgpt` with correct schema (`question` required + 7 optional) ✅
- tools/call (happy path, mocked OpenAI) → `{ content: [...], isError: false }` with answer ✅
- tools/call (minimal input `{ question: "hi" }`) → works ✅
- tools/call (full input, all 10 schema fields) → handled correctly ✅
- tools/call (missing OPENAI_API_KEY) → structured MCP error `"Error: Configuration error: OPENAI_API_KEY is missing."`
- tools/call (invalid API key) → structured MCP error `"OpenAI API error (OpenAIAuthError): 401"`
- All 523 unit tests pass across 18 test files ✅
- Task 5.3 — Register remaining MCP tools ✅
**Registered tools:**
- `review_plan` → handleReviewPlan
- `review_code` → handleReviewCode
- `debug_issue` → handleDebugIssue
- `architecture_review` → handleArchitectureReview
**All five MCP tools now registered:** ask_chatgpt, review_plan, review_code, debug_issue, architecture_review.
**Smoke test results (all passing):**
- initialize → server returns `chatgpt-mcp` v0.1.0 ✅
- tools/list → 5 tools total ✅
- tools/call reaches handlers for all 5 tools ✅
- missing OPENAI_API_KEY → structured tool errors (`"Error: Configuration error: OPENAI_API_KEY is missing."`) ✅
- npm test → 523 tests pass across 18 test files, no regressions ✅
- Task 5.4 — Normalize MCP tool error formatting ✅
MCP tool error formatting normalized in `src/server.js`. All 5 tools now produce a single "Error:" prefix with no duplicates.
- Task 5.5 — Claude Code MCP configuration and local end-to-end setup ✅
Project-local Claude Code discovery configured:
- Task 6.1 — Provider abstraction factory (`src/providers/factory.js`, `test/providers/factory.test.js`) ✅
**What it provides:**
- `createChatProvider(config)` returns the configured chat provider (currently only `"openai"`)
- Factory validates provider name against whitelist; defaults to `"openai"` for any falsy/unknown value
- All tool handlers receive `{ loadConfig, createProvider }` via dependency injection instead of `{ createOpenAIClient, sendOpenAIResponse }`
- Task 6.2 — OpenAI provider adapter (`src/providers/openai.js`, `test/providers/openai.test.js`) ✅
**What it provides:**
- `openaiProvider.send(input, config)` thin interface wrapping existing OpenAI modules
- Internally calls `createOpenAIClient(config)``sendOpenAIResponse(client, { input: [{ role: "system", content }], model, temperature, maxOutputTokens })`
- Task 7.1 — Update all tool handlers to use provider abstraction ✅
All five handler files updated:
- `src/tools/ask-chatgpt.js` — uses `deps.createProvider(config)` + `provider.send()`
- `src/tools/review-plan.js` — same
- `src/tools/review-code.js` — same
- `src/tools/debug-issue.js` — same
- `src/tools/architecture-review.js` — same
- Task 7.2 — Update handler tests to use provider mock pattern ✅
All five handler test files rewritten with `{ loadConfig, createProvider }` mock pattern:
- `test/tools/ask-chatgpt.test.js` — 27 tests
- `test/tools/review-plan.test.js` — 28 tests
- `test/tools/review-code.test.js` — 28 tests
- `test/tools/debug-issue.test.js` — 28 tests
- `test/tools/architecture-review.test.js` — 28 tests
- Task 7.3 — Config and provider test coverage ✅
- `test/config/env.test.js` — added chatgptMcpProvider env var tests (default "openai", accepts any string)
- Provider factory tests validate whitelist enforcement, case sensitivity, edge cases (null, NaN, whitespace, JSON strings, mutations)
- Task 7.4 — Final integration verification ✅
- All 579 tests pass across 20 test files with zero regressions
- `npm start` → tools/list shows same 5 tools with unchanged schemas
- Task 8.0 — Implement ReviewRequest and Manual Export Provider ✅
**Provider implementation:**
- `src/providers/manual-export.js` — Zero-API-cost provider that wraps pre-built prompts in copy/paste-ready format
- Returns `{ content: string }` via `send(reviewRequest, config)`
- Uses `https://chatgpt.com` (never `https://chat.openai.com`)
- Detects tool name from input fields for metadata
- Warns on prompts over 30k characters
- Preserves unicode, markdown, code blocks, and special characters exactly
**Factory integration:**
- `"manual"` added to SUPPORTED_PROVIDERS whitelist in `src/providers/factory.js`
- `CHATGPT_MCP_PROVIDER=manual` switches all tool handlers to manual export mode
- Defaults to `"openai"` when not set — OpenAI behaviour unchanged
**Tests:** 56 new tests in `test/providers/manual-export.test.js` + 9 new in `test/providers/factory.test.js`
- Total: 644 passing tests across 21 test files, zero regressions
- `.claude/` added to `.gitignore` (no machine-specific paths committed)
- Task 9.1 — Ollama Provider Implementation ✅
**Provider implementation:**
- `src/providers/ollama.js` — Local AI provider using Ollama `/api/chat` endpoint via native `fetch()` (zero new dependencies)
- Implements `{ send(request, config) => Promise<{ content: string }> }` interface
- Returns structured advisory responses from local LLM
- Error categories: `OllamaTimeoutError`, `OllamaModelNotFoundError`, `OllamaValidationError`, `OllamaApiNotAvailableError`, `OllamaRequestError`
**Defaults:**
- Base URL: `http://localhost:11434`
- Model: `qwen3:latest`
- Temperature: `0.2`
- Timeout: `60` seconds
**Environment variables:**
- `OLLAMA_BASE_URL` — Ollama API endpoint (default: `http://localhost:11434`)
- `OLLAMA_MODEL` — Model name (default: `qwen3:latest`)
- `OLLAMA_TEMPERATURE` — Sampling temperature (default: `0.2`)
- `OLLAMA_TIMEOUT` — Request timeout in seconds (default: `60`)
**Factory integration:**
- `"ollama"` added to SUPPORTED_PROVIDERS whitelist alongside `"openai"` and `"manual"`
- `CHATGPT_MCP_PROVIDER=ollama` switches all tool handlers to local Ollama mode
- Defaults to `"openai"` when not set — OpenAI behaviour unchanged
- Same provider interface as openai and manual providers
## Phase 9 Completion Summary — Ollama Provider ✅
Three providers now supported: `openai`, `manual`, `ollama`.
- Factory in `src/providers/factory.js`: `SUPPORTED_PROVIDERS = Set(["openai", "manual", "ollama"])`
- All three providers implement `{ send(request, config) => Promise<{ content: string }> }`
- Provider selection via `CHATGPT_MCP_PROVIDER` environment variable
- Zero additional dependencies — Ollama provider uses native `fetch()` only
## Next Pending
- README.md updated with Setup, MCP Tools, and Running sections
- MCP config snippet uses `"command": "npm"`, `"args": ["start"]` — no absolute paths
- All 5 tools documented in README
## Phase 3 Completion Summary
Phase 3 — Tool Inputs and Prompts — is now complete.
**Completed prompt builders:**
- `buildBasePrompt` — base system prompt (ARCHITECTURE.md §11)
- `buildAskChatGptPrompt` — general second-opinion advisor
- `buildReviewPlanPrompt` — plan review before implementation
- `buildReviewCodePrompt` — focused code/diff review
- `buildDebugIssuePrompt` — error/log/stack trace analysis
- `buildArchitectureReviewPrompt` — architecture decision trade-off review
**What Phase 3 established:**
- Prompt layer complete with composition pattern established.
- All prompt builders tested (56 tests for architecture-review alone; 384 total).
- Each builder follows the same pattern: `buildBasePrompt()``\n\n---\n\n` → tool-specific section.
- Guard rails reinforced in every builder (Claude Code is executor; ChatGPT is advisory only).
**Not done yet (belongs to Phase 4):**
- No MCP tool registration.
- No tool handlers.
## Phase 4 Completion Summary — Tool Handlers ✅
All five tool handlers are implemented and tested:
| # | Handler | File | Tests |
|---|---------|------|-------|
| 1 | `handleAskChatGpt` | `src/tools/ask-chatgpt.js` | ✅ 27 |
| 2 | `handleReviewPlan` | `src/tools/review-plan.js` | ✅ 28 |
| 3 | `handleReviewCode` | `src/tools/review-code.js` | ✅ 28 |
| 4 | `handleDebugIssue` | `src/tools/debug-issue.js` | ✅ 28 |
| 5 | `handleArchitectureReview` | `src/tools/architecture-review.js` | ✅ 28 |
**What Phase 4 established:**
- Five standalone, dependency-injected handlers following the same orchestration pattern: validate → config → budget → prompt → client → response.
- All external deps injected (loadConfig, createOpenAIClient, sendOpenAIResponse); internal utilities imported directly.
- Every handler returns structured `{ ok, answer|error, warnings }` — never throws to caller.
- Budget check short-circuits before prompt building or client creation.
- OpenAI errors pass through `String(err)` unchanged — no wrapping or reformatting.
- 139 orchestration-only tests covering success, validation failure, config failure, budget failure, client failure, OpenAI failure, call order, prompt integration, throws escaping, warnings, result shape, and short-circuit behavior.
**What Phase 4 did NOT do:**
- No MCP tool registration yet.
- No server or router code yet.
- That belongs to Phase 5.
## Phase 6 Completion Summary — Provider Abstraction ✅
Provider abstraction layer decouples tool handlers from OpenAI implementation:
- `createChatProvider(config)` factory in `src/providers/factory.js` with whitelist validation
- `openaiProvider.send(input, config)` thin adapter in `src/providers/openai.js`
- All 5 handlers now use `{ loadConfig, createProvider }` dependency injection
- Factory defaults to `"openai"` for any falsy/invalid provider name (null, NaN, numeric)
- Zero changes needed to handler logic — only interface change from direct OpenAI calls to provider abstraction
## Phase 7 Completion Summary — Tests ✅
All tests rewritten and verified:
- 644 passing tests across 21 test files (Phase 8 added 65 tests; Phase 9 has no new tests yet)
- Provider/config tests in factory.test.js, openai.test.js, env.test.js, manual-export.test.js
- All handler tests use `{ loadConfig, createProvider }` mock pattern
- `npm start` → tools/list shows identical 5 tools with unchanged schemas
## Next Pending
No pending tasks. MVP is complete. Future work roadmap: Anthropic provider, streaming responses, response caching, structured output parsing, cost tracking per tool call.