Skip to content

Commit 5bbab84

Browse files
Dumbrisclaude
andauthored
docs: optimize CLAUDE.md by moving detailed sections to dedicated docs (smart-mcp-proxy#190)
Move large documentation sections from CLAUDE.md to dedicated files in docs/ for better maintainability and discoverability: - Move OAuth Extra Parameters (~100 lines) → docs/oauth-extra-params.md - Move Management Service Architecture (~80 lines) → docs/architecture.md - Move Tray Application Architecture (~35 lines) → docs/architecture.md - Move Runtime Architecture (~45 lines) → docs/architecture.md - Move Zero-Config OAuth (~40 lines) → docs/oauth-resource-autodetect.md - Remove stale Active Technologies section (~25 lines) CLAUDE.md reduced from ~1035 to 736 lines (~29% smaller) while preserving all information in organized documentation files. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
1 parent 6ccc07c commit 5bbab84

4 files changed

Lines changed: 350 additions & 315 deletions

File tree

CLAUDE.md

Lines changed: 17 additions & 315 deletions
Original file line numberDiff line numberDiff line change
@@ -282,40 +282,13 @@ GOOS=darwin CGO_ENABLED=1 go build -o mcpproxy-tray ./cmd/mcpproxy-tray # Tray
282282
- **Cross-platform** system tray integration
283283
- **Server management** via GUI menus
284284

285-
#### Tray Application Architecture (Refactored)
286-
287-
The tray application uses a robust state machine architecture for reliable core management:
288-
289-
**State Machine States**:
290-
- `StateInitializing``StateLaunchingCore``StateWaitingForCore``StateConnectingAPI``StateConnected`
291-
- Error states: `StateCoreErrorPortConflict`, `StateCoreErrorDBLocked`, `StateCoreErrorGeneral`, `StateCoreErrorConfig`
292-
- Recovery states: `StateReconnecting`, `StateFailed`, `StateShuttingDown`
293-
294-
**Key Components**:
295-
- **Process Monitor** (`cmd/mcpproxy-tray/internal/monitor/process.go`): Monitors core subprocess lifecycle
296-
- **Health Monitor** (`cmd/mcpproxy-tray/internal/monitor/health.go`): Performs socket-aware HTTP health checks on core API (`/healthz`, `/readyz`)
297-
- **State Machine** (`cmd/mcpproxy-tray/internal/state/machine.go`): Manages state transitions and automatic retry logic
298-
299-
**Error Classification**:
300-
Core process exit codes are mapped to specific state machine events:
301-
- Exit code 2 (port conflict) → `EventPortConflict`
302-
- Exit code 3 (database locked) → `EventDBLocked`
303-
- Exit code 4 (config error) → `EventConfigError`
304-
- Exit code 5 (permission error) → `EventPermissionError`
305-
- Other errors → `EventGeneralError`
306-
307-
**Automatic Retry Logic**:
308-
Error states automatically retry core launch with exponential backoff:
309-
- `StateCoreErrorGeneral`: 2 retries with 3s delay (3 total attempts)
310-
- `StateCoreErrorPortConflict`: 2 retries with 10s delay
311-
- `StateCoreErrorDBLocked`: 3 retries with 5s delay
312-
- After max retries exceeded → transitions to `StateFailed`
313-
- Retry count and attempts logged for transparency
314-
315-
**Development Environment Variables**:
316-
- `MCPPROXY_TRAY_SKIP_CORE=1` - Skip core launch (for development)
317-
- `MCPPROXY_CORE_URL=http://localhost:8085` - Custom core URL
318-
- `MCPPROXY_TRAY_PORT=8090` - Custom tray port
285+
#### Tray Application Architecture
286+
287+
The tray application uses a state machine architecture for reliable core management. See [docs/architecture.md](docs/architecture.md) for details on:
288+
- State machine states and transitions
289+
- Process and health monitoring
290+
- Error classification and retry logic
291+
- Development environment variables
319292

320293
## Architecture Overview
321294

@@ -371,85 +344,11 @@ Error states automatically retry core launch with exponential backoff:
371344

372345
### Management Service Architecture
373346

374-
The management service (`internal/management/`) provides a centralized business logic layer for upstream server management operations, eliminating code duplication across CLI, REST API, and MCP interfaces.
347+
The management service (`internal/management/`) provides a centralized business logic layer for upstream server management, eliminating code duplication across CLI, REST API, and MCP interfaces.
375348

376-
**Architecture Diagram**:
377-
```
378-
┌─────────────────────────────────────────────────────────────┐
379-
│ Client Interfaces │
380-
├───────────────┬─────────────────┬───────────────────────────┤
381-
│ CLI Commands │ REST API │ MCP Protocol │
382-
│ (upstream) │ (/api/v1/*) │ (upstream_servers tool) │
383-
└───────┬───────┴────────┬────────┴───────────┬───────────────┘
384-
│ │ │
385-
└────────────────┼────────────────────┘
386-
387-
388-
┌─────────────────────┐
389-
│ Management Service │
390-
│ (internal/mgmt/) │
391-
└──────────┬──────────┘
392-
393-
┌────────────────┼────────────────┐
394-
│ │ │
395-
▼ ▼ ▼
396-
┌──────────┐ ┌──────────┐ ┌──────────┐
397-
│ Runtime │ │ Config │ │ Events │
398-
│Operations│ │ Gates │ │ Emitter │
399-
└──────────┘ └──────────┘ └──────────┘
400-
```
401-
402-
**Key Components**:
403-
404-
- **Service Interface** (`service.go:16-102`): Defines all management operations
405-
- Single-server: `RestartServer()`, `EnableServer()`, `DisableServer()`
406-
- Bulk operations: `RestartAll()`, `EnableAll()`, `DisableAll()`
407-
- Diagnostics: `GetServerHealth()`, `RunDiagnostics()`
408-
- Server CRUD: `AddServer()`, `RemoveServer()`, `QuarantineServer()`
409-
- Tool operations: `GetServerTools()`, `TriggerOAuthLogin()` (added in spec 005)
410-
411-
- **Configuration Gates**: All operations respect centralized configuration guards
412-
- `disable_management`: Blocks all write operations when true
413-
- `read_only_mode`: Blocks all configuration modifications
414-
415-
- **Bulk Operations** (`service.go:243-388`): Efficient multi-server management
416-
- Sequential execution with partial failure handling
417-
- Returns `BulkOperationResult` with success/failure counts
418-
- Collects per-server errors in results map
419-
- Continues on individual failures, reports aggregate results
420-
421-
- **Event Integration**: All operations emit events through event bus
422-
- `servers.changed`: Notifies UI of server state changes
423-
- Triggers SSE updates to web UI and tray application
424-
- Enables real-time synchronization across interfaces
425-
426-
**Benefits**:
427-
- **Code Deduplication**: 40%+ reduction in duplicate code across interfaces
428-
- **Consistent Behavior**: All interfaces use identical business logic
429-
- **Centralized Validation**: Configuration gates enforced in one place
430-
- **Easier Testing**: Unit tests cover all interfaces through service layer
431-
- **Future Extensibility**: New interfaces can reuse existing service methods
432-
433-
**Usage Examples**:
434-
435-
```go
436-
// CLI usage (cmd/mcpproxy/upstream_cmd.go:547-636)
437-
result, err := client.RestartAll(ctx)
438-
fmt.Printf(" Total servers: %d\n", result.Total)
439-
fmt.Printf(" ✅ Successful: %d\n", result.Successful)
440-
fmt.Printf(" ❌ Failed: %d\n", result.Failed)
441-
442-
// REST API usage (internal/httpapi/server.go:772-866)
443-
mgmtSvc := s.controller.GetManagementService().(ManagementService)
444-
result, err := mgmtSvc.RestartAll(r.Context())
445-
s.writeSuccess(w, result)
446-
447-
// MCP protocol usage (future integration)
448-
result, err := mgmtService.RestartAll(ctx)
449-
return mcpResponse(result)
450-
```
349+
See [docs/architecture.md](docs/architecture.md) for the full architecture diagram, component details, and usage examples.
451350

452-
**OpenAPI Documentation**: All REST endpoints are documented with OpenAPI 3.1 annotations and auto-generated Swagger spec. See `oas/swagger.yaml` for complete API reference.
351+
**OpenAPI Documentation**: All REST endpoints are documented with OpenAPI 3.1 annotations. See `oas/swagger.yaml` for complete API reference.
453352

454353
### Tray-Core Communication (Unix Sockets / Named Pipes)
455354

@@ -565,144 +464,12 @@ The `working_dir` field specifies the working directory for stdio MCP servers. U
565464
- If directory doesn't exist, server startup fails with detailed error
566465
- Compatible with Docker isolation (`isolation.working_dir` for container path)
567466

568-
### Zero-Config OAuth with Resource Auto-Detection (RFC 8707/9728)
569-
570-
MCPProxy automatically detects and injects the RFC 8707 `resource` parameter for OAuth providers like Runlayer. This enables zero-configuration OAuth for servers advertising Protected Resource Metadata (RFC 9728).
571-
572-
**How it works**:
573-
1. MCPProxy sends a preflight HEAD request to the MCP server URL
574-
2. If server returns 401 with `WWW-Authenticate` header containing `resource_metadata` URL, MCPProxy fetches the Protected Resource Metadata
575-
3. The `resource` field from metadata is automatically injected into OAuth authorization URL and token requests
576-
4. If metadata doesn't contain `resource`, MCPProxy falls back to using the server URL
577-
578-
**Zero-Config Example (Runlayer)**:
579-
```json
580-
{
581-
"mcpServers": [
582-
{
583-
"name": "runlayer-slack",
584-
"url": "https://oauth.runlayer.com/api/v1/proxy/abc123def/mcp",
585-
"protocol": "http",
586-
"enabled": true
587-
// No OAuth config needed! Resource parameter auto-detected from metadata
588-
}
589-
]
590-
}
591-
```
592-
593-
**Priority Order for Resource Parameter**:
594-
1. Manual `extra_params.resource` in config (highest priority - preserves backward compatibility)
595-
2. Auto-detected resource from RFC 9728 Protected Resource Metadata
596-
3. Fallback to server URL if metadata unavailable or lacks resource field
597-
598-
**Diagnostic Commands**:
599-
```bash
600-
# View auto-detected resource parameter
601-
mcpproxy auth status --server=runlayer-slack
602-
603-
# Check for OAuth issues including resource detection
604-
mcpproxy doctor
605-
```
467+
### OAuth Configuration
606468

607-
### OAuth Extra Parameters Configuration
469+
MCPProxy supports zero-config OAuth with RFC 8707/9728 resource auto-detection for providers like Runlayer. See [docs/oauth-resource-autodetect.md](docs/oauth-resource-autodetect.md) for details.
608470

609-
MCPProxy also supports manual `extra_params` for OAuth providers requiring non-standard parameters. Manual params override auto-detected values.
471+
For manual OAuth parameter configuration, see [docs/oauth-extra-params.md](docs/oauth-extra-params.md).
610472

611-
**Use Cases**:
612-
- **RFC 8707 Resource Indicators**: Override auto-detected resource for multi-tenant authorization
613-
- **Audience-Restricted Tokens**: Request tokens for specific API audiences
614-
- **Tenant Identification**: Pass tenant/organization identifiers for multi-tenant OAuth
615-
- **Custom Provider Extensions**: Support proprietary OAuth extensions from specific providers
616-
617-
**Example 1: Runlayer MCP Server with Resource Parameter**
618-
```json
619-
{
620-
"mcpServers": [
621-
{
622-
"name": "runlayer-slack",
623-
"url": "https://oauth.runlayer.com/api/v1/proxy/abc123def/mcp",
624-
"protocol": "http",
625-
"enabled": true,
626-
"oauth": {
627-
"scopes": ["mcp"],
628-
"pkce": true,
629-
"extra_params": {
630-
"resource": "https://oauth.runlayer.com/api/v1/proxy/abc123def/mcp"
631-
}
632-
}
633-
}
634-
]
635-
}
636-
```
637-
638-
**Example 2: Multi-Tenant OAuth with Multiple Parameters**
639-
```json
640-
{
641-
"mcpServers": [
642-
{
643-
"name": "enterprise-mcp",
644-
"url": "https://api.example.com/mcp",
645-
"protocol": "http",
646-
"enabled": true,
647-
"oauth": {
648-
"scopes": ["mcp:read", "mcp:write"],
649-
"pkce": true,
650-
"extra_params": {
651-
"resource": "https://api.example.com/mcp",
652-
"audience": "mcp-api",
653-
"tenant": "org-456"
654-
}
655-
}
656-
}
657-
]
658-
}
659-
```
660-
661-
**Example 3: Azure AD with Resource Parameter**
662-
```json
663-
{
664-
"mcpServers": [
665-
{
666-
"name": "azure-mcp",
667-
"url": "https://mcp.azure.example.com/api",
668-
"protocol": "http",
669-
"enabled": true,
670-
"oauth": {
671-
"scopes": ["https://mcp.azure.example.com/.default"],
672-
"pkce": true,
673-
"authorization_url": "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/authorize",
674-
"token_url": "https://login.microsoftonline.com/tenant-id/oauth2/v2.0/token",
675-
"extra_params": {
676-
"resource": "https://mcp.azure.example.com"
677-
}
678-
}
679-
}
680-
]
681-
}
682-
```
683-
684-
**Security & Validation**:
685-
- Reserved OAuth 2.0 parameters (`client_id`, `client_secret`, `redirect_uri`, `code`, `state`, `code_verifier`, `code_challenge`, `code_challenge_method`) are **rejected** at config load time
686-
- Extra parameters are injected into all OAuth 2.0 requests: authorization, token exchange, and token refresh
687-
- Parameter values containing secrets are automatically masked in logs (see `internal/oauth/masking.go`)
688-
689-
**Debugging OAuth Extra Parameters**:
690-
```bash
691-
# View OAuth configuration including extra_params
692-
mcpproxy auth status --server=runlayer-slack
693-
694-
# Test OAuth flow with debug logging
695-
mcpproxy auth login --server=runlayer-slack --log-level=debug
696-
697-
# Check for OAuth-related issues
698-
mcpproxy doctor
699-
```
700-
701-
**Implementation Details**:
702-
- Uses HTTP `RoundTripper` wrapper pattern (RFC 2616) for transparent request interception
703-
- Zero overhead for servers without `extra_params` configured
704-
- Thread-safe concurrent OAuth flows with parameter isolation
705-
- See `internal/oauth/transport_wrapper.go` for wrapper implementation
706473

707474
## MCP Protocol Implementation
708475

@@ -915,53 +682,9 @@ mcpproxy auth login --server=Sentry --log-level=debug
915682
- File watcher triggers automatic config reloads
916683
- Validate configuration on load and provide sensible defaults
917684

918-
## Runtime Architecture (Phase 1-3 Refactoring)
919-
920-
### Runtime Package (`internal/runtime/`)
921-
922-
The runtime package provides the core non-HTTP lifecycle management, separating concerns from the HTTP server layer:
923-
924-
- **Configuration Management**: Centralized config loading, validation, and hot-reload
925-
- **Background Services**: Connection management, tool indexing, and health monitoring
926-
- **State Management**: Thread-safe status tracking and upstream server state
927-
- **Event System**: Real-time event broadcasting for UI and SSE consumers
685+
## Runtime Architecture
928686

929-
### Event Bus System
930-
931-
The event bus enables real-time communication between runtime and UI components:
932-
933-
**Event Types**:
934-
- `servers.changed` - Server configuration or state changes
935-
- `config.reloaded` - Configuration file reloaded from disk
936-
937-
**Event Flow**:
938-
1. Runtime operations trigger events via `emitServersChanged()` and `emitConfigReloaded()`
939-
2. Events are broadcast to subscribers through buffered channels
940-
3. Server forwards events to tray UI and SSE endpoints
941-
4. Tray menus refresh automatically without file watching
942-
5. Web UI receives live updates via `/events` SSE endpoint
943-
944-
**SSE Integration**:
945-
- `/events` endpoint streams both status updates and runtime events
946-
- Automatic connection management with proper cleanup
947-
- JSON-formatted event payloads for easy consumption
948-
949-
### Runtime Lifecycle
950-
951-
**Initialization**:
952-
1. Runtime created with config, logger, and manager dependencies
953-
2. Background initialization starts server connections and tool indexing
954-
3. Status updates broadcast through event system
955-
956-
**Background Services**:
957-
- **Connection Management**: Periodic reconnection attempts with exponential backoff
958-
- **Tool Indexing**: Automatic discovery and search index updates every 15 minutes
959-
- **Configuration Sync**: File-based config changes trigger runtime resync
960-
961-
**Shutdown**:
962-
- Graceful context cancellation cascades to all background services
963-
- Upstream servers disconnected with proper Docker container cleanup
964-
- Resources closed in dependency order (upstream → cache → index → storage)
687+
The runtime package (`internal/runtime/`) provides core non-HTTP lifecycle management. See [docs/architecture.md](docs/architecture.md) for details on the event bus system, lifecycle management, and background services.
965688

966689
## Important Implementation Details
967690

@@ -1009,26 +732,5 @@ The event bus enables real-time communication between runtime and UI components:
1009732
- Double shutdown protection
1010733

1011734
When making changes to this codebase, ensure you understand the modular architecture and maintain the clear separation between core protocol handling, state management, and user interface components.
1012-
- remember before running mcpproxy core u need to kill all mcpproxy instances, because it locks DB
1013-
1014-
## Active Technologies
1015-
- Go 1.21+, TypeScript/Vue 3 (003-tool-annotations-webui)
1016-
- BBolt (existing `server_{serverID}_tool_calls` buckets, new `sessions` bucket) (003-tool-annotations-webui)
1017-
- Go 1.24.0 (004-management-health-refactor)
1018-
- BBolt embedded database (`~/.mcpproxy/config.db`) for server configurations, quarantine status, and tool statistics (004-management-health-refactor)
1019-
- BBolt embedded database (`~/.mcpproxy/config.db`) - used by existing runtime, no changes required (005-rest-management-integration)
1020-
- N/A (documentation-only feature) (001-oas-endpoint-documentation)
1021-
- BBolt embedded database (`~/.mcpproxy/config.db`) - used by existing runtime for server configurations and OAuth token persistence, no schema changes required (006-oauth-extra-params)
1022-
- Go 1.24.0 (as per existing project) (007-oauth-e2e-testing)
1023-
- BBolt (existing `internal/storage/`) for token persistence (007-oauth-e2e-testing)
1024-
- Go 1.24.0 + mcp-go (OAuth transport), zap (logging), BBolt (token persistence), google/uuid (correlation IDs) (008-oauth-token-refresh)
1025-
- BBolt embedded database (`~/.mcpproxy/config.db`) - `oauth_tokens` and `oauth_completion` buckets (008-oauth-token-refresh)
1026-
- Go 1.24.0 + mcp-go (v0.43.1), zap (logging), chi (HTTP router), BBolt (storage), Vue 3 + TypeScript (frontend) (009-proactive-oauth-refresh)
1027-
- BBolt embedded database (`~/.mcpproxy/config.db`) - `oauth_tokens` bucke (009-proactive-oauth-refresh)
1028-
- Bash (GitHub Actions), Go 1.25 (existing project) + curl, jq, GitHub Actions, Anthropic Messages API (010-release-notes-generator)
1029-
- N/A (ephemeral workflow artifacts only) (010-release-notes-generator)
1030-
- Go 1.24.0 + mcp-go (OAuth transport), zap (logging), BBolt (storage) (011-resource-auto-detect)
1031-
- BBolt embedded database (`~/.mcpproxy/config.db`) for OAuth tokens (011-resource-auto-detect)
1032-
1033-
## Recent Changes
1034-
- 003-tool-annotations-webui: Added Go 1.21+, TypeScript/Vue 3
735+
736+
**Important**: Before running mcpproxy core, kill all existing mcpproxy instances as it locks the database.

0 commit comments

Comments
 (0)