From 0099692f6cad89e105c855f7dda4b976d7cbe5f2 Mon Sep 17 00:00:00 2001 From: williamkasasa Date: Fri, 3 Apr 2026 18:05:39 +0200 Subject: [PATCH 01/15] Rebrand AG-Claw explorer docs and metadata --- .vscode/mcp.json | 14 + README.md | 507 ++++++++-------------------------- mcp-server/README.md | 284 ++++--------------- mcp-server/package-lock.json | 9 +- mcp-server/package.json | 27 +- mcp-server/src/index.ts.new | 8 +- prompts/11-mcp-integration.md | 15 +- server.json | 12 +- 8 files changed, 222 insertions(+), 654 deletions(-) create mode 100644 .vscode/mcp.json diff --git a/.vscode/mcp.json b/.vscode/mcp.json new file mode 100644 index 00000000..e0841282 --- /dev/null +++ b/.vscode/mcp.json @@ -0,0 +1,14 @@ +{ + "servers": { + "agclaw-source-explorer": { + "type": "stdio", + "command": "node", + "args": [ + "D:/OneDrive - AG SOLUTION/claude-code/mcp-server/dist/src/index.js" + ], + "env": { + "AGCLAW_REFERENCE_SRC_ROOT": "D:/OneDrive - AG SOLUTION/claude-code/src" + } + } + } +} diff --git a/README.md b/README.md index 4d75bd47..9152f72a 100644 --- a/README.md +++ b/README.md @@ -1,448 +1,171 @@ -
+# AG-Claw Reference Workspace -# Claude Code — Leaked Source +This repository is the AG-Claw research workspace. It combines a clean-room backend seed, a temporary web shell, planning documents, and a non-authoritative reference runtime tree used for behavior study and migration analysis. -**The full source code of Anthropic's Claude Code CLI, leaked on March 31, 2026** +## Boundary -[![TypeScript](https://img.shields.io/badge/TypeScript-512K%2B_lines-3178C6?logo=typescript&logoColor=white)](#tech-stack) -[![Bun](https://img.shields.io/badge/Runtime-Bun-f472b6?logo=bun&logoColor=white)](#tech-stack) -[![React + Ink](https://img.shields.io/badge/UI-React_%2B_Ink-61DAFB?logo=react&logoColor=black)](#tech-stack) -[![Files](https://img.shields.io/badge/~1,900_files-source_only-grey)](#directory-structure) -[![MCP Server](https://img.shields.io/badge/MCP-Explorer_Server-blueviolet)](#-explore-with-mcp-server) -[![npm](https://img.shields.io/npm/v/warrioraashuu-codemaster?label=npm&color=cb3837&logo=npm)](https://www.npmjs.com/package/warrioraashuu-codemaster) -[![Twitter Follow](https://img.shields.io/twitter/follow/warrioraashuu?style=social)](https://twitter.com/intent/follow?screen_name=warrioraashuu) +- `backend/` is the clean-room implementation surface. +- `web/` is the temporary AG-Claw operator shell. +- root `src/` is a reference artifact for study and parity analysis, not the product foundation. +- `mcp-server/` is a research utility for browsing the reference source tree safely. -> The original unmodified leaked source is preserved in the [`backup` branch](https://github.com/codeaashu/claude-code/tree/backup). +Read these first before extending the system: -
+- `docs/agclaw-clean-room-boundary.md` +- `docs/agclaw-subsystem-migration-matrix.md` +- `docs/agclaw-replacement-backlog.md` +- `docs/agclaw-naming-inventory.md` +- `docs/agclaw-vision-runbook.md` ---- +## What Is Runnable -## Table of Contents +- `backend/`: clean-room HTTP services for chat, orchestration, provider health, and MES research flows +- `web/`: Next.js UI for local testing and operator workflows +- `mcp-server/`: MCP explorer for the reference `src/` tree +- `promptfoo/`: prompt and evaluation harness -- [How It Leaked](#how-it-leaked) -- [What Is Claude Code?](#what-is-claude-code) -- [Documentation](#-documentation) -- [Explore with MCP Server](#-explore-with-mcp-server) -- [Directory Structure](#directory-structure) -- [Architecture](#architecture) - - [Tool System](#1-tool-system) - - [Command System](#2-command-system) - - [Service Layer](#3-service-layer) - - [Bridge System](#4-bridge-system) - - [Permission System](#5-permission-system) - - [Feature Flags](#6-feature-flags) -- [Key Files](#key-files) -- [Tech Stack](#tech-stack) -- [Design Patterns](#design-patterns) -- [GitPretty Setup](#gitpretty-setup) -- [Contributing](#contributing) -- [Disclaimer](#disclaimer) +## Quick Start: See The UI ---- +Use two terminals if you want the real clean-room backend behind the temporary web shell. -## How It Leaked +Terminal A: -[Chaofan Shou (@Fried_rice)](https://x.com/Fried_rice) discovered that the published npm package for Claude Code included a `.map` file referencing the full, unobfuscated TypeScript source — downloadable as a zip from Anthropic's R2 storage bucket. - -> **"Claude code source code has been leaked via a map file in their npm registry!"** -> -> — [@Fried_rice, March 31, 2026](https://x.com/Fried_rice/status/2038894956459290963) - ---- - -## What Is Claude Code? - -Claude Code is Anthropic's official CLI tool for interacting with Claude directly from the terminal — editing files, running commands, searching codebases, managing git workflows, and more. This repository contains the leaked `src/` directory. - -| | | -|---|---| -| **Leaked** | 2026-03-31 | -| **Language** | TypeScript (strict) | -| **Runtime** | [Bun](https://bun.sh) | -| **Terminal UI** | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) | -| **Scale** | ~1,900 files · 512,000+ lines of code | - ---- - -## � Documentation - -For in-depth guides, see the [`docs/`](docs/) directory: - -| Guide | Description | -|-------|-------------| -| **[Architecture](docs/architecture.md)** | Core pipeline, startup sequence, state management, rendering, data flow | -| **[Tools Reference](docs/tools.md)** | Complete catalog of all ~40 agent tools with categories and permission model | -| **[Commands Reference](docs/commands.md)** | All ~85 slash commands organized by category | -| **[Subsystems Guide](docs/subsystems.md)** | Deep dives into Bridge, MCP, Permissions, Plugins, Skills, Tasks, Memory, Voice | -| **[Exploration Guide](docs/exploration-guide.md)** | How to navigate the codebase — study paths, grep patterns, key files | - -Also see: [CONTRIBUTING.md](CONTRIBUTING.md) · [MCP Server README](mcp-server/README.md) - ---- - -## �🔍 Explore with MCP Server - -This repo ships an [MCP server](https://modelcontextprotocol.io/) that lets any MCP-compatible client (Claude Code, Claude Desktop, VS Code Copilot, Cursor) explore the full source interactively. - -### Install from npm - -The MCP server is published as [`warrioraashuu-codemaster`](https://www.npmjs.com/package/warrioraashuu-codemaster) on npm — no need to clone the repo: - -```bash -# Claude Code -claude mcp add warrioraashuu-codemaster -- npx -y warrioraashuu-codemaster +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code" +$env:PYTHONPATH = (Resolve-Path .\backend) +python -m agclaw_backend.server --host 127.0.0.1 --port 8008 ``` -### One-liner setup (from source) +Terminal B: -```bash -git clone https://github.com/codeaashu/claude-code.git ~/claude-code \ - && cd ~/claude-code/mcp-server \ - && npm install && npm run build \ - && claude mcp add claude-code-explorer -- node ~/claude-code/mcp-server/dist/index.js +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm install +$env:AGCLAW_BACKEND_URL = "http://127.0.0.1:8008" +$env:AGCLAW_WEB_ROOT = ".." +npm run dev ``` -
-Step-by-step setup - -```bash -# 1. Clone the repo -git clone https://github.com/codeaashu/claude-code.git -cd claude-code/mcp-server - -# 2. Install & build -npm install && npm run build - -# 3. Register with Claude Code -claude mcp add claude-code-explorer -- node /absolute/path/to/claude-code/mcp-server/dist/index.js -``` +Then open `http://127.0.0.1:3000`. -Replace `/absolute/path/to/claude-code` with your actual clone path. - -
- -
-VS Code / Cursor / Claude Desktop config - -**VS Code** — add to `.vscode/mcp.json`: -```json -{ - "servers": { - "claude-code-explorer": { - "type": "stdio", - "command": "node", - "args": ["${workspaceFolder}/mcp-server/dist/index.js"], - "env": { "CLAUDE_CODE_SRC_ROOT": "${workspaceFolder}/src" } - } - } -} -``` +If you only want a fast mock-backed browser demo, skip the backend terminal and run: -**Claude Desktop** — add to your config file: -```json -{ - "mcpServers": { - "claude-code-explorer": { - "command": "node", - "args": ["/absolute/path/to/claude-code/mcp-server/dist/index.js"], - "env": { "CLAUDE_CODE_SRC_ROOT": "/absolute/path/to/claude-code/src" } - } - } -} +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm install +npm run build +node .\scripts\start-e2e-server.mjs ``` -**Cursor** — add to `~/.cursor/mcp.json` (same format as Claude Desktop). - -
- -### Available tools & prompts - -| Tool | Description | -|------|-------------| -| `list_tools` | List all ~40 agent tools with source files | -| `list_commands` | List all ~50 slash commands with source files | -| `get_tool_source` | Read full source of any tool (e.g. BashTool, FileEditTool) | -| `get_command_source` | Read source of any slash command (e.g. review, mcp) | -| `read_source_file` | Read any file from `src/` by path | -| `search_source` | Grep across the entire source tree | -| `list_directory` | Browse `src/` directories | -| `get_architecture` | High-level architecture overview | - -| Prompt | Description | -|--------|-------------| -| `explain_tool` | Deep-dive into how a specific tool works | -| `explain_command` | Understand a slash command's implementation | -| `architecture_overview` | Guided tour of the full architecture | -| `how_does_it_work` | Explain any subsystem (permissions, MCP, bridge, etc.) | -| `compare_tools` | Side-by-side comparison of two tools | +That serves the UI at `http://127.0.0.1:3100`. -**Try asking:** *"How does the BashTool work?"* · *"Search for where permissions are checked"* · *"Show me the /review command source"* +## Run The Backend -### Custom source path / Remove +PowerShell: -```bash -# Custom source location -claude mcp add claude-code-explorer -e CLAUDE_CODE_SRC_ROOT=/path/to/src -- node /path/to/mcp-server/dist/index.js - -# Remove -claude mcp remove claude-code-explorer +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code" +$env:PYTHONPATH = (Resolve-Path .\backend) +python -m agclaw_backend.server --host 127.0.0.1 --port 8008 ``` ---- - -## Directory Structure - -``` -src/ -├── main.tsx # Entrypoint — Commander.js CLI parser + React/Ink renderer -├── QueryEngine.ts # Core LLM API caller (~46K lines) -├── Tool.ts # Tool type definitions (~29K lines) -├── commands.ts # Command registry (~25K lines) -├── tools.ts # Tool registry -├── context.ts # System/user context collection -├── cost-tracker.ts # Token cost tracking -│ -├── tools/ # Agent tool implementations (~40) -├── commands/ # Slash command implementations (~50) -├── components/ # Ink UI components (~140) -├── services/ # External service integrations -├── hooks/ # React hooks (incl. permission checks) -├── types/ # TypeScript type definitions -├── utils/ # Utility functions -├── screens/ # Full-screen UIs (Doctor, REPL, Resume) -│ -├── bridge/ # IDE integration (VS Code, JetBrains) -├── coordinator/ # Multi-agent orchestration -├── plugins/ # Plugin system -├── skills/ # Skill system -├── server/ # Server mode -├── remote/ # Remote sessions -├── memdir/ # Persistent memory directory -├── tasks/ # Task management -├── state/ # State management -│ -├── voice/ # Voice input -├── vim/ # Vim mode -├── keybindings/ # Keybinding configuration -├── schemas/ # Config schemas (Zod) -├── migrations/ # Config migrations -├── entrypoints/ # Initialization logic -├── query/ # Query pipeline -├── ink/ # Ink renderer wrapper -├── buddy/ # Companion sprite (Easter egg 🐣) -├── native-ts/ # Native TypeScript utils -├── outputStyles/ # Output styling -└── upstreamproxy/ # Proxy configuration -``` +Health check: ---- - -## Architecture - -### 1. Tool System - -> `src/tools/` — Every tool Claude can invoke is a self-contained module with its own input schema, permission model, and execution logic. - -| Tool | Description | -|---|---| -| **File I/O** | | -| `FileReadTool` | Read files (images, PDFs, notebooks) | -| `FileWriteTool` | Create / overwrite files | -| `FileEditTool` | Partial modification (string replacement) | -| `NotebookEditTool` | Jupyter notebook editing | -| **Search** | | -| `GlobTool` | File pattern matching | -| `GrepTool` | ripgrep-based content search | -| `WebSearchTool` | Web search | -| `WebFetchTool` | Fetch URL content | -| **Execution** | | -| `BashTool` | Shell command execution | -| `SkillTool` | Skill execution | -| `MCPTool` | MCP server tool invocation | -| `LSPTool` | Language Server Protocol integration | -| **Agents & Teams** | | -| `AgentTool` | Sub-agent spawning | -| `SendMessageTool` | Inter-agent messaging | -| `TeamCreateTool` / `TeamDeleteTool` | Team management | -| `TaskCreateTool` / `TaskUpdateTool` | Task management | -| **Mode & State** | | -| `EnterPlanModeTool` / `ExitPlanModeTool` | Plan mode toggle | -| `EnterWorktreeTool` / `ExitWorktreeTool` | Git worktree isolation | -| `ToolSearchTool` | Deferred tool discovery | -| `SleepTool` | Proactive mode wait | -| `CronCreateTool` | Scheduled triggers | -| `RemoteTriggerTool` | Remote trigger | -| `SyntheticOutputTool` | Structured output generation | - -### 2. Command System - -> `src/commands/` — User-facing slash commands invoked with `/` in the REPL. - -| Command | Description | | Command | Description | -|---|---|---|---|---| -| `/commit` | Git commit | | `/memory` | Persistent memory | -| `/review` | Code review | | `/skills` | Skill management | -| `/compact` | Context compression | | `/tasks` | Task management | -| `/mcp` | MCP server management | | `/vim` | Vim mode toggle | -| `/config` | Settings | | `/diff` | View changes | -| `/doctor` | Environment diagnostics | | `/cost` | Check usage cost | -| `/login` / `/logout` | Auth | | `/theme` | Change theme | -| `/context` | Context visualization | | `/share` | Share session | -| `/pr_comments` | PR comments | | `/resume` | Restore session | -| `/desktop` | Desktop handoff | | `/mobile` | Mobile handoff | - -### 3. Service Layer - -> `src/services/` — External integrations and core infrastructure. - -| Service | Description | -|---|---| -| `api/` | Anthropic API client, file API, bootstrap | -| `mcp/` | Model Context Protocol connection & management | -| `oauth/` | OAuth 2.0 authentication | -| `lsp/` | Language Server Protocol manager | -| `analytics/` | GrowthBook feature flags & analytics | -| `plugins/` | Plugin loader | -| `compact/` | Conversation context compression | -| `extractMemories/` | Automatic memory extraction | -| `teamMemorySync/` | Team memory synchronization | -| `tokenEstimation.ts` | Token count estimation | -| `policyLimits/` | Organization policy limits | -| `remoteManagedSettings/` | Remote managed settings | - -### 4. Bridge System - -> `src/bridge/` — Bidirectional communication layer connecting IDE extensions (VS Code, JetBrains) with the CLI. - -Key files: `bridgeMain.ts` (main loop) · `bridgeMessaging.ts` (protocol) · `bridgePermissionCallbacks.ts` (permission callbacks) · `replBridge.ts` (REPL session) · `jwtUtils.ts` (JWT auth) · `sessionRunner.ts` (session execution) - -### 5. Permission System - -> `src/hooks/toolPermission/` — Checks permissions on every tool invocation. - -Prompts the user for approval/denial or auto-resolves based on the configured permission mode: `default`, `plan`, `bypassPermissions`, `auto`, etc. - -### 6. Feature Flags - -Dead code elimination at build time via Bun's `bun:bundle`: - -```typescript -import { feature } from 'bun:bundle' - -const voiceCommand = feature('VOICE_MODE') - ? require('./commands/voice/index.js').default - : null +```powershell +Invoke-WebRequest http://127.0.0.1:8008/health | Select-Object -Expand Content ``` -Notable flags: `PROACTIVE` · `KAIROS` · `BRIDGE_MODE` · `DAEMON` · `VOICE_MODE` · `AGENT_TRIGGERS` · `MONITOR_TOOL` - ---- - -## Key Files - -| File | Lines | Purpose | -|------|------:|---------| -| `QueryEngine.ts` | ~46K | Core LLM API engine — streaming, tool loops, thinking mode, retries, token counting | -| `Tool.ts` | ~29K | Base types/interfaces for all tools — input schemas, permissions, progress state | -| `commands.ts` | ~25K | Command registration & execution with conditional per-environment imports | -| `main.tsx` | — | CLI parser + React/Ink renderer; parallelizes MDM, keychain, and GrowthBook on startup | - ---- - -## Tech Stack - -| Category | Technology | -|---|---| -| Runtime | [Bun](https://bun.sh) | -| Language | TypeScript (strict) | -| Terminal UI | [React](https://react.dev) + [Ink](https://github.com/vadimdemedes/ink) | -| CLI Parsing | [Commander.js](https://github.com/tj/commander.js) (extra-typings) | -| Schema Validation | [Zod v4](https://zod.dev) | -| Code Search | [ripgrep](https://github.com/BurntSushi/ripgrep) (via GrepTool) | -| Protocols | [MCP SDK](https://modelcontextprotocol.io) · LSP | -| API | [Anthropic SDK](https://docs.anthropic.com) | -| Telemetry | OpenTelemetry + gRPC | -| Feature Flags | GrowthBook | -| Auth | OAuth 2.0 · JWT · macOS Keychain | - ---- +Key endpoints: -## Design Patterns +- `GET /health` +- `GET /api/provider-health` +- `POST /api/chat` +- `POST /api/orchestrate` +- `GET /api/orchestration/history` +- `POST /api/mes/retrieve` +- `POST /api/mes/log-slim` +- `POST /api/mes/interpret-screen` -
-Parallel Prefetch — Startup optimization +## Run The Web UI -MDM settings, keychain reads, and API preconnect fire in parallel as side-effects before heavy module evaluation: +PowerShell: -```typescript -// main.tsx -startMdmRawRead() -startKeychainPrefetch() +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm install +$env:AGCLAW_BACKEND_URL = "http://127.0.0.1:8008" +$env:AGCLAW_WEB_ROOT = ".." +npm run dev ``` -
+Open `http://127.0.0.1:3000`. -
-Lazy Loading — Deferred heavy modules +If you want a quick mock-backed stack for browser testing, the Playwright launcher will start the backend in mock mode automatically: -OpenTelemetry (~400KB) and gRPC (~700KB) are loaded via dynamic `import()` only when needed. - -
- -
-Agent Swarms — Multi-agent orchestration - -Sub-agents spawn via `AgentTool`, with `coordinator/` handling orchestration. `TeamCreateTool` enables team-level parallel work. - -
- -
-Skill System — Reusable workflows +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm install +npm run build +node .\scripts\start-e2e-server.mjs +``` -Defined in `skills/` and executed through `SkillTool`. Users can add custom skills. +That serves the UI at `http://127.0.0.1:3100`. -
+## Run End-To-End Tests -
-Plugin Architecture — Extensibility +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm install +npm run e2e +``` -Built-in and third-party plugins loaded through the `plugins/` subsystem. +The Playwright configuration builds the web app and launches the local mock backend automatically. -
+## Run The MCP Explorer ---- +The MCP explorer is for research against the reference `src/` tree. It is not part of the clean-room runtime. -## GitPretty Setup +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\mcp-server" +npm install +npm run build +$env:AGCLAW_REFERENCE_SRC_ROOT = (Resolve-Path ..\src) +node .\dist\src\index.js +``` -
-Show per-file emoji commit messages in GitHub's file UI +The explorer also accepts legacy `CLAUDE_CODE_SRC_ROOT` for compatibility, but new setups should use `AGCLAW_REFERENCE_SRC_ROOT`. -```bash -# Apply emoji commits -bash ./gitpretty-apply.sh . +## Validation Commands -# Optional: install hooks for future commits -bash ./gitpretty-apply.sh . --hooks +Backend: -# Push as usual -git push origin main +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code" +$env:PYTHONPATH = (Resolve-Path .\backend) +python -m unittest discover -s backend/tests ``` -
- ---- +Web: -## Contributing - -Contributions to documentation, the MCP server, and exploration tooling are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines. +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\web" +npm run build +``` -> **Note:** The `src/` directory is the original leaked source and should not be modified. +MCP explorer: ---- +```powershell +Set-Location "d:\OneDrive - AG SOLUTION\claude-code\mcp-server" +npm run build +``` -## Disclaimer +## Related Docs -This repository archives source code leaked from Anthropic's npm registry on **2026-03-31**. All original source code is the property of [Anthropic](https://www.anthropic.com). This is not an official release and is not licensed for redistribution. Contact [aashuu ✦](https://x.com/warrioraashuu) for any comments. +- `backend/README.md` for backend endpoint and benchmark details +- `mcp-server/README.md` for MCP explorer usage +- `docs/agclaw-vision-runbook.md` for screen interpretation validation +- `docs/repo-status.md` for current migration status +## Operating Rule +No new AG-Claw operator-facing surface should introduce Claude-branded product naming. Upstream provider identifiers such as `anthropic` or model ids such as `claude-sonnet-*` remain acceptable only where they describe compatibility with external APIs. diff --git a/mcp-server/README.md b/mcp-server/README.md index bcd3e3e2..96cc71d6 100644 --- a/mcp-server/README.md +++ b/mcp-server/README.md @@ -1,279 +1,113 @@ -# warrioraashuu Codemaster — MCP Server +# AG-Claw Source Explorer MCP -A standalone [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) server that lets any MCP-compatible client explore the Claude Code source code. Rebranded and published by [warrioraashuu](https://www.npmjs.com/~warrioraashuu). Supports **STDIO**, **Streamable HTTP**, and **SSE** transports. +This MCP server exposes the repository's reference `src/` tree for research and migration work. It is for source inspection and code archaeology, not for running clean-room product logic. -## What It Does +It supports `stdio`, Streamable HTTP, and legacy SSE transports. -Exposes 8 tools, 3 resources, and 5 prompts for navigating the ~1,900-file, 512K+ line Claude Code codebase. This is the official npm package: `warrioraashuu-codemaster`. +## What It Exposes -### Transports +- tools for listing commands and tools, reading source files, searching, and summarizing architecture +- resources under `agclaw-reference://...` +- prompt templates for deeper code archaeology -| Transport | Endpoint | Best For | -|-----------|----------|----------| -| **STDIO** | `node dist/index.js` | Claude Desktop, local Claude Code, VS Code | -| **Streamable HTTP** | `POST/GET /mcp` | Modern MCP clients, remote hosting | -| **Legacy SSE** | `GET /sse` + `POST /messages` | Older MCP clients | - -### Tools - -| Tool | Description | -|------|-------------| -| `list_tools` | List all 40+ agent tools (BashTool, FileEditTool, etc.) | -| `list_commands` | List all 50+ slash commands (/commit, /review, etc.) | -| `get_tool_source` | Read a specific tool's implementation | -| `get_command_source` | Read a specific command's implementation | -| `read_source_file` | Read any file from `src/` by relative path | -| `search_source` | Regex search across the entire source tree | -| `list_directory` | List contents of any directory under `src/` | -| `get_architecture` | Get a full architecture overview | - -### Resources - -| URI | Description | -|-----|-------------| -| `claude-code://architecture` | README / architecture overview | -| `claude-code://tools` | Tool registry (JSON) | -| `claude-code://commands` | Command registry (JSON) | -| `claude-code://source/{path}` | Any source file (template) | - -### Prompts - -| Prompt | Description | -|--------|-------------| -| `explain_tool` | Deep-dive explanation of a specific tool's purpose, schema, permissions, and flow | -| `explain_command` | Explanation of a specific slash command's behavior and implementation | -| `architecture_overview` | Guided tour of the full Claude Code architecture | -| `how_does_it_work` | Explain a feature/subsystem (permissions, MCP, bridge, etc.) | -| `compare_tools` | Side-by-side comparison of two tools | - -## Setup +## Quick Start ```bash cd mcp-server npm install npm run build +AGCLAW_REFERENCE_SRC_ROOT=/path/to/repo/src node dist/src/index.js ``` -### Run Locally (STDIO) - -```bash -npm start -# or with custom source path: -CLAUDE_CODE_SRC_ROOT=/path/to/src npm start -``` +Legacy `CLAUDE_CODE_SRC_ROOT` is still accepted for compatibility, but new setups should use `AGCLAW_REFERENCE_SRC_ROOT`. -### Run Locally (HTTP) +## HTTP Mode ```bash -npm run start:http -# Streamable HTTP at http://localhost:3000/mcp -# Legacy SSE at http://localhost:3000/sse -# Health check at http://localhost:3000/health +AGCLAW_REFERENCE_SRC_ROOT=/path/to/repo/src npm run start:http ``` -### With Authentication +Optional auth: ```bash -MCP_API_KEY=your-secret-token npm run start:http -# Clients must include: Authorization: Bearer your-secret-token -``` - -## Configuration - -### Claude Desktop - -Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows): - -```json -{ - "mcpServers": { - "warrioraashuu-codemaster": { - "command": "node", - "args": ["/absolute/path/to/claude-code/mcp-server/dist/index.js"], - "env": { - "CLAUDE_CODE_SRC_ROOT": "/absolute/path/to/claude-code/src" - } - } - } -} +AGCLAW_REFERENCE_SRC_ROOT=/path/to/repo/src MCP_API_KEY=your-secret-token npm run start:http ``` -### VS Code (GitHub Copilot) - -Add to `.vscode/mcp.json` in your workspace: +## Example VS Code MCP Config ```json { "servers": { - "claude-code-explorer": { + "agclaw-source-explorer": { "type": "stdio", "command": "node", - "args": ["${workspaceFolder}/mcp-server/dist/index.js"], + "args": ["${workspaceFolder}/mcp-server/dist/src/index.js"], "env": { - "CLAUDE_CODE_SRC_ROOT": "${workspaceFolder}/src" + "AGCLAW_REFERENCE_SRC_ROOT": "${workspaceFolder}/src" } } } } ``` -### Cursor - -Add to `~/.cursor/mcp.json`: - -```json -{ - "mcpServers": { - "claude-code-explorer": { - "command": "node", - "args": ["/absolute/path/to/claude-code/mcp-server/dist/index.js"], - "env": { - "CLAUDE_CODE_SRC_ROOT": "/absolute/path/to/claude-code/src" - } - } - } -} -``` +## Key Tools -## Environment Variables +- `list_tools` +- `list_commands` +- `get_tool_source` +- `get_command_source` +- `read_source_file` +- `search_source` +- `list_directory` +- `get_architecture` -| Variable | Default | Description | -|----------|---------|-------------| -| `CLAUDE_CODE_SRC_ROOT` | `../src` (relative to dist/) | Path to the Claude Code `src/` directory | -| `PORT` | `3000` | HTTP server port (HTTP mode only) | -| `MCP_API_KEY` | _(none)_ | Bearer token for HTTP auth (optional) | +## Resource URIs -## Remote HTTP Client Configuration +- `agclaw-reference://architecture` +- `agclaw-reference://tools` +- `agclaw-reference://commands` +- `agclaw-reference://source/{path}` -For Claude Desktop connecting to a remote server: +## Example Prompts -```json -{ - "mcpServers": { - "claude-code-explorer": { - "url": "https://your-deployment.railway.app/mcp", - "headers": { - "Authorization": "Bearer your-secret-key" - } - } - } -} -``` - -## Deployment - -### Railway - -1. Connect your GitHub repo to [Railway](https://railway.app) -2. Railway automatically detects the `mcp-server/Dockerfile` -3. Set environment variables in the Railway dashboard: - - `MCP_API_KEY` — a secret bearer token - - `PORT` is set automatically by Railway -4. Deploy — available at `your-app.railway.app` - -Or via CLI: - -```bash -railway init -railway up -``` - -### Vercel - -```bash -npx vercel -``` - -Set environment variables in the Vercel dashboard: -- `CLAUDE_CODE_SRC_ROOT` — path where src/ files are bundled -- `MCP_API_KEY` — bearer token - -> **Note**: Vercel functions are stateless with execution time limits (10s hobby / 60s pro). Best for simple tool calls. For persistent SSE streams, use Railway or Docker. - -### Docker - -```bash -# From repo root -docker build -f mcp-server/Dockerfile -t claude-code-mcp . -docker run -p 3000:3000 -e MCP_API_KEY=your-secret claude-code-mcp -``` - -Works on any Docker host: Fly.io, Render, AWS ECS, Google Cloud Run, etc. - -## Prompts - -The server also exposes prompt templates for guided exploration: - -| Prompt | Description | -|--------|-------------| -| `explain_tool` | Deep-dive explanation of a specific tool (input schema, permissions, execution flow) | -| `explain_command` | Explain how a slash command works | -| `architecture_overview` | Guided tour of the entire Claude Code architecture | -| `how_does_it_work` | Explain a feature or subsystem (e.g. "permission system", "MCP client", "query engine") | -| `compare_tools` | Side-by-side comparison of two tools | - -## Example Usage - -Once connected, you can ask your AI assistant things like: - -- "List all Claude Code tools" +- "List all reference tools" - "Show me the BashTool implementation" - "Search for how permissions are checked" -- "What files are in the bridge directory?" -- "Read the QueryEngine.ts file, lines 1-100" -- "How does the MCP client connection work?" -- Use the `explain_tool` prompt with "FileEditTool" to get a full breakdown -- Use `how_does_it_work` with "bridge" to understand IDE integration - -## Publishing to MCP Registry - -This server is published to the [MCP Registry](https://registry.modelcontextprotocol.io) via GitHub Actions. On a tagged release (`v*`), the workflow: - -1. Publishes the npm package to npmjs.org -2. Authenticates with the MCP Registry using GitHub OIDC -3. Publishes the `server.json` metadata to the registry - -To publish manually: - -```bash -# Install the MCP Publisher CLI -curl -L "https://github.com/modelcontextprotocol/registry/releases/latest/download/mcp-publisher_$(uname -s | tr '[:upper:]' '[:lower:]')_$(uname -m | sed 's/x86_64/amd64/;s/aarch64/arm64/').tar.gz" | tar xz mcp-publisher - -# Authenticate (GitHub OAuth) -./mcp-publisher login github +- "Explain how the bridge subsystem works" +- "Compare FileReadTool and FileEditTool" -# Publish -cd mcp-server -../mcp-publisher publish -``` +## Environment Variables -Registry name: `warrioraashuu-codemaster` +| Variable | Default | Description | +| -------- | ------- | ----------- | +| `AGCLAW_REFERENCE_SRC_ROOT` | `../src` relative to `dist/` | Path to the reference `src/` directory | +| `CLAUDE_CODE_SRC_ROOT` | none | Legacy compatibility alias | +| `PORT` | `3000` | HTTP server port | +| `MCP_API_KEY` | none | Optional bearer token for HTTP auth | ## Development ```bash npm install -npm run dev # Watch mode TypeScript compilation -npm run build # Compile TypeScript to dist/ -npm start # Run STDIO server -npm run start:http # Run HTTP server +npm run dev +npm run build +npm start +npm run start:http ``` ## Architecture -``` +```text mcp-server/ -├── src/ -│ ├── server.ts — Shared MCP server (tools, resources, prompts) — transport-agnostic -│ ├── index.ts — STDIO entrypoint (local) -│ └── http.ts — HTTP + SSE entrypoint (remote) -├── api/ -│ ├── index.ts — Vercel serverless function -│ └── vercelApp.ts — Express app for Vercel -├── Dockerfile — Docker build (Railway, Fly.io, etc.) -├── railway.json — Railway deployment config -├── package.json -└── tsconfig.json +|-- src/ +| |-- server.ts - Shared MCP server (tools, resources, prompts); transport-agnostic +| |-- index.ts - STDIO entrypoint (local) +| `-- http.ts - HTTP + SSE entrypoint (remote) +|-- api/ +| |-- index.ts - Vercel serverless function +| `-- vercelApp.ts - Express app for Vercel +|-- Dockerfile - Docker build (Railway, Fly.io, etc.) +|-- railway.json - Railway deployment config +|-- package.json +`-- tsconfig.json ``` - - diff --git a/mcp-server/package-lock.json b/mcp-server/package-lock.json index 13a95fd9..56824a10 100644 --- a/mcp-server/package-lock.json +++ b/mcp-server/package-lock.json @@ -1,18 +1,18 @@ { - "name": "warrioraashuu-codemaster", + "name": "agclaw-source-explorer", "version": "1.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "warrioraashuu-codemaster", + "name": "agclaw-source-explorer", "version": "1.1.0", "dependencies": { "@modelcontextprotocol/sdk": "^1.12.1", "express": "^4.21.0" }, "bin": { - "warrioraashuu-codemaster": "dist/index.js" + "agclaw-source-explorer": "dist/src/index.js" }, "devDependencies": { "@types/express": "^5.0.0", @@ -1260,7 +1260,6 @@ "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", "license": "MIT", - "peer": true, "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", @@ -1493,7 +1492,6 @@ "resolved": "https://registry.npmjs.org/hono/-/hono-4.12.9.tgz", "integrity": "sha512-wy3T8Zm2bsEvxKZM5w21VdHDDcwVS1yUFFY6i8UobSsKfFceT7TOwhbhfKsDyx7tYQlmRM5FLpIuYvNFyjctiA==", "license": "MIT", - "peer": true, "engines": { "node": ">=16.9.0" } @@ -2165,7 +2163,6 @@ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz", "integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==", "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/sponsors/colinhacks" } diff --git a/mcp-server/package.json b/mcp-server/package.json index 5a580b84..7e102ce4 100644 --- a/mcp-server/package.json +++ b/mcp-server/package.json @@ -1,26 +1,18 @@ { - "name": "warrioraashuu-codemaster", + "name": "agclaw-source-explorer", "version": "1.1.0", - "mcpName": "io.github.warrioraashuu/warrioraashuu-codemaster", - "description": "MCP server for exploring the Claude Code source code — rebranded and published by warrioraashuu. STDIO, HTTP, and SSE transports.", - "repository": { - "type": "git", - "url": "https://github.com/codeaashu/claude-code.git" - }, + "mcpName": "io.github.williamkasasa/agclaw-source-explorer", + "description": "AG-Claw source explorer MCP server for local research workspaces.", "author": "warrioraashuu ", - "homepage": "https://github.com/codeaashu/claude-code#readme", - "bugs": { - "url": "https://github.com/codeaashu/claude-code/issues" - }, "type": "module", - "main": "dist/index.js", + "main": "dist/src/index.js", "bin": { - "warrioraashuu-codemaster": "dist/index.js" + "agclaw-source-explorer": "dist/src/index.js" }, "scripts": { "build": "tsc", - "start": "node dist/index.js", - "start:http": "node dist/http.js", + "start": "node dist/src/index.js", + "start:http": "node dist/src/http.js", "dev": "npx tsx src/index.ts" }, "dependencies": { @@ -32,7 +24,6 @@ "@types/node": "^22.0.0", "tsx": "^4.19.0", "typescript": "^5.7.0" - } + }, + "private": true } - - diff --git a/mcp-server/src/index.ts.new b/mcp-server/src/index.ts.new index b49f61cf..45110460 100644 --- a/mcp-server/src/index.ts.new +++ b/mcp-server/src/index.ts.new @@ -1,10 +1,10 @@ #!/usr/bin/env node /** - * STDIO entrypoint — for local use with Claude Desktop, Claude Code, etc. + * STDIO entrypoint for local MCP clients. * * Usage: - * node dist/index.js - * CLAUDE_CODE_SRC_ROOT=/path/to/src node dist/index.js + * node dist/src/index.js + * AGCLAW_REFERENCE_SRC_ROOT=/path/to/src node dist/src/index.js */ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; @@ -15,7 +15,7 @@ async function main() { const server = createServer(); const transport = new StdioServerTransport(); await server.connect(transport); - console.error(`Claude Code Explorer MCP (stdio) started — src: ${SRC_ROOT}`); + console.error(`AG-Claw Source Explorer MCP (stdio) started — src: ${SRC_ROOT}`); } main().catch((err) => { diff --git a/prompts/11-mcp-integration.md b/prompts/11-mcp-integration.md index 857e57d7..93c5eb9e 100644 --- a/prompts/11-mcp-integration.md +++ b/prompts/11-mcp-integration.md @@ -3,6 +3,7 @@ ## Context You are working in `/workspaces/claude-code`. The CLI has built-in MCP (Model Context Protocol) support: + - **MCP Client** — connects to external MCP servers (tools, resources) - **MCP Server** — exposes Claude Code itself as an MCP server @@ -24,6 +25,7 @@ MCP lets the CLI use tools provided by external servers and lets other clients u ### Part A: Understand MCP client architecture Read `src/services/mcp/` directory: + 1. How are MCP servers discovered? (`.mcp.json` config file?) 2. How are MCP server connections established? (stdio, HTTP, SSE?) 3. How are MCP tools registered and made available? @@ -32,11 +34,13 @@ Read `src/services/mcp/` directory: ### Part B: Understand MCP config format Search for `.mcp.json` or MCP config loading code. Document: + 1. Where does the config file live? (`~/.claude/.mcp.json`? project root?) 2. What's the config schema? (server name, command, args, env?) 3. How are multiple servers configured? Example config you might find: + ```json { "mcpServers": { @@ -52,6 +56,7 @@ Example config you might find: ### Part C: Verify MCP SDK integration The project uses `@modelcontextprotocol/sdk` (^1.12.1). Check: + 1. Is it installed in `node_modules/`? 2. Does the import work: `import { Client } from '@modelcontextprotocol/sdk/client/index.js'` 3. Are there version compatibility issues? @@ -59,12 +64,14 @@ The project uses `@modelcontextprotocol/sdk` (^1.12.1). Check: ### Part D: Test MCP client with our own server Create a test that: + 1. Starts the `mcp-server/` we fixed in Prompt 04 as a child process 2. Connects to it via stdio using the MCP client from `src/services/mcp/` 3. Lists available tools 4. Calls one tool (e.g., `list_files` or `search_code`) Create `scripts/test-mcp.ts`: + ```ts // scripts/test-mcp.ts // Test MCP client/server roundtrip @@ -84,6 +91,7 @@ import './src/shims/preload.js' ### Part E: Test MCP server mode The CLI can run as an MCP server itself (`src/entrypoints/mcp.ts`). Read this file and verify: + 1. What tools does it expose? 2. What resources does it provide? 3. Can it be started with `bun src/entrypoints/mcp.ts`? @@ -91,14 +99,15 @@ The CLI can run as an MCP server itself (`src/entrypoints/mcp.ts`). Read this fi ### Part F: Create sample MCP config Create a `.mcp.json` in the project root (or wherever the app looks for it) that configures the local MCP server: + ```json { "mcpServers": { - "claude-code-explorer": { + "agclaw-source-explorer": { "command": "node", - "args": ["mcp-server/dist/index.js"], + "args": ["mcp-server/dist/src/index.js"], "env": { - "CLAUDE_CODE_SRC_ROOT": "./src" + "AGCLAW_REFERENCE_SRC_ROOT": "./src" } } } diff --git a/server.json b/server.json index 14f86fbd..5dbb52c3 100644 --- a/server.json +++ b/server.json @@ -1,10 +1,10 @@ -cl{ +{ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", - "name": "warrioraashuu-codemaster", - "title": "Claude Code Explorer MCP", - "description": "Explore the Claude Code CLI source — browse tools, commands, search the 512K-line codebase.", + "name": "agclaw-source-explorer", + "title": "AG-Claw Source Explorer MCP", + "description": "Inspect the AG-Claw reference source tree for research, migration planning, and clean-room analysis.", "repository": { - "url": "https://github.com/codeaashu/claude-code", + "url": "https://github.com/williamkasasa/claude-code", "source": "github", "subfolder": "mcp-server" }, @@ -13,7 +13,7 @@ cl{ { "registryType": "npm", "registryBaseUrl": "https://registry.npmjs.org", - "identifier": "warrioraashuu-codemaster", + "identifier": "agclaw-source-explorer", "version": "1.1.0", "transport": { "type": "stdio" From 430393bbf66623fc58fa3c6c906f01940737ab10 Mon Sep 17 00:00:00 2001 From: williamkasasa Date: Fri, 3 Apr 2026 18:31:06 +0200 Subject: [PATCH 02/15] Fix web accessibility markup and TS config --- tsconfig.json | 1 - web/components/chat/ChatInput.tsx | 41 ++++- web/components/chat/ChatWindow.tsx | 28 ++- web/components/settings/ApiSettings.tsx | 160 +++++++++++++----- web/components/settings/McpSettings.tsx | 25 ++- web/components/settings/ModelSettings.tsx | 48 +++--- .../settings/PermissionSettings.tsx | 10 +- web/components/ui/input.tsx | 6 +- web/components/ui/textarea.tsx | 6 +- web/tsconfig.json | 22 ++- 10 files changed, 245 insertions(+), 102 deletions(-) diff --git a/tsconfig.json b/tsconfig.json index 17f0157c..78144f42 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,7 +16,6 @@ "verbatimModuleSyntax": false, "lib": ["ESNext"], "types": ["node"], - "baseUrl": ".", "paths": { "bun:bundle": ["./src/types/bun-bundle.d.ts"] } diff --git a/web/components/chat/ChatInput.tsx b/web/components/chat/ChatInput.tsx index 5f5c47a0..8033fc17 100644 --- a/web/components/chat/ChatInput.tsx +++ b/web/components/chat/ChatInput.tsx @@ -1,4 +1,4 @@ -"use client"; +"use client"; import { useState, useRef, useCallback } from "react"; import { Send, Square, Paperclip } from "lucide-react"; @@ -55,7 +55,20 @@ export function ChatInput({ conversationId }: ChatInputProps) { let fullText = ""; try { - for await (const chunk of streamChat(messages, settings.model, controller.signal)) { + for await (const chunk of streamChat( + messages, + settings.model, + { + provider: settings.provider, + apiUrl: settings.apiUrl, + apiKey: settings.apiKey, + streamingEnabled: settings.streamingEnabled, + systemPrompt: settings.systemPrompt, + temperature: settings.temperature, + maxTokens: settings.maxTokens, + }, + controller.signal + )) { if (chunk.type === "text" && chunk.content) { fullText += chunk.content; updateMessage(conversationId, assistantId, { @@ -87,7 +100,22 @@ export function ChatInput({ conversationId }: ChatInputProps) { setIsStreaming(false); abortRef.current = null; } - }, [input, isStreaming, conversationId, conversation, settings.model, addMessage, updateMessage]); + }, [ + input, + isStreaming, + conversationId, + conversation, + settings.model, + settings.provider, + settings.apiUrl, + settings.apiKey, + settings.streamingEnabled, + settings.systemPrompt, + settings.temperature, + settings.maxTokens, + addMessage, + updateMessage, + ]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Enter" && !e.shiftKey) { @@ -135,7 +163,7 @@ export function ChatInput({ conversationId }: ChatInputProps) { adjustHeight(); }} onKeyDown={handleKeyDown} - placeholder="Message Claude Code..." + placeholder="Message AG-Claw..." rows={1} aria-label="Message" className={cn( @@ -158,7 +186,6 @@ export function ChatInput({ conversationId }: ChatInputProps) { onClick={handleSubmit} disabled={!input.trim()} aria-label="Send message" - aria-disabled={!input.trim()} className={cn( "p-1.5 rounded-lg transition-colors flex-shrink-0", input.trim() @@ -172,9 +199,11 @@ export function ChatInput({ conversationId }: ChatInputProps) {

- Claude can make mistakes. Verify important information. + AG-Claw can make mistakes. Verify important information.

); } + + diff --git a/web/components/chat/ChatWindow.tsx b/web/components/chat/ChatWindow.tsx index fc7c841f..adf126fb 100644 --- a/web/components/chat/ChatWindow.tsx +++ b/web/components/chat/ChatWindow.tsx @@ -1,6 +1,6 @@ -"use client"; +"use client"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { useChatStore } from "@/lib/store"; import { MessageBubble } from "./MessageBubble"; import { Bot } from "lucide-react"; @@ -13,7 +13,7 @@ export function ChatWindow({ conversationId }: ChatWindowProps) { const bottomRef = useRef(null); const { conversations } = useChatStore(); const conversation = conversations.find((c) => c.id === conversationId); - const messages = conversation?.messages ?? []; + const messages = useMemo(() => conversation?.messages ?? [], [conversation]); const isStreaming = messages.some((m) => m.status === "streaming"); @@ -33,7 +33,7 @@ export function ChatWindow({ conversationId }: ChatWindowProps) { // Announce a short preview so screen reader users know a reply arrived const preview = lastMsg.content.slice(0, 100); setAnnouncement(""); - setTimeout(() => setAnnouncement(`Claude replied: ${preview}`), 50); + setTimeout(() => setAnnouncement(`AG-Claw replied: ${preview}`), 50); } prevLengthRef.current = messages.length; }, [messages.length, messages]); @@ -50,7 +50,7 @@ export function ChatWindow({ conversationId }: ChatWindowProps) {

How can I help?

- Start a conversation with Claude Code + Start a conversation with AG-Claw

@@ -60,25 +60,14 @@ export function ChatWindow({ conversationId }: ChatWindowProps) { return (
- {/* Polite live region — announces when Claude finishes a reply */} + {/* Polite live region announces when AG-Claw finishes a reply. */}
{announcement}
@@ -92,3 +81,6 @@ export function ChatWindow({ conversationId }: ChatWindowProps) {
); } + + + diff --git a/web/components/settings/ApiSettings.tsx b/web/components/settings/ApiSettings.tsx index 78ee92f3..f484590f 100644 --- a/web/components/settings/ApiSettings.tsx +++ b/web/components/settings/ApiSettings.tsx @@ -1,44 +1,85 @@ "use client"; -import { useState } from "react"; +import { useMemo, useState } from "react"; import { Eye, EyeOff, CheckCircle, XCircle, Loader2 } from "lucide-react"; import { useChatStore } from "@/lib/store"; +import { + DEFAULT_PROVIDER_URLS, + PROVIDERS, + getDefaultModelForProvider, + isLocalProvider, +} from "@/lib/constants"; +import type { ChatProvider } from "@/lib/types"; import { SettingRow, SectionHeader, Toggle } from "./SettingRow"; import { cn } from "@/lib/utils"; type ConnectionStatus = "idle" | "checking" | "ok" | "error"; +function getKeyPlaceholder(provider: ChatProvider) { + switch (provider) { + case "anthropic": + return "sk-ant-..."; + case "ollama": + return "Optional for proxied Ollama"; + default: + return "Optional bearer token"; + } +} + export function ApiSettings() { const { settings, updateSettings, resetSettings } = useChatStore(); const [showKey, setShowKey] = useState(false); const [connectionStatus, setConnectionStatus] = useState("idle"); const [latencyMs, setLatencyMs] = useState(null); + const selectedProvider = useMemo( + () => PROVIDERS.find((provider) => provider.id === settings.provider), + [settings.provider] + ); async function checkConnection() { setConnectionStatus("checking"); setLatencyMs(null); const start = Date.now(); try { - const res = await fetch(`${settings.apiUrl}/health`, { signal: AbortSignal.timeout(5000) }); - const ms = Date.now() - start; - setLatencyMs(ms); - setConnectionStatus(res.ok ? "ok" : "error"); + const params = new URLSearchParams({ + provider: settings.provider, + apiUrl: settings.apiUrl, + }); + if (settings.apiKey) { + params.set("apiKey", settings.apiKey); + } + const response = await fetch(`/api/provider-health?${params.toString()}`, { + signal: AbortSignal.timeout(5000), + }); + setLatencyMs(Date.now() - start); + setConnectionStatus(response.ok ? "ok" : "error"); } catch { setConnectionStatus("error"); } } + function handleProviderChange(provider: ChatProvider) { + updateSettings({ + provider, + localMode: isLocalProvider(provider), + apiUrl: DEFAULT_PROVIDER_URLS[provider], + model: getDefaultModelForProvider(provider), + }); + setConnectionStatus("idle"); + setLatencyMs(null); + } + const statusIcon = { idle: null, - checking: , - ok: , - error: , + checking: , + ok: , + error: , }[connectionStatus]; const statusText = { idle: "Not checked", checking: "Checking...", - ok: latencyMs !== null ? `Connected — ${latencyMs}ms` : "Connected", + ok: latencyMs !== null ? `Connected - ${latencyMs}ms` : "Connected", error: "Connection failed", }[connectionStatus]; @@ -46,9 +87,58 @@ export function ApiSettings() {
resetSettings("api")} /> + + { + const provider = checked ? "ollama" : "anthropic"; + updateSettings({ + localMode: checked, + provider, + apiUrl: DEFAULT_PROVIDER_URLS[provider], + model: getDefaultModelForProvider(provider), + }); + setConnectionStatus("idle"); + setLatencyMs(null); + }} + /> + + + + + {selectedProvider && ( +

{selectedProvider.description}

+ )} +
+
@@ -56,53 +146,45 @@ export function ApiSettings() { updateSettings({ apiKey: e.target.value })} - placeholder="sk-ant-..." + onChange={(event) => updateSettings({ apiKey: event.target.value })} + placeholder={getKeyPlaceholder(settings.provider)} + aria-label="API key" className={cn( - "w-full bg-surface-800 border border-surface-700 rounded-md px-3 py-1.5 pr-10 text-sm", + "w-full rounded-md border border-surface-700 bg-surface-800 px-3 py-1.5 pr-10 text-sm", "text-surface-200 placeholder-surface-600 focus:outline-none focus:ring-1 focus:ring-brand-500 font-mono" )} />
- {settings.apiKey && ( -

- Key ending in{" "} - - ...{settings.apiKey.slice(-4)} - -

- )} updateSettings({ apiUrl: e.target.value })} - placeholder="http://localhost:3001" + onChange={(event) => updateSettings({ apiUrl: event.target.value })} + placeholder={DEFAULT_PROVIDER_URLS[settings.provider]} + aria-label="API base URL" className={cn( - "w-full bg-surface-800 border border-surface-700 rounded-md px-3 py-1.5 text-sm", + "w-full rounded-md border border-surface-700 bg-surface-800 px-3 py-1.5 text-sm", "text-surface-200 placeholder-surface-600 focus:outline-none focus:ring-1 focus:ring-brand-500 font-mono" )} /> - +
{statusIcon} @@ -121,10 +203,11 @@ export function ApiSettings() {
- + updateSettings({ streamingEnabled: v })} + onChange={(value) => updateSettings({ streamingEnabled: value })} />
diff --git a/web/components/settings/McpSettings.tsx b/web/components/settings/McpSettings.tsx index a8fc415a..e3c44f6b 100644 --- a/web/components/settings/McpSettings.tsx +++ b/web/components/settings/McpSettings.tsx @@ -1,4 +1,4 @@ -"use client"; +"use client"; import { useState } from "react"; import { @@ -32,7 +32,7 @@ function ServerRow({ async function testConnection() { setTestStatus("testing"); - // Simulate connection test — in real impl this would call an API + // Simulate connection test — in real impl this would call an API await new Promise((r) => setTimeout(r, 800)); setTestStatus(Math.random() > 0.3 ? "ok" : "error"); } @@ -61,12 +61,18 @@ function ServerRow({